Zero to Python Hero - Part 2/10 : Understanding Python Variables, Data Types (with Code Examples)
Naveen
- 0

Learning Python can feel overwhelming when you’re starting from scratch. I discovered this firsthand while researching about the Python resources online. As I went through countless tutorials, documentation pages, and coding platforms, I realized a frustrating truth: beginners often have to jump between multiple websites, books, and resources just to understand the basics. Even worse, many newcomers don’t know what topics they should learn first or in what order.
This scattered approach to learning Python creates unnecessary confusion and can discourage beginners before they even write their first line of code. That’s why I decided to create this comprehensive guide.
In this article I’ll try to provide everything a complete beginner needs to start their Python journey in one place, presented in a logical, easy-to-follow sequence.
This article is the second in a series of 10 carefully crafted guides that will take you from absolute beginner to confident Python programmer. Each article builds upon the previous one, ensuring you develop a solid foundation without gaps in your knowledge.
By the end of this article, you’ll have a solid understanding of Python’s core concepts and be ready to start building simple programs. No more jumping between different resources or wondering what to learn next — everything you need is right here.
So, Let’s start!
1. Variables & Naming Conventions
What are Variables?
In Python, a variable is like a container that stores data. Think of it as a labeled box where you can put different types of information. You can create a variable by giving it a name and assigning a value using the equals sign (=
).
# Creating variables name = "Alice" age = 25 height = 5.6 is_student = True
Variable Naming Rules
Python has specific rules for naming variables. Breaking these rules will you a syntax errors:
Rule 1: Only Letters, Numbers, and Underscores
Variable names can contain only letters (a-z, A-Z), numbers (0–9), and underscores (_).
# Valid variable names user_name = "John" score1 = 100 player_2 = "Sarah" total_points = 250 # Invalid variable names (will cause errors) # user-name = "John" # Dash not allowed # score@ = 100 # @ symbol not allowed # player$ = "Sarah" # $ symbol not allowed
Rule 2: Cannot Start with Numbers
Variable names can start with a letter or underscore, but never with a number.
# Valid variable names name1 = "Alice" _score = 95 student_id = 12345 # Invalid variable names # 1name = "Alice" # Cannot start with number # 2player = "Bob" # Cannot start with number
Rule 3: No Spaces Allowed
Spaces are not permitted in variable names. Use underscores instead.
# Valid variable names first_name = "Emma" last_name = "Johnson" phone_number = "123-456-7890" # Invalid variable names # first name = "Emma" # Spaces not allowed # last name = "Johnson" # Spaces not allowed
Rule 4: Case Sensitive
Python treats uppercase and lowercase letters as different characters.
# These are all different variables! name = "Alice" Name = "Bob" NAME = "Charlie" print(name) # Output: Alice print(Name) # Output: Bob print(NAME) # Output: Charlie
Rule 5: Be Descriptive and Concise
Choose names that clearly describe what the variable stores, but keep them reasonably short.
# Good variable names student_grade = 85 temperature_celsius = 23.5 is_weekend = False # Poor variable names x = 85 # Too vague temp_in_celsius_today = 23.5 # Too long weekend = False # Less clear than is_weekend
Naming Conventions for Multi-Word Variables
When you need variable names with multiple words, Python offers several conventions:
1 – Snake Case (Recommended)
Words are separated by underscores, and all letters are lowercase. This is the most common convention in Python.
# Snake case examples first_name = "John" email_address = "john@email.com" total_price = 99.99 is_logged_in = True
2 – Camel Case
The first word is lowercase, and subsequent words start with uppercase letters.
# Camel case examples firstName = "John" emailAddress = "john@email.com" totalPrice = 99.99 isLoggedIn = True
3 – Pascal Case
All words start with uppercase letters, including the first word.
# Pascal case examples FirstName = "John" EmailAddress = "john@email.com" TotalPrice = 99.99 IsLoggedIn = True
Note: Throughout this course, we’ll use snake_case as it’s the most common convention in Python and follows the official Python style guide (PEP 8).
4 – Chained Assignment
Python allows you to assign the same value to multiple variables in a single line:
# Assigning the same value to multiple variables x = y = z = 10 print(x) # Output: 10 print(y) # Output: 10 print(z) # Output: 10 # This is equivalent to: # x = 10 # y = 10 # z = 10
Practical Example of Chained Assignment
# Initialize game variables player1_score = player2_score = player3_score = 0 lives = attempts = 3 print(f"Player 1: {player1_score}") # Output: Player 1: 0 print(f"Player 2: {player2_score}") # Output: Player 2: 0 print(f"Lives remaining: {lives}") # Output: Lives remaining: 3
Complete Example: Student Information System
Let’s put it all together with a practical example:
# Student information using proper naming conventions student_first_name = "Emma" student_last_name = "Wilson" student_age = 20 student_grade = 85.5 is_honor_student = True courses_enrolled = 4 # Display student information print(f"Student: {student_first_name} {student_last_name}") print(f"Age: {student_age}") print(f"Grade: {student_grade}%") print(f"Honor Student: {is_honor_student}") print(f"Courses: {courses_enrolled}") # Using chained assignment for default values homework_1 = homework_2 = homework_3 = 0 print(f"Homework scores: {homework_1}, {homework_2}, {homework_3}")
Key Takeaways
- Variable names can only contain letters, numbers, and underscores
- Cannot start with numbers — always begin with a letter or underscore
- No spaces allowed — use underscores instead
- Case sensitive —
name
andName
are different variables - Be descriptive — choose names that clearly indicate the variable’s purpose
- Use snake_case for multi-word variables (recommended Python style)
- Chained assignment lets you assign the same value to multiple variables
Remember: Good variable names make your code easier to read and understand, both for yourself and others who might work with your code later!
2. Data Types: int
, float
, str
, bool
, NoneType
What are Data Types?
Data types tell Python what kind of information you’re working with. Think of them as different categories of data — just like you wouldn’t mix up a phone number with someone’s name, Python needs to know whether you’re working with numbers, text, or other types of information.
Python has several built-in data types, but we’ll focus on the five most essential ones that you’ll use in everyday programming.
1. Integers (int
)
Integers are whole numbers without decimal points. They can be positive, negative, or zero.
Examples of Integers:
# Positive integers age = 25 score = 100 year = 2024 # Negative integers temperature = -15 debt = -500 # Zero balance = 0 print(age) # Output: 25 print(temperature) # Output: -15
Checking the Type:
print(type(42)) # Output: <class 'int'> print(type(-10)) # Output: <class 'int'> print(type(0)) # Output: <class 'int'>
Real-World Use Cases:
- Counting items:
books = 12
- Age calculations:
user_age = 30
- Index positions:
first_item = 0
2. Floating-Point Numbers (float
)
Floats are numbers that contain decimal points. Even if there’s nothing after the decimal point, Python still treats them as floats.
Examples of Floats:
# Numbers with decimals height = 5.9 price = 29.99 temperature = 98.6
# Numbers with decimal point but no fractional part weight = 150.0 distance = 100. # Scientific notation speed_of_light = 3.0e8 # 300,000,000 print(height) # Output: 5.9 print(weight) # Output: 150.0
Important Note:
# These look the same to humans, but Python treats them differently! integer_one = 1 # This is an int float_one = 1.0 # This is a float print(type(integer_one)) # Output: <class 'int'> print(type(float_one)) # Output: <class 'float'>
Checking the Type:
print(type(3.14)) # Output: <class 'float'> print(type(-20.5)) # Output: <class 'float'> print(type(1.0)) # Output: <class 'float'>
Real-World Use Cases:
- Money calculations:
account_balance = 1250.75
- Measurements:
room_length = 12.5
- Percentages:
tax_rate = 0.08
3. Strings (str
)
Strings are sequences of characters — letters, numbers, symbols, or spaces. They represent text data and must be enclosed in quotes.
Creating Strings:
You can use either single quotes ('
) or double quotes ("
):
# Single quotes name = 'Alice' city = 'New York' # Double quotes message = "Hello, World!" address = "123 Main Street" # Both work the same way print(name) # Output: Alice print(message) # Output: Hello, World!
When to Use Which Quotes:
# Use double quotes when your string contains single quotes sentence = "I'm learning Python!" # Use single quotes when your string contains double quotes quote = 'She said "Hello" to me.' # Or use escape characters alternative1 = 'I\'m learning Python!' alternative2 = "She said \"Hello\" to me."
Multi-line Strings:
# Using triple quotes for longer text poem = """ Roses are red, Violets are blue, Python is awesome, And so are you! """ description = ''' This is a long description that spans multiple lines and preserves the formatting. '''
String Examples:
# Personal information first_name = "John" last_name = "Doe" email = "john.doe@email.com" # Numbers as strings (not for calculations!) phone = "555-1234" zip_code = "12345" # Even single characters are strings grade = "A" initial = "J"
Checking the Type:
print(type("Hello")) # Output: <class 'str'> print(type('Python')) # Output: <class 'str'> print(type("123")) # Output: <class 'str'> (Note: this is text, not a number!)
Real-World Use Cases:
- User names:
username = "student123"
- File paths:
file_location = "/home/user/documents"
- Error messages:
error_msg = "File not found"
4. Boolean (bool
)
Booleans represent truth values and can only be True
or False
. They’re essential for decision-making in programs.
# Boolean literals is_student = True is_graduated = False has_license = True is_raining = False print(is_student) # Output: True print(is_raining) # Output: False
Important Notes:
True
andFalse
must be capitalized- They are not strings (no quotes needed)
# Correct is_online = True is_offline = False # Incorrect is_online = "True" # This is a string, not a boolean! is_offline = false # Should be capitalized: False
Real-World Examples:
# User status is_logged_in = True has_premium_account = False # Game states game_over = False player_won = True # Settings dark_mode_enabled = True notifications_on = False # Conditions is_weekend = True is_adult = False
Checking the Type:
print(type(True)) # Output: <class 'bool'> print(type(False)) # Output: <class 'bool'>
Boolean in Real-Life Analogies:
Think of booleans like switches:
- Light switch:
on
(True) oroff
(False) - Door:
open
(True) orclosed
(False) - Coin flip:
heads
(True) ortails
(False)
5. NoneType (None
)
None represents the absence of a value. It’s Python’s way of saying “nothing” or “no value.”
Using None:
# Initializing variables without a value result = None user_input = None error_message = None print(result) # Output: None print(type(None)) # Output: <class 'NoneType'>
Common Use Cases:
# Default values middle_name = None # Not everyone has a middle name
# Function returns (we'll learn about functions later) def get_user_age(): # If we can't determine age, return None return None # Placeholder for future values database_connection = None # Will be set up later
Checking Data Types
Python provides the type()
function to check what type of data you’re working with:
# Examples of checking types print(type(25)) # <class 'int'> print(type(3.14)) # <class 'float'> print(type("Hello")) # <class 'str'> print(type(True)) # <class 'bool'> print(type(None)) # <class 'NoneType'> # You can also store the type in a variable age = 30 age_type = type(age) print(age_type) # <class 'int'>
Practical Examples: Student Information System
Let’s see all data types working together:
# Student information using different data types student_name = "Emma Johnson" # str student_id = 12345 # int gpa = 3.85 # float is_honors_student = True # bool graduation_date = None # NoneType (not set yet) # Display information print("Student Information:") print(f"Name: {student_name}") print(f"ID: {student_id}") print(f"GPA: {gpa}") print(f"Honors Student: {is_honors_student}") print(f"Graduation Date: {graduation_date}") # Check data types print("\nData Types:") print(f"Name type: {type(student_name)}") print(f"ID type: {type(student_id)}") print(f"GPA type: {type(gpa)}") print(f"Honors type: {type(is_honors_student)}") print(f"Graduation type: {type(graduation_date)}")
Common Mistakes to Avoid
1. Confusing Numbers and Strings
# These are different! age_number = 25 # int - can do math with this age_string = "25" # str - this is just text print(type(age_number)) # <class 'int'> print(type(age_string)) # <class 'str'>
2. Boolean Capitalization
# ✅ Correct is_ready = True is_done = False # ❌ Wrong is_ready = true # NameError: name 'true' is not defined is_done = FALSE # NameError: name 'FALSE' is not defined
3. Unnecessary Quotes Around Numbers
# If you want to do math, don't use quotes score1 = 85 # int - can add, subtract, etc. score2 = "85" # str - just text, can't do math # This works: total = score1 + 15 # Result: 100 # This doesn't work as expected: # total = score2 + 15 # TypeError!
Key Takeaways
int
– Whole numbers (positive, negative, or zero)float
– Numbers with decimal pointsstr
– Text data enclosed in quotesbool
– EitherTrue
orFalse
(capitalized)None
– Represents “no value”- Use
type()
to check what data type you’re working with - Data types affect how Python handles your data
- Choose the right data type for your specific needs
Understanding data types is crucial because they determine what operations you can perform with your data. You can’t do math with strings, and you can’t use numbers where text is expected. Getting comfortable with these five data types will set you up for success in all your Python programming adventures!
Conclusion
In this comprehensive guide, we’ve covered two essential topics that form the foundation of every Python program you’ll ever write.
Let’s recap what we’ve learned in this article:
Variables & Naming Conventions — You now know how to store data and follow Python’s best practices for naming
Data Types — You understand the five fundamental data types and when to use each one
In the next part we will be discussing about Type Casting & Checking, Operators, User Interaction, String Formatting. So, stay tuned for the Upcoming articles.
Zero to Python Hero - Part 1/10: A Beginner guide to Python programming
Author
-
Naveen Pandey has more than 2 years of experience in data science and machine learning. He is an experienced Machine Learning Engineer with a strong background in data analysis, natural language processing, and machine learning. Holding a Bachelor of Science in Information Technology from Sikkim Manipal University, he excels in leveraging cutting-edge technologies such as Large Language Models (LLMs), TensorFlow, PyTorch, and Hugging Face to develop innovative solutions.
View all posts