Table of Contents
Understanding Python Variables and Data Types
Variables are containers for storing data values. Python has several built-in data types that we'll explore in this lesson.
Creating Variables
In Python, you create a variable by assigning a value to it:
# Creating variables
name = "Alice"
age = 25
height = 5.6
is_student = True
print(name) # Output: Alice
print(age) # Output: 25
print(height) # Output: 5.6
print(is_student) # Output: True
Python Data Types
1. Numbers
Python has three numeric types:
# Integer (int)
age = 25
year = 2024
# Float (floating point number)
price = 19.99
temperature = -5.5
# Complex (complex numbers)
complex_num = 3 + 4j
print(type(age)) #
print(type(price)) #
print(type(complex_num)) #
2. Strings (str)
Strings are sequences of characters:
# Different ways to create strings
name = "John"
message = 'Hello, World!'
multiline = """This is a
multiline string"""
# String operations
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Output: John Doe
# String methods
text = "python programming"
print(text.upper()) # PYTHON PROGRAMMING
print(text.capitalize()) # Python programming
print(text.replace("python", "Python")) # Python programming
3. Booleans (bool)
Booleans represent True or False values:
is_sunny = True
is_raining = False
# Boolean operations
print(is_sunny and is_raining) # False
print(is_sunny or is_raining) # True
print(not is_raining) # True
Type Conversion
You can convert between different data types:
# Converting to string
age = 25
age_str = str(age)
print("I am " + age_str + " years old")
# Converting to integer
price_str = "19"
price_int = int(price_str)
print(price_int + 1) # Output: 20
# Converting to float
score_str = "95.5"
score_float = float(score_str)
print(score_float) # Output: 95.5
Variable Naming Rules
- Must start with a letter or underscore
- Can contain letters, numbers, and underscores
- Case-sensitive (age and Age are different)
- Cannot use Python keywords (if, for, while, etc.)
Practice Exercise
Create a program that:
- Stores your personal information in variables
- Performs calculations with numbers
- Demonstrates string operations
# Personal information
name = "Your Name"
age = 20
height = 5.8
is_student = True
# Calculations
birth_year = 2024 - age
future_age = age + 10
# String operations
greeting = "Hello, my name is " + name
info = f"I am {age} years old and {height} feet tall"
print(greeting)
print(info)
print(f"I was born in {birth_year}")
print(f"In 10 years, I will be {future_age} years old")