Python_Day 3 Conditional Statements, logical operators, code blocks and scope
Conditional Statement
Conditional statement is if/else. By using If it should be followed with a condition and if it doesn’t it should be changed to else. By using a bathtub as an example we can code as follows:
water_level = 50
if water_level > 80:
print(“Drain water”)
else: print(“continue”)
A code for a ticketing box on a rollercoaster:
print(“Welcome to the rollercoaster”)
height = int(input(“What is your height in cm?”)
If height > 120:
print(“You can ride the rollercoaster!”)
#after the colon the next line of code with have an indention (Same indented code is in the same block of code)
else:
#else condition has to be on same line as if condition
print(“Sorry, you have to grow taller before you can ride this rollercoaster”)
Comparison operations
> means greater than
< means lesser than
>= means Greater than or equal to
<= means less than or equal to
== means equal to
!= means Not equal to
Odd or even exercise
Write a program that works out whether if a given number is an odd or even number.
Even numbers can be divided by 2 with no remainder.
6 ÷ 2 = 3 with no remainder.
therefore: 6 % 2 = 0
5 ÷ 2 = 2 x 2 + 1, remainder is 1.
therefore: 5 % 2 = 1
# Which number do you want to check?
number = int(input())
# 🚨 Don't change the code above 👆
# Write your code below this line 👇
# If the number can be divided by 2 with 0 remainder
if number % 2 == 0:
print("This is an even number.")
else:
print("This is an odd number.")
Nested if statements and elif statements
if condition:
if another condition:
do this
else:
do this
else:
do this
In elif statement, we can code as much conditions before the ending else
if condition 1:
elif condition:
else
Example elif statements for ticketing box on a rollercoaster
print("Welcome to the rollercoaster ride!")
height = int(input("What is your height?"))
if height >= 120:
print("You can ride the rollercoaster")
age = int(input("What is your age?"))
if age < 12:
print("Please pay $7.")
elif age <= 18:
print("Please pay $12.")
else:
print("Please pay $20.")
else:
print("You are unable to ride the rollercoaster")
Coding Exercise BMI 2.0
Write a program that interprets the Body Mass Index (BMI) based on a user's weight and height.
It should tell them the interpretation of their BMI based on the BMI value.
Under 18.5 they are underweight
Over 18.5 but below 25 they have a normal weight
Equal to or over 25 but below 30 they are slightly overweight
Equal to or over 30 but below 35 they are obese
Equal to or over 35 they are clinically obese.
# Enter your height in meters e.g., 1.55
height = float(input())
# Enter your weight in kilograms e.g., 72
weight = int(input())
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
BMI = weight / (height ** 2)
if BMI < 18.5:
print(f"Your BMI is {BMI}, you are underweight.")
elif BMI >= 18.5 < 25:
print(f"Your BMI is {BMI}, you have a normal weight.")
elif BMI >= 25 < 30:
print(f"Your BMI is {BMI}, you are slightly overweight.")
elif BMI >= 30 < 35:
print(f"Your BMI is {BMI}, you are obese.")
else:
print(f"Your BMI is {BMI}, you are clinically obese.")
Coding Exercise Leap Year
Write a program that works out whether if a given year is a leap year. A normal year has 365 days, leap years have 366, with an extra day in February.
This is how you work out whether if a particular year is a leap year.
on every year that is divisible by 4 with no remainder
except every year that is evenly divisible by 100 with no remainder
unless the year is also divisible by 400 with no remainder
# Which year do you want to check?
year = int(input())
# 🚨 Don't change the code above 👆
# Write your code below this line 👇 (Help with GPT)
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("Leap year")
else:
print("Not leap year")
Udemy code
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(“Leap year”)
else:
print(“Not leap year”)
else:
print(“Leap year”)
else:
print(“Not leap year”)
Pizza order exercise
Congratulations, you've got a job at Python Pizza! Your first job is to build an automatic pizza order program.
Based on a user's order, work out their final bill.
Small pizza (S): $15
Medium pizza (M): $20
Large pizza (L): $25
Add pepperoni for small pizza (Y or N): +$2
Add pepperoni for medium or large pizza (Y or N): +$3
Add extra cheese for any size pizza (Y or N): +$1
print("Thank you for choosing Python Pizza Deliveries!")
size = input() # What size pizza do you want? S, M, or L
add_pepperoni = input() # Do you want pepperoni? Y or N
extra_cheese = input() # Do you want extra cheese? Y or N
# 🚨 Don't change the code above 👆
# Write your code below this line 👇
bill = 0
if size == "S":
bill += 15
elif size == "M":
bill += 20
elif size == "L":
bill += 25
# Add pepperoni
if add_pepperoni == "Y":
if size == "S":
bill += 2
else:
bill += 3
# Add extra cheese for any size pizza
if extra_cheese == "Y":
bill += 1
print(f"Your final bill is: ${bill}.")
Logical Operators
How to combine different line of code? -> logical operators
1. A and B (both has to be true) if one is false then it will be false
2. C or D (both has to be false for the output to be false) if one is true output will be true
3. Not E (reverses the condition)
print("Welcome to the rollercoaster ride!")
height = int(input("What is your height?"))
if height >= 120:
print("You can ride the rollercoaster")
age = int(input("What is your age?"))
if age < 12:
bill = 7
print("Please pay $7.")
elif age <= 18:
bill = 12
print("Please pay $12.")
elif age >= 45 <= 55: #or elif age >= 45 and age <= 55:
bill = 0
print("The ride is free.")
else:
bill = 20
print("Please pay $20.")
#photos taken
want_photos = input("Do you want photos taken? Y or N. ")
if want_photos == "Y":
bill += 3
print(f"You total bill is ${bill}")
else:
print("You are unable to ride the rollercoaster")
Love calculator exercise
You are going to write a program that tests the compatibility between two people.
To work out the love score between two people:
Take both people's names and check for the number of times the letters in the word TRUE occurs.
Then check for the number of times the letters in the word LOVE occurs.
Then combine these numbers to make a 2 digit number.
For Love Scores less than 10 or greater than 90, the message should be:
"Your score is *x*, you go together like coke and mentos."
For Love Scores between 40 and 50, the message should be:
"Your score is *y*, you are alright together."
Otherwise, the message will just be their score. e.g.:
"Your score is *z*."
print("The Love Calculator is calculating your score...")
name1 = input() # What is your name?
name2 = input() # What is their name?
# 🚨 Don't change the code above 👆
# Write your code below this line 👇
t = (name1 + name2).count("t") + (name1 + name2).count("T")
r = (name1 + name2).count("r") + (name1 + name2).count("R")
u = (name1 + name2).count("u") + (name1 + name2).count("U")
e = (name1 + name2).count("e") + (name1 + name2).count("E")
true_total = t + r + u + e
l = (name1 + name2).count("l") + (name1 + name2).count("L")
o = (name1 + name2).count("o") + (name1 + name2).count("O")
v = (name1 + name2).count("v") + (name1 + name2).count("V")
e = (name1 + name2).count("e") + (name1 + name2).count("E")
love_total = l + o + v + e
love_score = f"{true_total}{love_total}"
love_score = int(love_score)
if (love_score < 10 or love_score > 90):
print(f"Your score is {love_score}, you go together like coke and mentos.")
elif (love_score >= 40 and love_score <= 50):
print(f"Your score is {love_score}, you are alright together.")
else:
print(f"Your score is {love_score}.")
Udemy code
combined_names = name1 + name2
lower_name = combined_name.lower()
t = lower_name.count(“t”)
r = lower_name.count(“r”)
u = lower_name.count(“u”)
e = lower_name.count(“e”)
first_digit = t + r + u + e
l = lower_name.count(“l”)
o = lower_name.count(“o”)
v= lower_name.count(“v”)
e = lower_name.count(“e”)
second_digit = l + o + v + e
score = int(str(first_digit) + str(second_digit))
if (score < 10) or (score >90):
print(f"Your score is {score}, you go together like coke and mentos.")
elif (score >= 40) and (score <= 50)
print(f"Your score is {score}, you are alright together.")
else:
print(f"Your score is {score}.")
Day 3 Project: Treasure Island
print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.")
crossroad = input("There is a crossroad, choose left or right.").lower()
if crossroad == "right":
print("You have fallen into a hole and died. Game over")
if crossroad == "left":
river = input("You have come across a river, You can choose to either swim or wait.").lower()
if river == "swim":
print("While swimming an alligator attacked and died. Game over")
if river == "wait":
print("A small boat floats down and you are able to get on it. It takes you to the other side with three doors.")
door = input("There is a blue, red and yellow door. Choose one.").lower()
if door == "blue":
print("You were attacked by lizardmen and died. Game over")
elif door == "red":
print("Opened a portal to a chaos wasteland. Game over")
else:
print("You found the lost treasure. You won!")
Other coding format version
print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.")
choice1 = input(‘You\ ‘re at a crossroad, where do you want to go? Type “left” or “right”.’).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.’).lower()
if choice2 == “wait”:
choice3 = input(“You arrive at the island. There is a house with 3 doors. One red, one yellow and one blue. Which color do you choose?”).lower()
if choice3 == “red”:
print(“Game Over”)
elif choice3 == “yellow”:
print(“You won”)
elif choice3 == “blue”:
print(“Game Over”)
else:
print(“Game Over”)
else:
print(“Attacked by a trout. Game Over”)
else:
print(“Fell into a hole. Game Over”)
'Coding : Python' 카테고리의 다른 글
Python_Day 6 (0) | 2023.11.30 |
---|---|
Python_Day 5 (1) | 2023.11.23 |
Python_Day 4 (0) | 2023.11.17 |
Python_Day 2 (0) | 2023.11.10 |
Python_Day 1 (0) | 2023.11.10 |