Python Programming (Basic) • Comparisons, F-Strings, Text Processing & Debugging
==
!=
<
>
<=
>=
=
and
or
not
age = 18 age == 18 # True (equal to) age != 21 # True (not equal to) age < 21 # True (less than) age > 16 # True (greater than) age <= 18 # True (less than or equal) age >= 18 # True (greater than or equal)
= assigns a value — == compares values
x = 5 # assignment x == 5 # comparison → True
age = 20 has_id = True # Both must be True age >= 18 and has_id # True # At least one must be True age >= 21 or has_id # True # Flip the result not has_id # False
score = 85 # Instead of: score >= 70 and score <= 100 70 <= score <= 100 # True (Pythonic)
0
0.0
""
None
False
name = "" if name: print("Has a name") else: print("Name is empty") # ← this prints
We'll see more of this as we work with conditionals.
age = int(input("Enter your age: ")) if age >= 13 and age < 18: print("Teen access granted") elif age >= 18: print("Adult access granted") else: print("Access denied — too young")
Enter your age: 15 Teen access granted
Time: 25–35 minutes
input()
int()
✓ Correct branching for boundary values (12, 13, 17, 18) ✓ Uses >= and < appropriately ✓ No hard-coded values (works for any valid age)
"18" >= 13
Question: What's the difference between == and =?
Expected Answer:
True
f"{var}"
{value:.2f}
name = "Alice" age = 25 print(f"Hello, {name}!") print(f"{name} is {age} years old")
price = 49.99 tax_rate = 0.08 print(f"Total: {price * (1 + tax_rate)}")
Anything valid Python can go inside {}
{}
price = 19.999 tip = 3.5 print(f"Price: ${price:.2f}") # Price: $20.00 print(f"Tip: ${tip:.2f}") # Tip: $3.50
# Right-align in a 10-character field print(f"{'Item':<10} {'Price':>8}") print(f"{'Coffee':<10} {4.50:>8.2f}") print(f"{'Sandwich':<10} {8.75:>8.2f}")
Item Price Coffee 4.50 Sandwich 8.75
# String concatenation print("Hello, " + name + "! You are " + str(age) + " years old.")
# ✓ F-string print(f"Hello, {name}! You are {age} years old.")
str()
bill = 85.50 tip_percent = 18 tip = bill * (tip_percent / 100) total = bill + tip tip_label = f"Tip ({tip_percent}%):" print(f"{'Bill:':<12} ${bill:>8.2f}") print(f"{tip_label:<12} ${tip:>8.2f}") print(f"{'Total:':<12} ${total:>8.2f}")
Bill: $ 85.50 Tip (18%): $ 15.39 Total: $ 100.89
✓ Clean, consistent output formatting ✓ All monetary values show exactly 2 decimal places ✓ No type errors ✓ Uses f-strings (not concatenation or str.format())
str.format()
Forgetting the leading f — "{name}" prints literally Using braces incorrectly — f"{{name}}" prints {name} Mixing quotes — use different quotes inside vs outside Wrong format spec — .2f not .2 for fixed decimals
f
"{name}"
f"{{name}}"
{name}
.2f
.2
# Missing the f print("{name} is {age}") # literal text # ✓ With the f print(f"{name} is {age}") # variable values
Question: Why is f-string formatting usually better than + concatenation?
+
.split()
' '.join()
sentence = "Hello Python World" words = sentence.split() print(words) # ['Hello', 'Python', 'World'] print(len(words)) # 3
data = "Alice,Bob,Charlie" names = data.split(",") print(names) # ['Alice', 'Bob', 'Charlie']
words = "Hello Python World".split() print(words[0]) # 'Hello' print(words[-1]) # 'World'
words = ['Hello', 'Python', 'World'] # Join with a space result = ' '.join(words) print(result) # 'Hello Python World' # Join with hyphens result = '-'.join(words) print(result) # 'Hello-Python-World' # Join with ' | ' result = ' | '.join(words) print(result) # 'Hello | Python | World'
The separator goes before .join():
.join()
separator.join(list_of_strings)
sentence = "The quick brown fox jumps" words = sentence.split() print(f"Word count: {len(words)}") # 5
sentence = "The quick brown fox jumps" words = sentence.split() longest = "" for word in words: if len(word) > len(longest): longest = word print(f"Longest word: {longest}") # 'quick' or 'brown' or 'jumps'
len()
sentence = input("Enter a sentence: ") words = sentence.split() print(f"Word count: {len(words)}") print(f"Hyphenated: {'-'.join(words)}")
Enter a sentence: Python is great Word count: 3 Hyphenated: Python-is-great
|
Enter a sentence: The quick brown fox jumps Word count: 5 Longest word: quick Pipe version: The | quick | brown | fox | jumps
✓ Accurate word count ✓ Correctly identifies longest word ✓ Uses .split() and .join() correctly ✓ Clean formatted output
Punctuation attached to words — "hello," counts as one word Empty input edge case — "".split() returns [] Forgetting that split returns a list — not a string join() requires strings — ', '.join([1, 2, 3]) fails
"hello,"
"".split()
[]
', '.join([1, 2, 3])
# This fails numbers = [1, 2, 3] result = ', '.join(numbers) # TypeError! # ✓ Convert to strings first result = ', '.join(str(n) for n in numbers)
Question: What type does .split() return?
Expected Answer: A list of strings
Traceback (most recent call last): File "calculator.py", line 5, in <module> total = bill + tip_amount NameError: name 'tip_amount' is not defined
NameError
name 'tip_amount' is not defined
calculator.py
total = bill + tip_amount
Read tracebacks from the bottom up — the error type is the most important clue.
print(mesage) # Typo: 'mesage' instead of 'message'
age = input("Age: ") print(age + 5) # Can't add str + int
number = int("hello") # Can't convert "hello" to int
words = ["hello", "world"] print(words[5]) # Only indices 0 and 1 exist
# Step 4: Add diagnostic prints print(f"DEBUG: bill = {bill}, type = {type(bill)}") print(f"DEBUG: tip = {tip}, type = {type(tip)}") total = bill + tip # ← error is here
Change one thing, then re-run. Never change multiple things at once.
# Broken script — 3 bugs hidden name = input("Enter name: ") age = input("Enter age: ") birth_year = 2025 - age # Bug 1: age is a string greeting = f"Hello, {nmae}!" # Bug 2: typo in variable name scores = [85, 92, 78] print(f"Top score: {scores[3]}") # Bug 3: index out of range
age = int(input("Enter age: "))
greeting = f"Hello, {name}!"
print(f"Top score: {scores[2]}")
user_name = "Alice" print(f"Welcome, {username}!")
price = input("Enter price: ") tax = price * 0.08 print(f"Tax: ${tax:.2f}")
colors = ["red", "green", "blue"] print(f"Last color: {colors[3]}")
✓ All 3 scripts fixed and running without errors ✓ Learner can explain each fix in one sentence:
username
user_name
price
float()
colors[2]
colors[-1]
print "hello"
print("hello")
5 / 2 → 2
5 / 2 → 2.5
raw_input()
Always use Python 3. If you find Python 2 code online, convert the syntax.
Question: You see this error: TypeError: can only concatenate str (not "int") to str. What's likely wrong and how do you fix it?
TypeError: can only concatenate str (not "int") to str
Expected Answer: You're trying to add a string and an integer — use str() to convert the int, or use an f-string.
f"{variable}"
✓ Comparison operators and boolean logic ✓ F-string formatting (basics) ✓ split() and join() for text processing ✓ Print-debugging and reading tracebacks
for
Remember:
See you in Session 4!