๐ฉ๐ผโ๐ป Day3 - #100DaysOfCode in Python
Day 3 - Beginner - Control Flow and Logical Operators
Day 3 completed! ๐คฉ
Today has been an intense day, lots of learning and really looking forward to continue every day with this challenge! ๐ช๐ป
I leave you the great part of exercises to be of use for those who start this #100DaysOfCode adventure or those who are just curious about Python. ๐ค
Go ahead!!
Today's Goals:
Learn enough to build a Choose your own adventure game
In order to build this, I had to tackle some skills including working with conditional statements (if/elif/else), logical operators and more! And by the way, lots and lots of practice! ๐ฉ๐ผโ๐ป
What Iโve seen:
โ
Conditional Statements
โ
Logical Operators
โ
Code Blocks and Scope
What I Learned Today:
๐ฆ First of all, Iโd like to mention that I found this website where it explains in a very simple way both, logical operators and conditional statements and their use (actually the web is about learning C#, but it works for any language that we are learning):
Conditional Statements
if / elif / else:
Conditional statements
if
,else
, andelif
(short for else if) in Python are control structures that allow you to execute different blocks of code based on the outcome of one or more conditions. They are fundamental to programming, allowing for decision-making within the code.if condition: do this else: do this
if
: Evaluates a condition and executes the associated block of code if the condition is true.if condition: # code to execute if the condition is true
elif
: Follows anif
statement and provides an additional condition to check if the previousif
orelif
was false.if condition1: # code to execute if condition1 is true elif condition2: # code to execute if condition2 is true, but condition1 was false
else
: Concludes anif
/elif
chain and executes a block of code if none of the preceding conditions are true.if condition1: # code to execute if condition1 is true elif condition2: # code to execute if condition2 is true and condition1 was false else: # code to execute if both condition1 and condition2 were false
Conditional statements evaluate expressions for a Boolean value of True
or False
and direct the flow of execution accordingly. They can include logical operators (and
, or
, not
) and comparisons (==
, !=
, >
, <
, >=
, <=
) to form complex conditions.
Example:
water_level = 50
if water_level > 80:
print("Drain water")
else:
print("Continue")
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(f"Sorry, you have to grow {120 - height} more cm to ride the rollercoaster.")
Conditional statements evaluate expressions for a Boolean value of True
or False
and direct the flow of execution accordingly. They can include logical operators (and
, or
, not
) and comparisons (==
, !=
, >
, <
, >=
, <=
) to form complex conditions.
Nested if / else
Nested
if/else
statements in Python are conditional statements placed inside other conditional statements. They allow for more complex decision-making paths by letting you check for further conditions after a previous condition has been met.For example:
if condition1: # code to execute if condition1 is true if condition2: # code to execute if both condition1 and condition2 are true else: # code to execute if condition1 is true but condition2 is not else: # code to execute if condition1 is false
Here, if
condition1
isTrue
, the program evaluatescondition2
. Ifcondition2
is alsoTrue
, it executes that block of code. Ifcondition2
isFalse
, it executes the code in theelse
block associated withcondition2
. Ifcondition1
isFalse
from the beginning, it skips the nestedif
and goes straight to theelse
block at the same level ascondition1
.Example:
#Nested if/else print("Welcome to the rollercoaster!") height = int(input("What is your height in cm? ")) if height > 120: print("You can ride the rollercoaster!") age = int(input("What is your age? ")) if age < 12: price = 5 print(f"Your ticket price is {price} dollars.") elif age < 18: price = 7 print(f"Your ticket price is {price} dollars.") else: price = 12 print(f"Your ticket price is {price} dollars.")
Multiple if
Using multiple
if
statements allow for the execution of separate blocks of code based on different conditions, independently of each other. Unlikeif/elif
structures where only one block executes, eachif
statement is evaluated and can trigger its block of code if its condition is true.For example:
if condition1: # This code runs if condition1 is true. if condition2: # This code runs independently if condition2 is true. if condition3: # This code runs independently if condition3 is true.
Here, all three conditions are checked, and the corresponding blocks of code could all run if each condition is
True
, rather than only one block running as in anif/elif/else
chain.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. ") #Once we land in this if statement, I'm going to have to add $3 #to theri bill no matter which value it's at the moment if wants_photo == "Y": bill += 3 #after this if statement is completed, I don't actually have #to write a companion else statement because in this case, #if the answer is no, then we're simply going to do nothing. #We're not going to do anything to the bill. print(f"Your final bill is ${bill}") else: print("Sorry, you have to grow taller before you can ride.")
Logical Operators
Logical operators in Python are used to combine conditional statements and are crucial for expressing more complex logic. The three logical operators are:
and
: ReturnsTrue
if both the operands (conditions) are true.or
: ReturnsTrue
if at least one of the operands is true.not
: ReturnsTrue
if the operand is false (inverts the boolean value).
Usage in conditional statements:
if condition1 and condition2:
# Executes if both condition1 and condition2 are true.
if condition1 or condition2:
# Executes if either condition1 or condition2 is true.
if not condition1:
# Executes if condition1 is false.
These operators are fundamental in constructing complex Boolean expressions, allowing for detailed decision-making paths in the code.
Code Sample:
Exercises
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.
e.g. 86 is even because 86 รท 2 = 43
43 does not have any decimal places. Therefore the division is clean.
e.g. 59 is odd because 59 รท 2 = 29.5
# Which number do you want to check? number = int(input()) # ๐จ Don't change the code above ๐ # Write your code below this line ๐ if number % 2 == 0: print(f"the number {number} is even") else: print(f"the number {number} is odd")
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.
The BMI is calculated by dividing a person's weight (in kg) by the square of their height (in m):
$$BMI = weight (kg) / height^2 (m2)$$
Important: you do not need to round the result to the nearest whole number. It's fine to print out a floating point number for this exercise. The interpretation message needs to include the words in bold from the interpretations above. e.g. underweight, normal weight, overweight, obese, 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 ๐
#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.
bmi = weight / height ** 2
if bmi >= 35:
print(f"Your BMI is {bmi}, you are clinically obese.")
elif bmi >= 30:
print(f"Your BMI is {bmi}, you are obese.")
elif bmi >= 25:
print(f"Your BMI is {bmi}, you are slightly overweight.")
elif bmi > 18.5:
print(f"Your BMI is {bmi}, you have a normal weight.")
else:
print(f"Your BMI is {bmi}, you are underweight.")
๐ช This is a difficult challenge! ๐ช 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. The reason why we have leap years is really fascinating, this video does it more justice.
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
If english is not your first language or if the above logic is confusing, try using this flow chart .
e.g. The year 2000:
2000 รท 4 = 500 (Leap)
2000 รท 100 = 20 (Not Leap)
2000 รท 400 = 5 (Leap!)
So the year 2000 is a leap year.
But the year 2100 is not a leap year because:
2100 รท 4 = 525 (Leap)
2100 รท 100 = 21 (Not Leap)
2100 รท 400 = 5.25 (Not Leap)
First solution:
# Which year do you want to check?
year = int(input())
# ๐จ Don't change the code above ๐
# Write your code below this line ๐
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(f"Year {year} is leap")
else:
print(f"Year {year} is not leap")
else:
print(f"Year {year} is leap")
else:
print(f"Year {year} is not leap")
Second solution -> Enhanced:
# Which year do you want to check?
year = int(input())
# ๐จ Don't change the code above ๐
# Write your code below this line ๐
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print(f"The year {year} is leap")
else:
print(f"The year {year} is not leap")
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 ๐
#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
bill = 0
if size == 'L':
bill += 25
elif size == 'M':
bill += 20
else:
bill += 15
if add_pepperoni == 'Y':
if size == 'S':
bill += 2
else:
bill += 3
if extra_cheese == 'Y':
bill += 1
print(f"Your final bill is: ${bill}.")
๐ช This is a difficult challenge! ๐ช 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 ๐
combined_names = name1 + name2
lower_names = combined_names.lower()
t = lower_names.count("t")
r = lower_names.count("r")
u = lower_names.count("u")
e = lower_names.count("e")
first_digit = t + r + u + e
l = lower_names.count("l")
o = lower_names.count("o")
v = lower_names.count("v")
e = lower_names.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 >= 10) or (score <= 50):
print(f"Your score is {score}, you are alright together.")
else:
print(f"You score is {score}.")
Project: Treasure Island
print('''
*******************************************************************************
| | | |
_________|________________.=""_;=.______________|_____________________|_______
| | ,-"_,="" `"=.| |
|___________________|__"=._o`"-._ `"=.______________|___________________
| `"=._o`"=._ _`"=._ |
_________|_____________________:=._o "=._."_.-="'"=.__________________|_______
| | __.--" , ; `"=._o." ,-"""-._ ". |
|___________________|_._" ,. .` ` `` , `"-._"-._ ". '__|___________________
| |o`"=._` , "` `; .". , "-._"-._; ; |
_________|___________| ;`-.o`"=._; ." ` '`."\` . "-._ /_______________|_______
| | |o; `"-.o`"=._`` '` " ,__.--o; |
|___________________|_| ; (#) `-.o `"=.`_.--"_o.-; ;___|___________________
____/______/______/___|o;._ " `".o|o_.--" ;o;____/______/______/____
/______/______/______/_"=._o--._ ; | ; ; ;/______/______/______/_
____/______/______/______/__"=._o--._ ;o|o; _._;o;____/______/______/____
/______/______/______/______/____"=._o._; | ;_.--"o.--"_/______/______/______/_
____/______/______/______/______/_____"=.o|o_.--""___/______/______/______/____
/______/______/______/______/______/______/______/______/______/______/_____ /
*******************************************************************************
''')
#Write your code below this line ๐
print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.")
choise_1 = input("You're at a cross road. Where do you want to go? Type 'left' or 'right'")
if choise_1 == "left":
choise_2 = 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 choise_2 == "wait":
choise_3 = input("You arrived 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 choise_3 == 'red':
print("It's a trap! You died.")
elif choise_3 == 'yellow':
print("You found the treasure!")
elif choise_3 == 'blue':
print("You enter a room of beasts. Game over!")
else:
print("You fell into a pit of snakes. Game over!")
else:
print("You got eaten by a shark. You are died.")
else:
print("You fell in the water. Game over!")
#https://www.draw.io/?lightbox=1&highlight=0000ff&edit=_blank&layers=1&nav=1&title=Treasure%20Island%20Conditional.drawio#Uhttps%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D1oDe4ehjWZipYRsVfeAx2HyB7LCQ8_Fvi%26export%3Ddownload
Thanks! ๐ซถ๐ป
๐Now you can also find me at the following links:
๐๐ป Instagram
๐๐ป Twitter
๐๐ป Medium
๐๐ป LinkedIn