TIL: Python Basics Day 3 - if/else

이다연·2020년 11월 23일
0

Udemy Python Course

목록 보기
3/64

if/else statement

Conditional statement: depending on a particular condition, we would do A or B

if condition:
	do this
else:
	do this

Comparison Operators

'> Greater than
< Less than
= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to

Exercise. Rollercoaster

print("Welcome to the rollercoaster!")
height = int(input("What is your height in cm? "))
if height >= 140:
  print("You can ride the rollercoaster!")
else:
  print("Sorry")

Exercise 3.1 Odd or Even

modulo '%' : The modulo (or "modulus" or "mod") is the remainder after dividing one number by another.

if number % 2 == 1:
  print("This is an odd number.")
else: 
  print("This is an even number.")

Nested if /elif/ else

Flow chart

Exercise 3.2 BMI Calcullator

you don't need to write the previous condition on the second line as '18.5'< BMI < 25. As the first condition stated it before. Reason why second code is executed is becasue it already met the condition on the first ‘if’.

# 🚨 Don't change the code below 👇
height = float(input("enter your height in m: "))
weight = float(input("enter your weight in kg: "))
# 🚨 Don't change the code above 👆

#Write your code below this line 👇

bmi = round( weight/height**2)


if bmi < 18.5:
  print(f"Your BMI is {bmi}, you are underweight")
elif bmi <25:
  print(f"Your BMI is {bmi}, you are a normal weight.")
elif bmi < 30:
  print(f"Your BMI is {bmi}, you are slightly obese.")
elif bmi > 35:
  print(f"Your BMI is {bmi}, you are obese.")
else:
  print(f"Your BMI is {bmi}, you are clinically obese.")

Exercise 3.3 Leap Year

Create a flow chart first!
This task was tricky as the english statement itself was tricky at first. (except, unless...)
I solved it by using variables like year, year_1, _2 but Angela's solution looks more readable. I managed to write the nested ifs while solving it, but failed to use else: part. Maching 'else:' part was the key!

#<my code>
if year % 4 == 0:
  year_1 = year
else:
  print("not a leap year") 

if year_1 % 100 == 0:
  year_2 = year_1
else: 
  print(f"{year} is a leap year!""leap year")

if year_2 % 400 == 0:
  print(f"{year} is a leap year!""leap year")
else:
  print("not a leap year")

  
#<solution>
if year % 4 == 0:
  if year % 100 == 0:
    if year % 400 == 0:
      print("leap year")
    else: print("not")
  else:
    print("leap")
else: 
  print("not")

Multiple if

When you use if, elif, else, Once the first if is correct, it will bypass the others. However if you want all conditions being chekced, you need to list each ifs as below:

if condition1:
	do A
if condition2:
	do B
if condition3:
	do C

Indentation matters a huge deal!

Exercise 3.4 Pizza Order Practice

"Nested ifs" structure is used in this exercise. Instead of repeating 2nd question about pepperoni after each ifs, creating a independant set is much easier to edit in the future.

# 🚨 Don't change the code below 👇
print("Welcome to 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
  if add_pepperoni == "Y":
    bill += 2
elif size == "M":
  bill += 20
  if add_pepperoni == "Y":
    bill += 3
elif size == "L": 
  bill += 25
  if add_pepperoni == "Y":
    bill += 3

if extra_cheese == "Y":
  bill += 1

print(f"Your final bill is: ${bill}.")


#Angela's
bill = 0
#1st if
if size == "S":
  bill += 15
  bill += 2
elif size == "M":
  bill += 20
  bill += 3
elif size == "L": 
  bill += 25
  bill += 3
#2nd if
if add_pepperoni == "Y":
  if size == "S": #nested if
    bill += 2
  else:
    bill += 3
#3rd if
if extra_cheese == "Y":
  bill += 1

print(f"Your final bill is: ${bill}.")

Logical Operators: and, or, not

A and B
Both needs to be True to be True, but when one of them is false, it's False

C or D
only one of them needs to be True to be True.
if only when both C and D are false, does this statement become actually false.

not operator:
reverse a condition

Exercise 3.5 Love Calculator

lower() and count()
hi = "HihiHI".lower()
print(hi)
print(hi.count("i")) -> count function only counts lowercase!!

# 🚨 Don't change the code below 👇
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
# 🚨 Don't change the code above 👆

#Write your code below this line 👇


names = (name1 + name2).lower()

num_true = 0
#for i in "true":
  #num_true += names.count(i)
num_true += names.count("t")
num_true += names.count("r")
num_true += names.count("u")
num_true += names.count("e")

num_love = 0
num_love += names.count("l")
num_love += names.count("o")
num_love += names.count("v")
num_love += names.count("e")

str_total = str(num_true) + str(num_love)
total = int(str_total)

if (10 > total) or (total > 90):
  print(f"Your score is {total}, you go together like coke and mentos.")

elif (40 <= total) or (total <= 50):
  print(f"Your score is {total}, you are alright together.")

else:
  print(f"Your score is {total}.")

3 Project

I was quite proud that I made this game hahahaah. I am quite comfortable with a flow chart logic now.

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_.--""___/______/______/______/____
/______/______/______/______/______/______/______/______/______/______/_____ /
*******************************************************************************
''')
print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.") 

crossroad = input("You\'re at a corssroad, would you go 'right' or 'left'?")

# with blackslash, you can use ' inside ""

lower_crossroad = crossroad.lower()

if lower_crossroad == "left":
  pond = input("You've come to a lake, 'swim' or 'wait'? ")  
  lower_pond = pond.lower()
  if lower_pond == "swim":
    door = input("There are three doors, which one would you choose: 'Red', 'Yellow', 'Blue'? ")
    lower_door = door.lower()
    if lower_door == "blue":
      print("You found a dolphin! You Won!")
    elif lower_door == "red":
      print("You burned by fire. Game Over")
    else:
      print("You spilt curry on your bed sheet. House owner got angry. Game Over")
  else:
    print("You waited there for 100 years. Game Over")    
else:
  print("You fall into a hole. Game Over")

ASCII ART

profile
Dayeon Lee | Django & Python Web Developer

0개의 댓글