PYTHON
  • PYTHON v3
  • Python IDE Setup
  • Python Programming
    • Python for ABS
      • Resources
      • Ch1 - Getting Started
      • Ch2 - Types, Variables and Simple I/O
  • Python For Network Engineers-Kirk Beyers
    • Resources
    • Python Fundamentals
  • Python Inststitute (PCAP)
    • Resources
    • Course Introduction
    • Python Essentials (Part 1)
      • Module 1
        • Fundamentals
        • What is Python
        • Starting your work with Python
      • Module 2
        • The Print Function
          • Section Summary
        • Literals
          • Section Summary
        • Operations- Data Manipulation Tools
          • Section Summary
        • Variables
          • Leaving Comments in Code
          • The input () Function
  • 100 Days Of Code
    • Resources
    • What You Have To Do !!
    • 100 DAY's
      • DAY 1: Working with Variables
      • Day 2: Data Types & String Manipulation
      • Day 3: Control Flow and Operators
      • Day 4: Randomisation and Lists
      • Day 5: For Loops, Range & Code Blocks
      • Day 6: Python Functions and Karel
      • Day 7: Hangman
      • SUMMARY
  • {Pirple}
    • Resources
Powered by GitBook
On this page
  • Control Flow with if/else and Conditional Operators
  • Nested if/else Statements
  • Multiple "IF" Statements
  • Logical Operators
  • AND:
  • OR:
  • Exercise - Rollercoaster + Logical Operators
  • Exercise: Love Calculator (Difficult)
  • Instructions
  • THINGS TO KNOW BEFORE WE START
  • Day 3 Project - Treasure Hunt

Was this helpful?

  1. 100 Days Of Code
  2. 100 DAY's

Day 3: Control Flow and Operators

Conditional Statements, Logical Operators, Code Blocks and Scope

PreviousDay 2: Data Types & String ManipulationNextDay 4: Randomisation and Lists

Last updated 4 years ago

Was this helpful?

Control Flow with if/else and Conditional Operators

if condition: do this else: do that water-level = 50 if water_level > 80: print("Drain Water") else: print("Continue")

Here's an example - Lets say you have a job at the theme-park and you have to write some code that will replace the ticket-box: Things to think about:-

  • Roller-coaster ride, kids need to be over 120cm

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(" You need to grow taller before you can ride. ")

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(" You need to grow taller before you can ride. ") Symbols we can use (Comparison Operators)

OPERATOR

MEANING

>

Greater than

<

Less than

>=

Greater than or equal to

<=

Less than or equal to

==

Equal to (both sides are the same)

!=

Not equal to

Exercise - Odds or Evens

# 🚨 Don't change the code below 👇
number = int(input("Which number do you want to check? "))
# 🚨 Don't change the code above 👆

#Write your code below this line 👇

if number % 2 == 0:
  print("This is an even number")
else:
  print("This is an odd number")
What can I say - same as mine - Woooo hooo :)

Nested if/else Statements

In the theme park ticket office scenario, we ALSO need to add in another condition, whereby if you are over 18 you pay $12 and if younger then you pay $7

In this case we use a nested if/else statement where we want MORE than 2 choices (as per the original if/else conditions) In a nested if/else statement, once the first condition has passed, we can check for another condition and then we can have another if/else statement

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 <= 18:
      print("Please pay $7")
    else:
      print("Please pay $12")

else:
    print(" You need to grow taller before you can ride. ")

We find out that the code we have written hasnt taken into consideration that the under 12's pay junior rates of $5 and above 12 to 18 pay the $7.

Where we AGAIN had 2 options ($7 or $12) we used the if/else option. Here we have 3 options (or more) we can use the if / elif / else where with the elif options we can use as many as we want!!

The flow chart now looks like this:-

Exercise - Body Mass Calculator - v2.0 Upgrade

My effort :)

# 🚨 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, 0)
bmi_1 = int(bmi)


if bmi <= 18.5:
  print(f"Your BMI is {bmi_1}, you are underweight.")
elif bmi > 18.5 and bmi <= 25:
  print(f"Your BMI is {bmi_1}, you have a normal weight.")
elif bmi > 25 and bmi <= 30:
  print(f"Your BMI is {bmi_1}, you are slightly overweight.")
elif bmi > 30 and bmi<= 35:
  print(f"Your BMI is {bmi_1}, you are obese")
else:
  print(f"Your BMI is {bmi_1} , you are clinically obese.")
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 have a normal weight.")
elif bmi < 30:
  print(f"Your BMI is {bmi}, you are slightly overweight.")
elif bmi < 35:
  print(f"Your BMI is {bmi}, you are obese")
else:
  print(f"Your BMI is {bmi}, you are clinically obese.")

Angela's method of rounding did not include how many digits to round off to and left the function(round) by itself. She also did not use "and" like I did in the elif statements. All she did was say it had to be less that 25, less than 30 etc. Cleaner than mine :)

Exercise 2: Leap Year

Step by Step :)

Working from "How to know if it's a leap year" We know the facts as:

  • STEP 1

    • The data HAS to be divisible by 4 to be in contention as a leap year

  • STEP 2

    • At the moment the statement is TRUE, the date can be divided by 4. We now have to create another "IF" statement and see if it CAN be divided by 100.

  • STEP 3

    • If we CAN divide the date by 100 AS WELL as dividing it by 400, then its a leap year

    • So we create ANOTHER "if" statement

Multiple "IF" Statements

With the if /elif /else statement on the left, only ONE of the conditions will be carried out, whilst on the right ALL conditions will be checked and if it so happens that all 3 conditions are TRUE, all 3 will be carried out

Back to the Ticket Office : )

Going back to the ticket office we want to ask the people if they would like a photo of their ride, and if agreeable, then the $3 would be added onto the cost of admission

  • Lets look at the flowchart as it was BEFORE:

  • Lets look at the flowchart as it was AFTER:

This additional feature is completely independent of their age or height, this asks if they want a photo, a "yes" or a "no". If you do we will add on $3 to the existing ticket price To do this we will ask multiple "IF" conditions and checks if the 1st condition is "true" then do "A" , it will then move onto the 2nd condition and do "B" a and so on

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 <= 18:
      print("Please pay $7")
    else:
      print("Please pay $12")

else:
    print(" You need to grow taller before you can ride. ")

So from the mind-map - how do we implement these extra cost for the photos?

Here is the original code with the new additions made

Exercise: Pizza

# 🚨 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
  #print("Small Pizzas are $15")
elif size == "M":
  bill += 20
  #print("Medium Pizzas are $20")
else:
  bill +=25
  #print("Large Pizzas are $25")

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}.")
# 🚨 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
 
elif size == "M":
   bill += 20
   
else:
   bill += 25
   
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}")

Logical Operators

We have done if statements, else statements, elif statements, multiple if statements as well as nested if statements. But we haven't be able to do thus far is to check for multiple conditions in the SAME LINE of code So how do we combine different conditions and say "Is the pizza large AND the user wants pepperoni AND extra cheese all in the same line of code? We use "Logical Operators" !! A and B C or D not E

AND:

When you combine 2 different conditions using an AND operator, they BOTH have to be TRUE for A and B for the entire line of code to be true. If ONE of them is FALSE, then the OVERALL thing evaluates to FALSE

OR:

When ONLY ONE of the conditions needs to be TRUE, then we use the OR operator If A OR B or if BOTH were TRUE - it would evaluate to TRUE If BOTH A and B are FALSE - will it evaluate to FALSE

NOT:

This operator basically REVERSES a condition. So, if a condition is FALSE, then it becomes TRUE, or of its TRUE, it becomes FALSE

Exercise - Rollercoaster + Logical Operators

Lets say that the theme park decided to give people between 45 and 55 free rides as they might be suffering from a mid-life crisis

How would we re-write our code that we have already:

Exercise: Love Calculator (Difficult)

Instructions

You are going to write a program that tests the compatibility between two people. We're going to use the super scientific method recommended by Buzz Feed.

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.

This video gives you more details on this:

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**."

THINGS TO KNOW BEFORE WE START

  • We need to use the "lower function" - this changes all letters to lower case

  • Use .lower() - For example:

    • s = "Kilometer" ----------- in comma because its STRING :) print(s.lower())

  • We need to use the "count function" - this counts how many times a character appears in a string

  • Use .count( ) - For example

    • sentence = 'Mary had a little lamb'

      sentence.count('a") 4

My Answer

# 🚨 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 👇
name = name1 + name2
#lcn = lower case name
lcn = name.lower()

t=lcn.count("t")
r=lcn.count("r")
u=lcn.count("u")
e=lcn.count("e")

true = t+r+u+e

l=lcn.count("l")
o=lcn.count("o")
v=lcn.count("v")
e=lcn.count("e")

love = l+o+v+e

score = int(str(true) + str(love))

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}.")
# 🚨 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 👇

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 >= 40) and (score <= 50):
  print(f"Your score is {score}, you are alright together.")
else:
  print(f"Your score is {score}.")

Really pleased I got there and very similar to Angela's solution which is a bonus :)

UPDATE: - Because I can :)

Day 3 Project - Treasure Hunt

- Cool art pictures you can have in your code. Dont forget that if you want to print a string across multiple lines use the 3 single quotes at the beginning and end print(' ' ' sjpjpjwpfjpwjepf etc ' ' ')

ASCII Art
Conditional Statement
Just a variation on the initial one above including free photos :)