Condition, Loops & Type Casting
Master decision‑making with if‑elif‑else, repeat code with for/while loops, and safely convert data types with casting functions.
For Loop
Iterates over sequences
While Loop
Repeats while true
range()
Number generator
Type Casting
int(), float(), str(), bool()
If‑Elif‑Else Statements
The if statement lets you execute code only when a condition is True. Use elif for additional checks and else for a default block.
age = 18
if age < 13:
print("You are a child")
elif age < 18:
print("You are a teenager")
else:
print("You are an adult")
Note: Indentation defines blocks. elif and else are optional.
For Loop
A for loop repeats a block of code for each item in a sequence.
Beginner Example
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
for letter in "Python":
print(letter)
for i in range(5):
print(i)
banana
orange
P y t h o n
0 1 2 3 4
Intermediate Example
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
for i in range(1,4):
for j in range(1,4):
print(f"{i} x {j} = {i*j}")
for x in range(3):
print(x)
else:
print("Loop ended without break")
1: banana
2: cherry
multiplication table
0 1 2
Loop ended without break
range() – The Loop Counter
range(start, stop, step) generates sequences.
range(stop)
range(5) → 0,1,2,3,4range(start, stop)
range(2,6) → 2,3,4,5range(start, stop, step)
range(1,10,2) → 1,3,5,7,9for i in range(4): print(i) # 0 1 2 3
for i in range(10,13): print(i) # 10 11 12
for i in range(2,11,2): print(i) # 2 4 6 8 10
for i in range(5,0,-1): print(i) # 5 4 3 2 1
While Loop
Repeats while condition is True. Use break to exit and continue to skip.
count = 0
while count < 5:
print(count)
count += 1
Type Casting – Converting Between Data Types
Python provides built‑in functions to convert one data type to another. This is essential when handling user input or preparing data for calculations.
| Function | Converts to | Example |
|---|---|---|
int(x) | Integer | int("42") → 42, int(3.14) → 3 |
float(x) | Float | float("3.14") → 3.14, float(5) → 5.0 |
str(x) | String | str(123) → "123", str(4.5) → "4.5" |
bool(x) | Boolean | bool(0) → False, bool(5) → True |
Beginner Example: Converting Input
# input() always returns a string
age_str = input("Enter your age: ")
age = int(age_str) # convert to int
next_age = age + 1
print(f"Next year you'll be {next_age}")
price = float(input("Enter price: "))
tax = price * 0.18
print(f"Tax = {tax:.2f}")
Next year you'll be 16
Enter price: 100
Tax = 18.00
Intermediate Example: Casting with Conditions
# Convert string to bool – caution: bool("False") is True!
value = input("Enter True or False: ").lower()
bool_val = value == "true" # manual conversion
print(bool_val)
# Mixing numbers and strings
num = 42
message = "The answer is " + str(num)
print(message)
# Float to int (truncates)
pi = 3.14159
approx = int(pi)
print(approx) # 3
True
The answer is 42
3
Practice Problems (Solved)
Strengthen conditions, loops, and casting.
🔰 Beginner Level
1. Check If a Number is Prime
num = int(input("Enter number: "))
is_prime = num > 1
for i in range(2, int(num**0.5)+1):
if num % i == 0:
is_prime = False
break
print("Prime" if is_prime else "Not Prime")2. Sum of First n Natural Numbers
n = int(input("Enter n: "))
total = sum(range(1, n+1))
print(total)3. Reverse a String (without slicing)
text = input("Enter string: ")
rev = ""
for ch in text:
rev = ch + rev
print(rev)4. Safe Division with Casting
Problem: Accept two numbers (as strings), convert to float, and print division result. Handle division by zero.
a = float(input("First number: "))
b = float(input("Second number: "))
if b == 0:
print("Cannot divide by zero")
else:
print(f"Result = {a/b:.2f}")5. Convert String List to Integers
Problem: Given a string of numbers "10 20 30", convert each to integer and find the sum using a loop.
numbers_str = "10 20 30"
parts = numbers_str.split()
total = 0
for p in parts:
total += int(p)
print("Sum =", total)⚡ Intermediate Level
6. Fibonacci Series up to n Terms
n = int(input("Terms: "))
a,b = 0,1
for _ in range(n):
print(a, end=' ')
a,b = b, a+b7. Count Digits, Letters, Spaces
s = input("Sentence: ")
d = l = sp = 0
for ch in s:
if ch.isdigit(): d+=1
elif ch.isalpha(): l+=1
elif ch==' ': sp+=1
print(f"Digits:{d} Letters:{l} Spaces:{sp}")8. Multiplication Table (nested loops)
for i in range(1,11):
for j in range(1,11):
print(f"{i*j:4}", end="")
print()Unsolved Exercises
Solve these on your own – no solutions provided.
🔰 Beginner Level
1. Print Even Numbers from 1 to 20
2. Countdown Timer
3. Grade Calculator (if‑elif‑else)
4. String to Float & Average
Accept three string numbers (e.g., "85.5 90 78.2"), split, convert to float, and print average.
5. Boolean Casting Practice
Write a program that reads a string "True" or "False" and prints the corresponding boolean value. Also show what happens with empty string.