# Day 3: Control Flow and Operators

## Control Flow with if/else and Conditional Operators

![Conditional Statement](/files/-MM22c50fGlHW-hcJSvk)

**`if condition:`**\
&#x20;   **`do this`**\
**`else:`**\
&#x20;   **`do that`**\
\
**`water-level = 50`**\
**`if water_level > 80:`**\
&#x20;   **`print("Drain Water")`**\
**`else:`**\
&#x20;   **`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

![](/files/-MM25gGlRwAoZIk3X5rH)

```
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:`**\
&#x20;   **`print("You can ride the rollercoaster!")`**\
**`else:`**\
&#x20;   **`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

![](/files/-MM2Ck40suh8Tg0Txj0A)

![](/files/-MM2CtxXarbfQ3ns0lzX)

{% tabs %}
{% tab title="My Code" %}

```
# 🚨 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")

```

{% endtab %}

{% tab title="Angela's Code" %}

```
What can I say - same as mine - Woooo hooo :)
```

{% endtab %}
{% endtabs %}

### 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<br>

![](/files/-MM2G5rkaa1SuC5qRj4X)

![](/files/-MM2GF9FcSegWib9fYbN)

![](/files/-MM2lhkXYnL3kpHOv9E-)

{% tabs %}
{% tab title="Nested if/else - Height and Age Options" %}

```
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. ")

```

{% endtab %}
{% endtabs %}

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. <br>

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:-**

![](/files/-MM2o3oZQb-xpfTJ6WNt)

![](/files/-MM2qWnigynd6JbibLsm)

#### **Exercise - Body Mass Calculator - v2.0 Upgrade**

![](/files/-MM2r_il1PAwo2XwyynD)

![](/files/-MM6jnf-Fj1EMrmVgVFe)

![](/files/-MM6jssMSHA8YW-vVMaI)

My effort :)

![](/files/-MM6mwXY6YSFBiyvfYR3)

{% tabs %}
{% tab title="My Answer" %}

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

{% endtab %}

{% tab title="Angela's Answer" %}

```
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.")
```

{% endtab %}
{% endtabs %}

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

![](/files/-MM7yp3WIEx3BgpgX7qv)

![](/files/-MM7yXekymV5bXlpjgYr)

![](/files/-MM7yzGgglSQC-UTk79q)

#### 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

![](/files/-MM80830iudNZyMcadKC)

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

![](/files/-MM86YGP5XsaXwLjyRq6)

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

![](/files/-MM88S4jllZSSMkjfKZV)

### Multiple "IF" Statements

![](/files/-MM8AWhoYCdr6kRFoL0-)

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**:

![](/files/-MM8C2oao_OQSuM8XyBi)

* Lets look at the flowchart as it was **AFTER**:

![](/files/-MM8CaSXrd7TBCjr86YD)

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

{% tabs %}
{% tab title="Nested if/else - Height and Age Options" %}

```
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. ")

```

{% endtab %}
{% endtabs %}

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

![](/files/-MMAjsmLC-_p1hQjsUxk)

Here is the original code with the new additions made

![](/files/-MMAtMID1koLKJET704G)

![](/files/-MMBG2u3h5zUyXr7S9qQ)

#### Exercise: Pizza

![](/files/-MMBl_srMAGYlk9tyn1P)

![](/files/-MMBlil3SxyvYaNmX2Jr)

![](/files/-MNV2FbXtXXUNJGDIIvp)

{% tabs %}
{% tab title="My Answer" %}

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

```

{% endtab %}

{% tab title="Angela's Answer" %}

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

{% endtab %}
{% endtabs %}

### 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:**&#x20;

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

![](/files/-MMCmGd7zjt9uOYp-Z44)

### 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**

![](/files/-MMCoPyd2WDbwdDSlbAk)

**NOT:**

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

![](/files/-MMCpzlBeaJh70V6J3Gt)

### 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

![](/files/-MMCrnqC3se5ytN7_yry)

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

![](/files/-MMDKQEQlno-uTyvTK8r)

![Just a variation on the initial one above including free photos :)](/files/-M_7iCbpaRaQLe5S3UFe)

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

![](/files/-MMFGT_d4S0Ym9nvXT69)

![](/files/-MMFHDgX3Ldo4r90z4ZZ)

![](/files/-MMFMdm_DLXcpSQRdddg)

### 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())`**

![](/files/-MMFJVAm04wQLDFT4ABU)

* 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`**

![](/files/-MMFM1pkBbigO0TaUjk2)

![](/files/-MMFMNkSr_2dJCRxzVq-)

#### My Answer

![](/files/-MMG4r1dCN_ShtazXMrq)

{% tabs %}
{% tab title="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}.")
```

{% endtab %}

{% tab title="Angela's 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 👇

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}.")
```

{% endtab %}
{% endtabs %}

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

UPDATE: - Because I can :)

![](/files/-M_83k6LNCVBveziMpy6)

## Day 3 Project - Treasure Hunt

[ASCII Art](https://ascii.co.uk/art) - 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 ' ' ')`**

![](/files/-MMGKKTHdje6u4wJCxvj)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://python.microcisco.com/python-bootcamp/100-days/day-3.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
