Welcome to Day 2 of PythonForAI! Today, we will delve into control structures, which are essential for making decisions and repeating tasks in your code. We will cover conditional statements and loops, followed by solving some practical problems to reinforce these concepts. Let’s get started!
Table of Contents
Topics to Cover
1. Conditional Statements (if, elif, else)
Conditional statements allow you to execute certain parts of your code based on specific conditions.
Syntax
if condition:
# code block to execute if condition is true
elif another_condition:
# code block to execute if another_condition is true
else:
# code block to execute if all conditions are false
Example
age = 18
if age < 18:
print("You are a minor.")
elif age == 18:
print("You just became an adult!")
else:
print("You are an adult.")
2. Loops (for, while)
Loops are used to execute a block of code repeatedly.
For Loop
A for
loop is used for iterating over a sequence (such as a list, tuple, dictionary, set, or string).
Syntax
for variable in sequence:
# code block to execute
Example
for i in range(5):
print(i)
While Loop
A while
loop is used to repeat a block of code as long as a condition is true.
Syntax
while condition:
# code block to execute
Example
count = 0
while count < 5:
print(count)
count += 1
Potential Problems to Solve
1. Write a Number Guessing Game
Let’s create a simple number guessing game. The program will randomly select a number between 1 and 100, and the user will try to guess it. The program will give hints if the guess is too high or too low.
Solution
import random
# Generate a random number between 1 and 100
number_to_guess = random.randint(1, 100)
guess = None
attempts = 0
print("Welcome to the Number Guessing Game!")
print("I have selected a number between 1 and 100. Can you guess it?")
while guess != number_to_guess:
# Get the user's guess
guess = int(input("Enter your guess: "))
attempts += 1
# Check the guess
if guess < number_to_guess:
print("Too low! Try again.")
elif guess > number_to_guess:
print("Too high! Try again.")
else:
print(f"Congratulations! You've guessed the number in {attempts} attempts.")
2. Create a Program that Prints All Even Numbers from 1 to 100
We’ll write a program that uses a loop to print all even numbers between 1 and 100.
Solution
print("Even numbers from 1 to 100:")
for number in range(1, 101):
if number % 2 == 0:
print(number)
Summary
Today, we explored control structures in Python, including conditional statements and loops. These constructs allow you to control the flow of your programs, making decisions and repeating tasks as needed. We also applied these concepts by creating a number guessing game and a program that prints all even numbers from 1 to 100.
Practice these concepts further to solidify your understanding. Tomorrow, we will dive into functions and how to use them to organize and reuse your code efficiently.
Feel free to leave any questions or comments below, and happy coding! 🐍🚀
Additional Resources
Frequently Asked Questions (FAQs)
Q1: What is the difference between if
, elif
, and else
?
if
checks the initial condition.elif
(short for “else if”) checks additional conditions if the previousif
orelif
conditions were not true.else
executes a block of code if none of the previous conditions were true.
Q2: Can a for
loop iterate over any sequence type?
Yes, a for
loop can iterate over any sequence type, including lists, tuples, strings, dictionaries, and sets.
Q3: How do I exit a loop prematurely?
You can use the break
statement to exit a loop prematurely. You can also use the continue
statement to skip the rest of the current iteration and move to the next iteration of the loop.
Q4: What is the difference between for
and while
loops?
A for
loop is typically used when you know the number of iterations beforehand (e.g., iterating over a sequence). A while
loop is used when the number of iterations is not known and depends on a condition being true or false.
Q5: How can I generate random numbers in Python?
You can use the random
module to generate random numbers. For example, random.randint(a, b)
generates a random integer between a
and b
(inclusive).