1. VOTING AGE CHECKER USING IF-ELSE STATEMENT
The Code:
age = int(input("Enter your age: ")) if age >= 18: print("You are eligible to vote.") else: print("You are not eligible to vote.")
Line-by-Line Explanation:
Line 1: age = int(input("Enter your age: "))
input("Enter your age: ")- This displays the prompt "Enter your age: " and waits for the user to type somethingint()- This converts whatever the user types (which comes as text/string) into a whole number (integer)age =- This stores that number in a variable calledageExample: If user types
25, thenagebecomes25
Line 2: if age >= 18:
if- This starts a conditional statement (a decision)age >= 18- This checks if the value inageis greater than or equal to 18>=is the "greater than or equal to" operatorThe colon
:tells Python the next indented line belongs to this condition
Line 3: print("You are eligible to vote.")
This line ONLY runs if the condition on line 2 is TRUE (age is 18 or more)
The indentation (4 spaces) is important - it shows this line belongs to the
if
Line 4: else:
elsemeans "otherwise" - this runs when theifcondition is FALSEThe colon
:again indicates the next indented block belongs toelse
Line 5: print("You are not eligible to vote.")
This line ONLY runs if age is LESS than 18
The indentation shows it belongs to the
else
Flow Chart of How It Works:
Start β Ask for age β User enters 20 β Is 20 >= 18? β YES β Print "eligible"
β
User enters 16 β Is 16 >= 18? β NO β Print "not eligible"Example Scenarios:
| User Input | age >= 18? | Output |
|---|---|---|
| 25 | True | "You are eligible to vote." |
| 18 | True | "You are eligible to vote." |
| 17 | False | "You are not eligible to vote." |
| 5 | False | "You are not eligible to vote." |
2. PRINTING EVEN NUMBERS FROM 1-20 USING FOR LOOP
The Code:
for i in range(1, 21): if i % 2 == 0: print(i)
Line-by-Line Explanation:
Line 1: for i in range(1, 21):
for- This starts a loop that will repeat multiple timesi- This is a loop variable (can be any name, butiis common for "index")in- Specifies what we're looping throughrange(1, 21)- This creates a sequence of numbers starting at 1, up to but NOT including 21So it generates: 1, 2, 3, 4, ..., 20
The colon
:indicates the loop body starts next
Understanding range():
range(1, 21) # Gives: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 range(5) # Gives: 0, 1, 2, 3, 4 (starts at 0 by default) range(2, 10, 2) # Gives: 2, 4, 6, 8 (start, stop, step)
Line 2: if i % 2 == 0:
i % 2- The%is the modulo operator (gives the REMAINDER after division)If
i = 5, then5 % 2 = 1(5 divided by 2 is 2 with remainder 1)If
i = 4, then4 % 2 = 0(4 divided by 2 is 2 with remainder 0)
== 0- Checks if the remainder equals zeroSo this condition is TRUE for even numbers (remainder 0)
Line 3: print(i)
This runs only when the number is even
Prints the current value of
i
What Happens During Loop Execution:
| Loop Iteration | i value | i % 2 | i % 2 == 0? | Print? |
|---|---|---|---|---|
| 1 | 1 | 1 | False | No |
| 2 | 2 | 0 | True | Yes β prints 2 |
| 3 | 3 | 1 | False | No |
| 4 | 4 | 0 | True | Yes β prints 4 |
| 5 | 5 | 1 | False | No |
| 6 | 6 | 0 | True | Yes β prints 6 |
| ... | ... | ... | ... | ... |
| 20 | 20 | 0 | True | Yes β prints 20 |
Visual Representation:
Start β i = 1 β Is 1 even? β No β Next i β i = 2 β Is 2 even? β Yes β Print 2 β Next i β i = 3 β Is 3 even? β No β Next i β i = 4 β Is 4 even? β Yes β Print 4 β Next i β ... continues until i = 20 ... β End (when i reaches 21, loop stops)
Alternative Ways to Write This:
# Method 2: Using step parameter (more efficient) for i in range(2, 21, 2): print(i) # Method 3: Using list comprehension even_numbers = [i for i in range(1, 21) if i % 2 == 0] print(even_numbers)
3. NUMBER GUESSING GAME USING WHILE LOOP
The Code:
import random number_to_guess = random.randint(1, 100) guess = 0 while guess != number_to_guess: guess = int(input("Guess a number between 1 and 100: ")) if guess < number_to_guess: print("Too low! Try again.") elif guess > number_to_guess: print("Too high! Try again.") else: print("Congratulations! You guessed the number.")
Line-by-Line Explanation:
Line 1: import random
import- This brings in Python's random modulerandom- A built-in library that provides functions for generating random numbersWithout this line, you can't use
random.randint()
Line 2: number_to_guess = random.randint(1, 100)
random.randint(1, 100)- Generates a random integer between 1 and 100 (inclusive)randint= Random IntegerCould return any number like 42, 17, 99, etc.
number_to_guess =- Stores that random number in this variableExample result: If random gives 73, then
number_to_guess = 73
Line 3: guess = 0
Creates a variable called
guessand sets it to 0Set to 0 initially so it's different from any valid guess (1-100)
This ensures the while loop runs at least once
Line 4: while guess != number_to_guess:
while- Creates a loop that continues as long as the condition is TRUEguess != number_to_guess- Checks if guess is NOT equal to the target number!=means "not equal to"The loop continues UNTIL the user guesses correctly
Line 5: guess = int(input("Guess a number between 1 and 100: "))
input("Guess a number between 1 and 100: ")- Prompts user for inputint()- Converts the string input to an integerguess =- Updates the guess variable with the user's input
Line 6: if guess < number_to_guess:
Checks if the user's guess is less than the secret number
Line 7: print("Too low! Try again.")
Tells the user they need to guess higher
Line 8: elif guess > number_to_guess:
elif= "else if" - Checks if guess is greater than secret numberOnly runs if the first condition (guess <) was false
Line 9: print("Too high! Try again.")
Tells the user they need to guess lower
Line 10: else:
Runs if neither condition was true
This means guess is NOT less than AND NOT greater than secret number
Therefore, guess MUST equal the secret number
Line 11: print("Congratulations! You guessed the number.")
Congratulates the user for guessing correctly
After this, the loop condition will be checked again
Since guess now equals number_to_guess, the loop ends
Detailed Walkthrough Example:
Let's trace through the game assuming the secret number is 42:
Step 1: import random (load the random module) Step 2: number_to_guess = random.randint(1, 100) β gets 42 (hypothetically) Step 3: guess = 0 β Check while condition: Is 0 != 42? YES β Enter loop Step 4: User enters 50 β guess = 50 Step 5: Is 50 < 42? NO Step 6: Is 50 > 42? YES β Print "Too high! Try again." β Loop continues (guess is 50, secret is 42, 50 != 42 is TRUE) Step 7: User enters 30 β guess = 30 Step 8: Is 30 < 42? YES β Print "Too low! Try again." β Loop continues (30 != 42 is TRUE) Step 9: User enters 42 β guess = 42 Step 10: Is 42 < 42? NO Step 11: Is 42 > 42? NO Step 12: else β Print "Congratulations! You guessed the number." β Check while condition: Is 42 != 42? NO β Exit loop Program ends
Visual Flow Chart:
Start β Generate secret number (e.g., 42) β Initialize guess = 0 β βββββββββββββββββββββββββββββββββββ β WHILE guess != secret? β β β YES β β Ask user for guess β β β β β Is guess < secret? β YES β Print "Too low" β Back to loop start β β NO β β Is guess > secret? β YES β Print "Too high" β Back to loop start β β NO β β (must be equal) β β Print "Congratulations" β β β β β Exit loop β βββββββββββββββββββββββββββββββββββ β End
Common Issues and Solutions:
# ISSUE 1: User enters a letter instead of number # This would crash the program. FIX with try-except: try: guess = int(input("Guess a number: ")) except ValueError: print("Please enter a valid number!") continue # Ask again # ISSUE 2: User guesses outside 1-100 range # FIX with validation: if guess < 1 or guess > 100: print("Please guess between 1 and 100!") continue # Don't count this guess, ask again # ISSUE 3: Want to limit number of attempts # FIX with attempt counter: attempts = 0 max_attempts = 10 while guess != number_to_guess and attempts < max_attempts: attempts += 1 # rest of game logic
Key Concepts Demonstrated:
| Concept | How It's Used |
|---|---|
| Import | import random brings in external functionality |
| Variable Assignment | Storing random number, user guesses, and tracking |
| While Loop | Repeats until correct guess is made |
| If-Elif-Else | Provides different feedback based on guess comparison |
| Comparison Operators | < (less than), > (greater than), != (not equal) |
| User Input | input() gets guesses from user |
| Type Conversion | int() converts string to integer |
SUMMARY TABLE OF KEY CONCEPTS
| Concept | Code Example | What It Does |
|---|---|---|
| If Statement | if age >= 18: | Executes code block if condition is true |
| Else Statement | else: | Executes code block if if-condition is false |
| For Loop | for i in range(1, 21): | Repeats code block for each value in sequence |
| Modulo Operator | i % 2 == 0 | Checks if a number is even (remainder of division by 2 is 0) |
| While Loop | while guess != number: | Repeats code block as long as condition is true |
| Random Module | random.randint(1, 100) | Generates random integer between specified values |
| Comparison | guess < number_to_guess | Compares two values and returns True/False |
PRACTICE EXERCISES
Try modifying these on your own:
Voting Checker Challenge: Add different voting ages for different countries
Even Numbers Challenge: Print odd numbers instead of even ones
Guessing Game Challenge: Add a hint system, difficulty levels, or score tracking
TIPS FOR BEGINNERS
Indentation is CRITICAL in Python - always use consistent spaces (4 spaces is standard)
Read error messages - they tell you exactly what went wrong
Test with different inputs - try edge cases (like age = 18 exactly)
Add print statements to see what your variables contain while debugging
Comment your code - explain what each part does for future reference
Discussion (0)