Lesson 2 of 40
Foundations
Beginner
โฑ 25 min
Variables, Types & Operators
Explore Python's dynamic type system โ numbers, strings, booleans, None, type conversion, and all operators including the walrus operator.
Part 1: Built-in Types
# Numbers
age = 30 # int
price = 9.99 # float
balance = 1_000_000 # readable large int
score = 3+4j # complex
# Strings
name = "Alice"
bio = """Multi
line string"""
# Boolean & None
active = True
data = None
age = 30 # int
price = 9.99 # float
balance = 1_000_000 # readable large int
score = 3+4j # complex
# Strings
name = "Alice"
bio = """Multi
line string"""
# Boolean & None
active = True
data = None
Part 2: Type Checking & Conversion
type(42) # <class 'int'>
isinstance("hi", str) # True
# Conversion
int("42") # 42
float("3.14") # 3.14
str(100) # "100"
bool(0) # False (0, "", None, [] are falsy)
# Safe conversion
try:
n = int(user_input)
except ValueError:
print("Not a valid number")
isinstance("hi", str) # True
# Conversion
int("42") # 42
float("3.14") # 3.14
str(100) # "100"
bool(0) # False (0, "", None, [] are falsy)
# Safe conversion
try:
n = int(user_input)
except ValueError:
print("Not a valid number")
Part 3: String Methods & f-strings
s = " Hello, World! "
s.strip() # "Hello, World!"
s.lower() # " hello, world! "
s.replace("World", "Python")
s.split(",") # [" Hello", " World! "]
",".join(["a","b","c"]) # "a,b,c"
# f-string expressions
x = 3.14159
print(f"Pi is {x:.2f}") # Pi is 3.14
print(f"{x = }") # x = 3.14159 (debug format)
s.strip() # "Hello, World!"
s.lower() # " hello, world! "
s.replace("World", "Python")
s.split(",") # [" Hello", " World! "]
",".join(["a","b","c"]) # "a,b,c"
# f-string expressions
x = 3.14159
print(f"Pi is {x:.2f}") # Pi is 3.14
print(f"{x = }") # x = 3.14159 (debug format)
Part 4: Walrus Operator & Augmented Assignment
# Walrus operator := (Python 3.8+)
import re
if m := re.search(r"d+", "Order 42"):
print(m.group()) # 42
# Augmented assignment
x = 10
x += 5 # x = 15
x **= 2 # x = 225
x //= 10 # x = 22 (floor division)
import re
if m := re.search(r"d+", "Order 42"):
print(m.group()) # 42
# Augmented assignment
x = 10
x += 5 # x = 15
x **= 2 # x = 225
x //= 10 # x = 22 (floor division)