MadiisAttendance
Python programming complete guide 7 min read 1,372 words 96 sentences uni

Python in 7 Days – Day 2: Control Flow, Loops & Building Your First Game

M Usman May 25, 2026
8 0 0 score
0%
Your Progress
0/21 sections
Reading Speed
0
words/min
Time Spent
00:00

1. VOTING AGE CHECKER USING IF-ELSE STATEMENT

The Code:

python
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 something

  • int() - This converts whatever the user types (which comes as text/string) into a whole number (integer)

  • age = - This stores that number in a variable called age

  • Example: If user types 25, then age becomes 25

Line 2: if age >= 18:

  • if - This starts a conditional statement (a decision)

  • age >= 18 - This checks if the value in age is greater than or equal to 18

  • >= is the "greater than or equal to" operator

  • The 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:

  • else means "otherwise" - this runs when the if condition is FALSE

  • The colon : again indicates the next indented block belongs to else

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:

text
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 Inputage >= 18?Output
25True"You are eligible to vote."
18True"You are eligible to vote."
17False"You are not eligible to vote."
5False"You are not eligible to vote."

2. PRINTING EVEN NUMBERS FROM 1-20 USING FOR LOOP

The Code:

python
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 times

  • i - This is a loop variable (can be any name, but i is common for "index")

  • in - Specifies what we're looping through

  • range(1, 21) - This creates a sequence of numbers starting at 1, up to but NOT including 21

    • So it generates: 1, 2, 3, 4, ..., 20

  • The colon : indicates the loop body starts next

Understanding range():

python
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, then 5 % 2 = 1 (5 divided by 2 is 2 with remainder 1)

    • If i = 4, then 4 % 2 = 0 (4 divided by 2 is 2 with remainder 0)

  • == 0 - Checks if the remainder equals zero

  • So 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 Iterationi valuei % 2i % 2 == 0?Print?
111FalseNo
220TrueYes β†’ prints 2
331FalseNo
440TrueYes β†’ prints 4
551FalseNo
660TrueYes β†’ prints 6
...............
20200TrueYes β†’ prints 20

Visual Representation:

text
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:

python
# 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:

python
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 module

  • random - A built-in library that provides functions for generating random numbers

  • Without 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 Integer

    • Could return any number like 42, 17, 99, etc.

  • number_to_guess = - Stores that random number in this variable

  • Example result: If random gives 73, then number_to_guess = 73

Line 3: guess = 0

  • Creates a variable called guess and sets it to 0

  • Set 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 TRUE

  • guess != 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 input

  • int() - Converts the string input to an integer

  • guess = - 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 number

  • Only 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:

text
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:

text
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:

python
# 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:

ConceptHow It's Used
Importimport random brings in external functionality
Variable AssignmentStoring random number, user guesses, and tracking
While LoopRepeats until correct guess is made
If-Elif-ElseProvides different feedback based on guess comparison
Comparison Operators< (less than), > (greater than), != (not equal)
User Inputinput() gets guesses from user
Type Conversionint() converts string to integer

SUMMARY TABLE OF KEY CONCEPTS

ConceptCode ExampleWhat It Does
If Statementif age >= 18:Executes code block if condition is true
Else Statementelse:Executes code block if if-condition is false
For Loopfor i in range(1, 21):Repeats code block for each value in sequence
Modulo Operatori % 2 == 0Checks if a number is even (remainder of division by 2 is 0)
While Loopwhile guess != number:Repeats code block as long as condition is true
Random Modulerandom.randint(1, 100)Generates random integer between specified values
Comparisonguess < number_to_guessCompares two values and returns True/False

PRACTICE EXERCISES

Try modifying these on your own:

  1. Voting Checker Challenge: Add different voting ages for different countries

  2. Even Numbers Challenge: Print odd numbers instead of even ones

  3. Guessing Game Challenge: Add a hint system, difficulty levels, or score tracking


TIPS FOR BEGINNERS

  1. Indentation is CRITICAL in Python - always use consistent spaces (4 spaces is standard)

  2. Read error messages - they tell you exactly what went wrong

  3. Test with different inputs - try edge cases (like age = 18 exactly)

  4. Add print statements to see what your variables contain while debugging

  5. Comment your code - explain what each part does for future reference

Discussion (0)
Login to comment
Dictionary

Add New Word

Dictionary Words
My Notes
Highlights
Select text and click highlight to save
My Vocabulary
Quick Quiz
Settings
Reading Analytics
Today's reading: 0 min
Total read time: 0 min
Words learned: 0
Streak: 0 days
AI Summary

Generating summary...