Loops and Conditional Statements in Python
Loops and conditional statements are fundamental building blocks of programming in Python. These constructs allow programmers to automate repetitive tasks and control the flow of their programs based on certain conditions. In this article, we will explore loops and conditional statements in Python with examples.
Loops
Loops allow us to execute a block of code repeatedly. There are two types of loops in Python: for loops and while loops.
for Loops
A for loop is used to iterate over a sequence of elements, such as a list, tuple or string. The basic syntax of a for loop is as follows:
for element in sequence:
# execute code
The element variable takes on the value of each element in the sequence one at a time, and the code inside the loop is executed for each element. Here is an example of a for loop that prints out the elements of a list:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
while Loops
A while loop is used to repeatedly execute a block of code as long as a certain condition is true. The basic syntax of a while loop is as follows:
while condition:
# execute code
The condition is a Boolean expression that is evaluated at the beginning of each iteration of the loop. If the condition is true, the code inside the loop is executed. Here is an example of a while loop that counts down from 5 to 1:
i = 5
while i > 0:
print(i)
i -= 1
Output:
5
4
3
2
1
Conditional Statements
Conditional statements allow us to execute different blocks of code depending on whether certain conditions are true or false. There are two types of conditional statements in Python: if statements and if-else statements.
if Statements
An if statement is used to execute a block of code if a certain condition is true. The basic syntax of an if statement is as follows:
if condition:
# execute code
The condition is a Boolean expression that is evaluated. If it is true, the code inside the if statement is executed. Here is an example of an if statement that checks if a number is positive:
x = 5
if x > 0:
print("x is positive")
Output:
x is positive
if-else Statements
An if-else statement is used to execute one block of code if a certain condition is true, and another block of code if the condition is false. The basic syntax of an if-else statement is as follows:
if condition:
# execute code if condition is true
else:
# execute code if condition is false
The condition is a Boolean expression that is evaluated. If it is true, the code inside the if statement is executed. If it is false, the code inside the else statement is executed. Here is an example of an if-else statement that checks if a number is positive or negative:
x = -5
if x > 0:
print("x is positive")
else:
print("x is negative")
Output:
x is negative
if-elif Statements
An if-elif statement is used to execute one block of code if a certain condition is true, and another block of code if a different condition is true. The basic syntax of an if-elif statement is as follows:
if condition1:
# execute code if condition1 is true
elif condition2:
# execute code if condition2 is true
The condition1 is a Boolean expression that is evaluated. If it is true, the code inside the first if statement is executed. If it is false, the program moves on to the next elif statement. If condition2 is true, the code inside the second if statement is executed. If condition2 is also false, the program moves on to the next elif statement, and so on.
Here is an example of an if-elif statement that checks if a number is positive, negative, or zero:
x = -5
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
Output:
x is negative
In this example, if x is greater than 0, the first if statement is executed and "x is positive" is printed. If x is not greater than 0, the program moves on to the elif statement. If x is less than 0, the second if statement is executed and "x is negative" is printed. If x is not less than 0, the program moves on to the else statement. Since x is not greater than 0 and not less than 0, it must be equal to 0, so "x is zero" is printed.
Conclusion
Loops and conditional statements are powerful constructs that allow programmers to automate repetitive tasks and control the flow of their programs based on certain conditions. In this article, we explored for loops, while loops, if statements, and if-else statements in Python with examples. By mastering these constructs, you will be well on your way to becoming a proficient Python programmer.
Number Guess Game Project
Project Description
Our program will be a simple guessing game. The computer will generate a random number between 1 and 10, and the user will have three chances to guess the number. After each guess, the program will provide feedback to the user based on whether their guess was too high or too low. If the user guesses the correct number, they win the game. If they do not guess the number correctly in three tries, they lose the game.
Source Code
Here is the source code for our program:
import random
# generate a random number between 1 and 10
number = random.randint(1, 10)
# set the number of chances
chances = 3
# loop through the chances
for i in range(chances):
# get the user's guess
guess = int(input("Guess a number between 1 and 10: "))
# check if the guess is correct
if guess == number:
print("Congratulations! You guessed the number.")
break
# check if the guess is too high
elif guess > number:
print("Your guess is too high. Try again.")
# check if the guess is too low
else:
print("Your guess is too low. Try again.")
# check if the user has any chances left
if i == chances - 1:
print("Sorry, you ran out of chances. The number was", number)
Let's break down the code:
First, we import the random library to generate a random number. We use the randint function to generate a random integer between 1 and 10, inclusive.
import random
# generate a random number between 1 and 10
number = random.randint(1, 10)
Next, we set the number of chances the user has to guess the number. In our case, we set it to three.
# set the number of chances
chances = 3
We then loop through the chances using a for loop. The range function generates a sequence of numbers from 0 to chances - 1.
# loop through the chances
for i in range(chances):
Inside the loop, we get the user's guess using the input function, and convert it to an integer using the int function.
# get the user's guess
guess = int(input("Guess a number between 1 and 10: "))
We then use conditional statements to check if the user's guess is correct, too high, or too low. If the guess is correct, we print a message congratulating the user and break out of the loop using the break keyword. If the guess is too high or too low, we print a message telling the user to try again.
# check if the guess is correct
if guess == number:
print("Congratulations! You guessed the number.")
break
# check if the guess is too high
elif guess > number:
print("Your guess is too high. Try again.")
# check if the guess is too low
else:
print("Your guess is too low. Try again.")
Finally, we check if the user has any chances left. If the user has used up all their chances and still has not guessed the number correctly, we print a message telling them the number and that they have lost the game.
# check if the user has any chances left
if i == chances - 1:
print("Sorry, you ran out of chances. The number was", number)
Conclusion
In this project, we created a simple guessing game using loops and conditional statements in Python. The program demonstrates the use of the random library, the for loop, the range function, the input function, the int function, and conditional statements (if, elif, and else). This project can be extended or modified to include additional features, such as keeping score or allowing the user to choose the range of numbers to guess from.