Python - Conditional Statements, Logical Operators, Code Blocks, and Scope
Todays Goal:
print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.")
#Write your code below this line ๐
choice1 = input('You\'re at a cross road. Where do you want to go? Type "left" or "right" \n').lower()
if choice1 == "left":
choice2 = input('You\'ve come to a lake. There is an island in the middle of the lake. Type "wait" to wait for a boat. Type "swim" to swim across. \n').lower()
if choice2 == "wait":
choice3 = input("You arrive at the island unharmed. There is a house with 3 doors. One red, one yellow and one blue. Which colour do you choose? \n").lower()
if choice3 == "red":
print("It's a room full of fire. Game Over.")
elif choice3 == "yellow":
print("You found the treasure! You Win!")
elif choice3 == "blue":
print("You enter a room of beasts. Game Over.")
else:
print("You chose a door that doesn't exist. Game Over.")
else:
print("You get attacked by an angry trout. Game Over.")
else:
print("You fell into a hole. Game Over.")
Control Flow with if / else and Conditional Operators python
In Python, you can use the if
and else
statements along with conditional operators to create control flow in your code. Conditional operators allow you to compare values and make decisions based on the result of the comparison.
Here's an example of using if
and else
with conditional operators:
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
In this example, the variable x
is assigned a value of 10. The if
statement checks if x
is greater than 5 using the >
operator. If the condition is true, it executes the code block under the if
statement, which prints "x is greater than 5". If the condition is false, it executes the code block under the else
statement, which prints "x is not greater than 5".
You can also use other conditional operators such as <
(less than), >=
(greater than or equal to), <=
(less than or equal to), ==
(equal to), and !=
(not equal to) to compare values.
Additionally, you can combine multiple conditions using logical operators such as and
, or
, and not
:
x = 10
if x > 5 and x < 20:
print("x is between 5 and 20")
else:
print("x is not between 5 and 20")
In this example, the if
statement checks if x
is greater than 5 and less than 20. If both conditions are true, it executes the code block under the if
statement. Otherwise, it executes the code block under the else
statement.
By using if
, else
, and conditional operators, you can control the flow of your code based on different conditions and make your program more dynamic and responsive.
Example:
print("Welcome to the rollercoaster!")
height = int(input("What is your height in cm? "))
if height >= 120:
print("You can ride the rollercoaster!")
else:
print("Sorry, you have to grow taller before you can ride.")
output:
Welcome to the rollercoaster!
What is your height in cm? 100
Sorry, you have to grow taller before you can ride.
Explanation:
In the code you provided, the program prompts the user for their height in centimeters using the input()
function. The input is then converted to an integer using the int()
function and stored in the variable height
.
The program then uses an if
statement to check if the value of height
is greater than or equal to 120. If the condition is true, meaning the person's height is 120 cm or taller, it prints "You can ride the rollercoaster!". Otherwise, if the condition is false, meaning the person's height is less than 120 cm, it prints "Sorry, you have to grow taller before you can ride."
In the example output you provided, the user enters a height of 100 cm, which is less than 120 cm. Therefore, the condition in the if
statement evaluates to false, and the program executes the code block under the else
statement, printing "Sorry, you have to grow taller before you can ride."
Nested if statements and elif statements
Nested if
statements and elif
statements in Python allow you to create more complex conditional structures by adding additional levels of conditions and branching.
Nested if
statements are if
statements that are placed inside another if
or else
block. This allows for more granular control and the ability to check for multiple conditions.
Here's an example of using nested if
statements:
x = 10
y = 5
if x > 5:
print("x is greater than 5")
if y > 2:
print("y is greater than 2")
In this example, the outer if
statement checks if x
is greater than 5. If the condition is true, it prints "x is greater than 5" and then enters the inner if
statement. The inner if
statement checks if y
is greater than 2. If the condition is true, it prints "y is greater than 2".
Note that the inner if
statement is only executed if the outer if
condition is true. If the outer if
condition is false, the inner if
statement is skipped entirely.
On the other hand, elif
statements allow you to check multiple conditions sequentially, providing an alternative option if the previous conditions are not met.
Here's an example of using elif
statements:
x = 10
if x < 5:
print("x is less than 5")
elif x < 10:
print("x is less than 10 but greater than or equal to 5")
else:
print("x is greater than or equal to 10")
In this example, the program checks the value of x
against multiple conditions using elif
statements. It first checks if x
is less than 5. If the condition is true, it prints "x is less than 5". If the condition is false, it moves to the next elif
statement, which checks if x
is less than 10. If this condition is true, it prints "x is less than 10 but greater than or equal to 5". If neither of the previous conditions is true, the program executes the code block under the else
statement, printing "x is greater than or equal to 10".
By using nested if
statements and elif
statements, you can create more intricate conditional structures to handle various scenarios and conditions in your code.
Multiple if Statements in Succession
Using multiple if
statements in succession allows you to check multiple conditions independently. Each if
statement is evaluated separately, regardless of the outcome of the previous if
statements. This can be useful when you want to perform different actions based on multiple conditions.
Here's an example of using multiple if
statements in succession:
x = 10
if x > 5:
print("x is greater than 5")
if x < 15:
print("x is less than 15")
if x % 2 == 0:
print("x is even")
In this example, there are three separate if
statements. The first if
statement checks if x
is greater than 5 and prints "x is greater than 5" if the condition is true. The second if
statement checks if x
is less than 15 and prints "x is less than 15" if the condition is true. The third if
statement checks if x
is even (i.e., divisible by 2) using the modulo operator (%
) and prints "x is even" if the condition is true.
Note that each if
statement is evaluated independently. Even if one if
statement is true, the others will still be evaluated. In the example, since x
is both greater than 5 and less than 15, both corresponding messages will be printed.
Using multiple if
statements in succession gives you more flexibility in handling different conditions separately. However, keep in mind that if the conditions are related or mutually exclusive, you may want to consider using elif
statements to create a more structured and efficient conditional flow.
Example:
print("Welcome to the rollercoaster!")
height = int(input("What is your height in cm? "))
bill = 0
if height >= 120:
print("You can ride the rollercoaster!")
age = int(input("What is your age? "))
if age < 12:
bill = 5
print("Child tickets are $5.")
elif age <= 18:
bill = 7
print("Youth tickets are $7.")
else:
bill = 12
print("Adult tickets are $12.")
wants_photo = input("Do you want a photo taken? Y or N. ")
if wants_photo == "Y":
bill += 3
print(f"Your final bill is ${bill}")
else:
print("Sorry, you have to grow taller before you can ride.")
Output:
Welcome to the rollercoaster!
What is your height in cm? 120
You can ride the rollercoaster!
What is your age? 29
Adult tickets are $12.
Do you want a photo taken? Y or N. y
Your final bill is $12
n the provided code, multiple if
statements are used in succession to handle different conditions and perform various actions based on those conditions.
Let's go through the code step by step:
The program starts by printing the "Welcome to the rollercoaster!" message.
The user is prompted to enter their height in centimeters, and the input is stored in the
height
variable as an integer.The first
if
statement checks if the height is greater than or equal to 120. If the condition is true, it proceeds to the code block under thisif
statement. Otherwise, it jumps to theelse
block and prints "Sorry, you have to grow taller before you can ride."Inside the first
if
block, the program prints "You can ride the rollercoaster!" because the height condition is met.The user is then prompted to enter their age, and the input is stored in the
age
variable as an integer.The nested
if-elif-else
structure is used to determine the ticket price based on the age of the rider. If the age is less than 12, the code block under the firstif
statement in this nested structure executes, and thebill
variable is set to 5, and "Child tickets are $5." is printed. If the age is between 12 and 18 (inclusive), the code block under theelif
statement executes, and thebill
variable is set to 7, and "Youth tickets are $7." is printed. Otherwise, if none of the previous conditions are met, the code block under theelse
statement executes, and thebill
variable is set to 12, and "Adult tickets are $12." is printed.The user is asked whether they want a photo taken, and their response is stored in the
wants_photo
variable.The program uses another
if
statement to check if the user wants a photo taken (wants_photo == "Y"
). If the condition is true, thebill
variable is incremented by 3.Finally, the program prints the final bill by using an f-string and displays "Your final bill is $" followed by the value of the
bill
variable.
In the example output you provided, the user enters a height of 120, which satisfies the condition of the first if
statement. The program proceeds to ask for the age, and the user enters 29. Since the age is not less than 12 or between 12 and 18, the code block under the else
statement in the nested structure executes. The program then asks if the user wants a photo taken, and they respond with "y". The final bill is calculated as $12, and the program prints "Your final bill is $12" accordingly.
Using multiple if
statements in succession allows for a more detailed and flexible handling of different conditions in your code. Each if
statement is evaluated independently, allowing you to perform specific actions based on the condition being true.
Logical Operators
Logical operators in Python allow you to combine or manipulate boolean values. The three main logical operators are and
, or
, and not
. They are used to create more complex boolean expressions by combining multiple conditions.
Here's an explanation of each logical operator:
and
: Theand
operator returnsTrue
if both the left-hand side and the right-hand side of the operator areTrue
. Otherwise, it returnsFalse
.x = 5 y = 10 if x > 0 and y > 0: print("Both x and y are positive numbers.")
In this example, the condition
x > 0
evaluates toTrue
and the conditiony > 0
also evaluates toTrue
. Since both conditions areTrue
, the message "Both x and y are positive numbers." will be printed.or
: Theor
operator returnsTrue
if either the left-hand side or the right-hand side of the operator isTrue
. It returnsFalse
only if both sides areFalse
.x = 5 y = -2 if x > 0 or y > 0: print("At least one of x or y is a positive number.")
In this example, the condition
x > 0
evaluates toTrue
and the conditiony > 0
evaluates toFalse
. Since at least one condition isTrue
, the message "At least one of x or y is a positive number." will be printed.not
: Thenot
operator negates the boolean value of a condition. If the condition isTrue
,not
returnsFalse
. If the condition isFalse
,not
returnsTrue
.x = 5 if not x > 10: print("x is not greater than 10.")
In this example, the condition
x > 10
evaluates toFalse
. Thenot
operator negates the value, resulting inTrue
. Therefore, the message "x is not greater than 10." will be printed.
These logical operators can be used to create more complex conditions by combining multiple expressions. They help you control the flow of your code based on various conditions and make your programs more flexible and robust.
Example:
print("Welcome to the rollercoaster!")
height = int(input("What is your height in cm? "))
bill = 0
if height >= 120:
print("You can ride the rollercoaster!")
age = int(input("What is your age? "))
if age < 12:
bill = 5
print("Child tickets are $5.")
elif age <= 18:
bill = 7
print("Youth tickets are $7.")
elif age >= 45 and age <= 55:
print("Everything is going to be ok. Have a free ride on us!")
else:
bill = 12
print("Adult tickets are $12.")
wants_photo = input("Do you want a photo taken? Y or N. ")
if wants_photo == "Y":
bill += 3
print(f"Your final bill is ${bill}")
else:
print("Sorry, you have to grow taller before you can ride.")
Output:
Welcome to the rollercoaster!
What is your height in cm? 121
You can ride the rollercoaster!
What is your age? 13
Youth tickets are $7.
Do you want a photo taken? Y or N. y
Your final bill is $7
In the provided code, logical operators are used to introduce additional conditions for determining the ticket price and offering a free ride. Let's explain the use of logical operators in the code:
The first logical operator used is the
and
operator (and age >= 45 and age <= 55
). This condition is placed within theelif
statement and checks if the age is between 45 and 55 (inclusive). If the age satisfies this condition, the message "Everything is going to be ok. Have a free ride on us!" is printed. This demonstrates that the person within the specified age range receives a special offer, without requiring a specific ticket price.The second logical operator used is the equality operator (
==
). It is used to check if the user wants a photo taken by comparing the input (wants_photo
) with the string "Y". If the user enters "Y", the conditionwants_photo == "Y"
evaluates toTrue
, and the bill is increased by 3 using the+=
operator.
These logical operators allow for additional conditions to be checked and actions to be taken based on those conditions. In the example output you provided, the person's height is 121 cm, which is greater than or equal to 120 cm, so they can ride the rollercoaster. Their age is 13, falling within the range specified by the elif
statement (age <= 18
), resulting in the message "Youth tickets are $7." being printed. The user wants a photo taken, so the final bill is $7.
Day -3 Assignment
Try to achieve Treasure Island Game
print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.")
#Write your code below this line ๐
choice1 = input('You\'re at a cross road. Where do you want to go? Type "left" or "right" \n').lower()
if choice1 == "left":
choice2 = input('You\'ve come to a lake. There is an island in the middle of the lake. Type "wait" to wait for a boat. Type "swim" to swim across. \n').lower()
if choice2 == "wait":
choice3 = input("You arrive at the island unharmed. There is a house with 3 doors. One red, one yellow and one blue. Which colour do you choose? \n").lower()
if choice3 == "red":
print("It's a room full of fire. Game Over.")
elif choice3 == "yellow":
print("You found the treasure! You Win!")
elif choice3 == "blue":
print("You enter a room of beasts. Game Over.")
else:
print("You chose a door that doesn't exist. Game Over.")
else:
print("You get attacked by an angry trout. Game Over.")
else:
print("You fell into a hole. Game Over.")
Output:
Welcome to Treasure Island.
Your mission is to find the treasure.
You're at a cross road. Where do you want to go? Type "left" or "right"
left
You've come to a lake. There is an island in the middle of the lake. Type "wait" to wait for a boat. Type "swim" to swim across.
wait
You arrive at the island unharmed. There is a house with 3 doors. One red, one yellow and one blue. Which colour do you choose?
yellow
You found the treasure! You Win!
If you miss The 100 days of the Python - Day - 01 see here
If you miss The 100 days of the Python - Day - 02 see here
#100DaysofCode #Python
Subscribe to my newsletter
Read articles from Ganesh Balimidi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by