Variables and Data Types in Python
Understanding variables and data types is fundamental to programming in Python. In this lesson, you'll learn how to store and work with different types of data in your programs.
What are Variables?
A variable is like a labeled box that stores a value. You can think of it as giving a name to a piece of data so you can use it later in your program.
Creating Variables
In Python, creating a variable is simple - you just assign a value to a name:
# Creating variables
name = "Alice"
age = 25
height = 5.6
is_student = True
Variable Naming Rules
Python has specific rules for naming variables:
Valid variable names:
name = "John"
age = 30
first_name = "Jane"
user_id = 12345
_private_var = "hidden"
name2 = "Bob"
Invalid variable names:
# These will cause errors
2name = "Invalid" # Can't start with a number
first-name = "Invalid" # Can't contain hyphens
class = "Invalid" # Can't use reserved words
my name = "Invalid" # Can't contain spaces
Best Practices for Variable Names
- Use descriptive names:
user_ageinstead ofua - Use lowercase with underscores:
first_namenotfirstName - Be consistent throughout your code
- Avoid single letters except for loops:
i,j,k
Python Data Types
Python has several built-in data types. Let's explore the most important ones:
1. Numbers
Python has three numeric types:
Integers (int)
Whole numbers without decimal points:
age = 25
population = 7800000000
negative_number = -42
big_number = 123456789012345678901234567890 # Python handles big numbers!
Floating-Point Numbers (float)
Numbers with decimal points:
height = 5.9
temperature = 98.6
pi = 3.14159
scientific_notation = 1.5e-4 # 0.00015
Complex Numbers (complex)
Numbers with real and imaginary parts (advanced):
complex_num = 3 + 4j
2. Strings (str)
Strings represent text data:
# Different ways to create strings
name = "Alice"
message = 'Hello, World!'
multiline = """This is a
multiline string"""
# String with quotes inside
quote = "She said, 'Hello there!'"
another_quote = 'He replied, "Nice to meet you!"'
Common String Operations
first_name = "John"
last_name = "Doe"
# String concatenation
full_name = first_name + " " + last_name
print(full_name) # Output: John Doe
# String formatting with f-strings (recommended)
greeting = f"Hello, {full_name}!"
print(greeting) # Output: Hello, John Doe!
# String methods
print(full_name.upper()) # JOHN DOE
print(full_name.lower()) # john doe
print(len(full_name)) # 8 (length of string)
3. Booleans (bool)
Boolean values represent True or False:
is_sunny = True
is_raining = False
has_license = True
is_weekend = False
Booleans are often the result of comparisons:
age = 18
is_adult = age >= 18 # True
is_teenager = age < 20 # True
is_senior = age >= 65 # False
4. None Type
None represents the absence of a value:
result = None
user_input = None
# Often used as a default value
def greet(name=None):
if name is None:
print("Hello, stranger!")
else:
print(f"Hello, {name}!")
Type Checking and Conversion
Checking Variable Types
Use the type() function to see what type a variable is:
name = "Alice"
age = 25
height = 5.6
is_student = True
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
print(type(height)) # <class 'float'>
print(type(is_student)) # <class 'bool'>
Type Conversion
You can convert between different types:
# Converting to string
age = 25
age_str = str(age) # "25"
# Converting to integer
price_str = "19"
price = int(price_str) # 19
# Converting to float
temperature_str = "98.6"
temperature = float(temperature_str) # 98.6
# Converting to boolean
empty_string = bool("") # False
non_empty = bool("hello") # True
zero = bool(0) # False
non_zero = bool(42) # True
Working with User Input
When you get input from users, it's always a string. You'll often need to convert it:
# Getting user input
name = input("Enter your name: ")
age_str = input("Enter your age: ")
# Converting string to integer
age = int(age_str)
# Using the data
print(f"Hello {name}, you are {age} years old.")
print(f"Next year you will be {age + 1}.")
Common Data Type Operations
Arithmetic with Numbers
a = 10
b = 3
print(a + b) # Addition: 13
print(a - b) # Subtraction: 7
print(a * b) # Multiplication: 30
print(a / b) # Division: 3.333...
print(a // b) # Floor division: 3
print(a % b) # Modulus (remainder): 1
print(a ** b) # Exponentiation: 1000
String Operations
text = "Python"
print(text + " Programming") # Concatenation: Python Programming
print(text * 3) # Repetition: PythonPythonPython
print("Py" in text) # Membership: True
print(text[0]) # Indexing: P
print(text[1:4]) # Slicing: yth
Practical Examples
Example 1: Personal Information Calculator
# Get user information
print("=== Personal Information ===")
name = input("Enter your name: ")
birth_year = int(input("Enter your birth year: "))
current_year = 2024
# Calculate age
age = current_year - birth_year
# Display results
print(f"\nHello, {name}!")
print(f"You are approximately {age} years old.")
print(f"In 10 years, you'll be {age + 10} years old.")
Example 2: Temperature Converter with Validation
# Temperature converter
print("=== Temperature Converter ===")
temp_str = input("Enter temperature in Celsius: ")
try:
celsius = float(temp_str)
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C = {fahrenheit}°F")
# Add some context
if celsius <= 0:
print("That's freezing!")
elif celsius >= 100:
print("That's boiling!")
else:
print("That's a comfortable temperature.")
except ValueError:
print("Please enter a valid number!")
Common Mistakes and How to Avoid Them
1. Type Mismatch Errors
# This will cause an error
age = "25"
next_year = age + 1 # Can't add string and number
# Fix: Convert the type
age = int("25")
next_year = age + 1 # Now it works
2. Variable Scope
# Be careful about where variables are defined
def calculate_area():
length = 10
width = 5
return length * width
area = calculate_area()
# print(length) # Error: length is not defined outside the function
3. Reassigning Variables
# Variables can change type
value = 42 # integer
print(type(value)) # <class 'int'>
value = "hello" # now a string
print(type(value)) # <class 'str'>
Practice Exercises
Exercise 1: Variable Practice
Create variables for your personal information (name, age, city, favorite number) and print them in a formatted message.
Exercise 2: Type Conversion
Ask the user for two numbers and perform all basic arithmetic operations on them.
Exercise 3: Boolean Logic
Create a program that determines if someone can vote based on their age and citizenship status.
Sample Solutions
Exercise 1:
name = "Alice"
age = 28
city = "New York"
favorite_number = 7
print(f"My name is {name}.")
print(f"I am {age} years old.")
print(f"I live in {city}.")
print(f"My favorite number is {favorite_number}.")
Exercise 2:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print(f"Addition: {num1} + {num2} = {num1 + num2}")
print(f"Subtraction: {num1} - {num2} = {num1 - num2}")
print(f"Multiplication: {num1} * {num2} = {num1 * num2}")
if num2 != 0:
print(f"Division: {num1} / {num2} = {num1 / num2}")
else:
print("Cannot divide by zero!")
Exercise 3:
age = int(input("Enter your age: "))
is_citizen = input("Are you a citizen? (yes/no): ").lower() == "yes"
can_vote = age >= 18 and is_citizen
print(f"Can vote: {can_vote}")
if can_vote:
print("You are eligible to vote!")
else:
if age < 18:
print("You must be at least 18 to vote.")
if not is_citizen:
print("You must be a citizen to vote.")
Key Takeaways
- Variables store data and give it a meaningful name
- Python has several built-in data types: int, float, str, bool, None
- Use
type()to check a variable's type - Convert between types using
int(),float(),str(),bool() - User input is always a string and often needs conversion
- Choose descriptive variable names and follow Python naming conventions
What's Next?
Now that you understand variables and data types, you're ready to learn about:
Remember: Understanding data types is crucial for preventing bugs and writing efficient code. Take time to practice with different types and conversions.
