Learning Python with the Prince: Conditional Statements and Loops

Review: The answers to the two homework questions left in the previous chapter are now published. (Aren’t the answers quite simple? They only apply basic mathematical knowledge: addition, subtraction, multiplication, and division.)

# Student Grade Management System
student_name = "Zhang Xiaoming"
chinese = 88
math = 92
english = 85
# Calculate total score and average score
total_score = chinese + math + english
average_score = total_score / 3
# Output results
print("=== Student Report Card ===")
print("Name:", student_name)
print("Chinese:", chinese)
print("Math:", math)
print("English:", english)
print("Total Score:", total_score)
print("Average Score:", average_score)
# Shopping Plan
apple_price = 8      # Price of apples
banana_price = 5     # Price of bananas
orange_price = 6     # Price of oranges
# Quantity purchased
apple_count = 3
banana_count = 2
orange_count = 4
# Calculate
apple_total = apple_price * apple_count
banana_total = banana_price * banana_count
orange_total = orange_price * orange_count
subtotal = apple_total + banana_total + orange_total
discount = 0.9        # 10% discount
final_price = subtotal * discount
# Output shopping receipt
print("=== Shopping List ===")
print(f"Apples: {apple_count} kg Γ— {apple_price} yuan = {apple_total} yuan")
print(f"Bananas: {banana_count} kg Γ— {banana_price} yuan = {banana_total} yuan")
print(f"Oranges: {orange_count} kg Γ— {orange_price} yuan = {orange_total} yuan")
print("Subtotal:", subtotal, "yuan")
print("Discount: 10%")
print("Total Payable:", final_price, "yuan")

πŸ“š Today’s New Learning Goals

  • Master conditional statements (if statements) to make the program “think”

  • Master loops (for, while) to make the program “repeat tasks”

  • Be able to write simple intelligent programs and repetitive task programs

Chapter 5: Conditional Statements – Making the Program “Think” 🧠

5.1 Basic if Statement

Life Analogy: Just like deciding whether to take an umbrella every day

  • If it rains β†’ take an umbrella

  • If it doesn’t rain β†’ don’t take an umbrella

# Basic syntax
if condition:
    action to execute
# Actual example: Check if it is raining
is_raining = True
if is_raining:
    print("It is raining today, remember to take an umbrella!")
    print("Be careful on the road!")
# Note: The colon after the condition cannot be omitted.

5.2 if-else Statement

# Syntax
if condition:
    # Execute if condition is true
else:
    # Execute if condition is false
# Actual example: Exam score judgment
score = 85
if score >= 60:
    print("Congratulations, you passed the exam! πŸŽ‰")
else:
    print("Unfortunately, you did not pass the exam. Keep working hard! πŸ’ͺ")

5.3 if-elif-else Multiple Judgments

# Syntax
if condition1:
    # Execute if condition1 is true
elif condition2:
    # Execute if condition2 is true
else:
    # Execute for other cases
# Actual example: Grade level judgment
score = 78
if score >= 90:
    print("Excellent! Great job! 🌟")
elif score >= 80:
    print("Good! Keep it up! πŸ‘")
elif score >= 70:
    print("Average! There is room for improvement! ✨")
elif score >= 60:
    print("Pass! Work harder! πŸ“š")
else:
    print("Fail! Need to work twice as hard! πŸ’ͺ")

5.4 Practical Application Cases

# Case: The weather suddenly turned cold, before going out, mom's nagging reminders
temperature = 10  # Temperature
print("=== Today's Clothing Suggestions ===")
if temperature > 25:
    print("It's hot, wear short sleeves")
elif temperature > 15:
    print("It's warm, wear a long-sleeve T-shirt")
elif temperature > 10:
    print("It's cool, wear a jacket")
else:
    print("It's cold, wear a down jacket")
# ------------------------------------------------------------
# Case 2: Amusement park ticket
age = 13
height = 160  # cm
print("\n=== Amusement Park Project Recommendations ===")
if age >= 14 and height >= 150:
    print("You can ride the roller coaster! 🎒")
else:
    print("The roller coaster has age and height restrictions, let's ride the carousel instead! 🎠")
if age < 6 or age >= 65:
    print("You can enjoy a discounted ticket!")
elif age < 18 and age >= 6:
    print("Students can enjoy half-price discounts!")
else:
    print("Need to buy a full-price ticket")

Chapter 6: Loops – Making the Program “Repeat Tasks” πŸ”„

6.1 for Loop – A Loop with a Known Number of Iterations

Life Analogy: Just like in PE class, the teacher counts the number of students participating in physical exercise.

  • Counting from the first student to the last student

  • Each student will be counted once

# Basic syntax
for variable in sequence:
    action to repeat
# Actual example: Roll call
students = ["Xiaoming", "Xiaohong", "Xiaogang", "Xiaoli"]
print("Starting roll call:")
for student in students:
    print(student + " is here!")
# Output:
# Starting roll call:
# Xiaoming is here!
# Xiaohong is here!
# Xiaogang is here!
# Xiaoli is here!

6.2 range() Function – Generating a Sequence of Numbers

# range(5) generates 0,1,2,3,4
# range(1,6) generates 1,2,3,4,5
# range(1,10,2) generates 1,3,5,7,9
# Actual example: Reciting the multiplication table
print("=== Multiplication Table of 5 ===")
for i in range(1, 10):  # i from 1 to 9
    result = 5 * i
    print(f"5 Γ— {i} = {result}")

6.3 while Loop – Conditional Loop

Life Analogy: Just like doing homework until it’s finished

  • As long as the homework is not finished β†’ keep doing

  • Homework is finished β†’ stop

# Syntax
while condition:
    action to repeat
# Actual example: Doing homework
homework_finished = False
time_spent = 0  # Time spent (minutes)
print("Starting homework...")
while not homework_finished:
    time_spent += 30
    print(f"Already spent {time_spent} minutes on homework")
    # Assume homework is completed after 90 minutes
    if time_spent >= 90:
        homework_finished = True
        print("Great! Homework is done! πŸŽ‰")

6.4 Practical Application Cases

# Case 1: Calculate the sum from 1 to 100
total = 0
for i in range(1, 101):
    total += i
print(f"The sum from 1 to 100 is: {total}")
# --------------------------------------------------------
# Case 2: Guess the number game
import random
secret_number = random.randint(1, 10)  # Randomly generate a number from 1-10
guess_count = 0
max_guesses = 3
print("=== Guess the Number Game ===")
print("I have thought of a number from 1-10, you have 3 chances to guess!")
while guess_count < max_guesses:
    guess = int(input("What do you guess? "))
    guess_count += 1
    if guess == secret_number:
        print(f"Great! You guessed it! It's {secret_number} πŸŽ‰")
        break
    elif guess < secret_number:
        print("Too low, try a bigger number!")
    else:
        print("Too high, try a smaller number!")
    print(f"You have {max_guesses - guess_count} chances left")
if guess_count == max_guesses and guess != secret_number:
    print(f"Game over! The correct answer is {secret_number}")

Chapter 7: Comprehensive Exercises πŸ†

7.1 Student Grade Analysis System: Ask the teacher for a list of grades for the mid-term exam in Chinese, Math, and English for the class, and complete a statistical analysis of how many students have a total score above 250.

7.2 Daily Review Plan Reminder: Based on your daily review plan, determine whether you have completed all review tasks before going to bed each day.

🌟 Study Tips

Key Points of Conditional Statements:

  1. Indentation is important: Python uses indentation to distinguish code blocks

  2. Conditional expressions: Use comparison operators (>, <, ==, etc.)

  3. Logical connections: Use and, or, not to connect multiple conditions

Key Points of Loops:

  1. for loop: Used when the number of iterations is known

  2. while loop: Used for loops based on conditions

  3. Avoid infinite loops: Ensure that the condition of the while loop will eventually become False

If you’re interested, you can challenge this task

Task 1: Write a program to determine if a given year is a leap year.

Task 2: Write a program to output the first 20 numbers of the Fibonacci sequence.

β€œLeap year” and β€œFibonacci sequence” are two mathematical concepts that you need to look up yourself.

PS: As usual, the answers will be published in the next issue.

Leave a Comment