Variables
Variables are containers for storing data values. Python is dynamically typed โ no need to declare the type.
name = "Alice"
age = 30
height = 5.7
is_student = True
Naming Rules
- Must start with a letter or underscore:
name,_private - Cannot start with a number:
1name - Can contain letters, numbers, underscores:
my_var_1 - Case-sensitive:
ageโAgeโAGE - Cannot use reserved keywords:
for,if,class, etc.
Multiple Assignment
x = y = z = 0 # all point to same value
a, b, c = 1, 2, 3 # tuple unpacking
first, *rest = [1, 2, 3, 4] # first=1, rest=[2,3,4]
Core Data Types
Integers (int)
x = 42
y = -17
big = 1_000_000 # underscores for readability
binary = 0b1010 # binary: 10
hex_val = 0xFF # hexadecimal: 255
print(type(x)) # <class 'int'>
Floats (float)
pi = 3.14159
e = 2.718
sci = 1.5e10 # scientific notation: 15000000000.0
neg_sci = 2.5e-3 # 0.0025
print(type(pi)) # <class 'float'>
Strings (str)
single = 'hello'
double = "world"
multi = """line one
line two
line three"""
raw = r"C:\new\files" # raw string, backslash is literal
print(len("hello")) # 5
print(type("hello")) # <class 'str'>
Booleans (bool)
is_raining = True
is_sunny = False
print(type(True)) # <class 'bool'>
print(int(True)) # 1
print(int(False)) # 0
NoneType (None)
result = None
print(result is None) # True
print(type(None)) # <class 'NoneType'>
Type Conversion
# Implicit (Python does it automatically)
result = 3 + 1.5 # int + float = float (4.5)
# Explicit conversion
int("42") # 42
float("3.14") # 3.14
str(100) # "100"
bool(0) # False
bool(1) # True
bool("") # False
bool("hello") # True
list("abc") # ['a', 'b', 'c']
Checking Types
x = 42
print(type(x)) # <class 'int'>
print(isinstance(x, int)) # True
print(isinstance(x, float)) # False
print(isinstance(x, (int, float))) # True โ check multiple types
Exercises
Exercise 1: Variable Assignment
Create variables for a person's profile: name (str), age (int), gpa (float), is_enrolled (bool). Print each with its type.
Solution:
name = "Bob"
age = 20
gpa = 3.85
is_enrolled = True
print(name, type(name))
print(age, type(age))
print(gpa, type(gpa))
print(is_enrolled, type(is_enrolled))
Exercise 2: Type Conversion
Convert the string "123" to an integer, add 7 to it, then convert back to a string and print.
Solution:
s = "123"
n = int(s) + 7 # 130
result = str(n) # "130"
print(result) # 130
Exercise 3: Truthiness
Predict which values are truthy and which are falsy, then verify:
0, "", [], None, 1, "hello", [0], 0.0
Solution:
values = [0, "", [], None, 1, "hello", [0], 0.0]
for v in values:
print(f"{repr(v):10} -> {bool(v)}")
# 0 -> False
# '' -> False
# [] -> False
# None -> False
# 1 -> True
# 'hello' -> True
# [0] -> True
# 0.0 -> False
Exercise 4: Swap Variables
Swap the values of a = 5 and b = 10 without using a third variable.
Solution:
a = 5
b = 10
a, b = b, a
print(a, b) # 10 5