Learn Python-100 Days Of Code with Khemlall DAY 3-Control flow, code blocks scope and logical Operator

Khemlall Mangal
13 min readOct 19, 2021

Today we will learn about conditional statement, if, else, elsif, logical operators, code block blocks, name spacing and whole lot more.

By the end of the day we will learn enough to build a game! Treasure island.

In our daily lives everything we encounter relies on us making decisions. If you are constructing a tub, you will have to take different scenarios into account. For example if you have a bath-tub, have you ever notice they have a overflow drain if the water level gets to a certain height? or have you ever been to a theme park that has height restriction where you have to be a certain height to get on a particular ride? So imagine you have to create a program that will need to see if you meet the eligibility before they can sell you the ticket.

Now lets represent this in PYTHON…Begin by forking the replit and lets begin.

All you have there is: welcome and asking the user to input their height in cm

print(“Welcome to the rollercoaster!”)
height = int(input(“What is your height in cm? “))

Now reference the flow chart above for the if else statement….

Now if you have experience with java or c@ programming, you will recognize that we have sytax like if(height !<120) do something else do something else… Well in Python you don’t then the parenthesis etc….you will do something like below where we don’t put a parenthesis and just put a colon to represent evaluating that block.

if height<120:

Lets stop and talk about Python Operator:

What is Python Comparison Operator?
A comparison operator in python, also called python relational operator, compares the values of two operands and returns True or False based on whether the condition is met.

We have six of these, including and limited to- less than, greater than, less than or equal to, greater than or equal to, equal to, and not equal to.

So, let’s begin with the Python Comparison operators.
Python Less Than (<) Operator

Python Greater Than (>) Operator

Let’s see the Greater than Python Comparison Operator

Now that we’ve seen which constructs we can apply these operators to, we will focus on the operators now on.

The greater than an operator, denoted by >, checks whether the left value is greater than the one on the right.

Less Than or Equal To (<=) Operator

We guess the next two operators won’t be much of a problem with you. We will quickly learn how to write less than or equal to in Python.

The less than or equal to operator, denoted by <=, returns True only if the value on the left is either less than or equal to that on the right of the operator.

>>> a=2

>>> a<=a*2

Equal To or Greater Than — Python (>=) Operator

Likewise, this operator returns True only if the value on the left is greater than or equal to that on the right.

>>> from math import pi

>>> 3.14>=pi

Python Not Equal Operator (!=) Operator

Finally, we’ll discuss the not equal to operator. Denoted by !=, this does the exact opposite of the equal to operator.

It returns True if the values on either side of the operator are unequal.

Python Equal To (==) Operator

The final two operators we’ll be looking at are equal to (==) and not equal to (!=).

The equal to operator returns True if the values on either side of the operator are equal.

Concluding for today, we learned six comparison operator in python.

These are- python less than, python greater than, Less Than or Equal To, Equal to or greater than, Python Equal To and Python Not Equal Operator.

Note: there is a difference between == and =. Equal (=) assign a value so a=10… so we are assigning a value to a..

if you want to check equivalency use == operator. Try this out in the replit.

Go to this following replit and lets do a code challenge today.

Figure out if a number is Odd or Even

Instructions

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

29.5 is not a whole number, it has decimal places. Therefore there is a remainder of 0.5, so the division is not clean.

The modulo is written as a percentage sign (%) in Python. It gives you the remainder after a division.

e.g.

6 ÷ 2 = 3 with no remainder.

6 % 2 = 0

5 ÷ 2 = 2 x 2 + 1, remainder is 1.

5 % 2 = 1

14 ÷ 4 = 3 x 4 + 2, remainder is 2.

14 % 4 = 2

Warning your output should match the Example Output format exactly, even the positions of the commas and full stops.

Example Input 1

43

Example Output 1

This is an odd number.

Example Input 2

94

Example Output 2

This is an even number.

e.g. When you hit run, this is what should happen:

https://cdn.fs.teachablecdn.com/bkF9TKJSTGksvxNzOtba

elif python

Alright let go on to nested if statement. From what we learned, let implement the follow flow chart below.

nest if else python

go to my replit here: https://replit.com/@KhemlallMangal/day-3-start-2#main.py

Now let do an upgrade of our BMI calculator project and add if else etc… apply what we learn!

BMI Calculator 2.0

Fork my replit and create your own and give this challenge a go. Good luck

https://replit.com/@KhemlallMangal/day-3-2-exercise-1#main.py

Instructions

Write a program that interprets the Body Mass Index (BMI) based on a user’s weight and height.

Now lets make this a little interesting. If you don’t know how much Kg you have but know your weigh in lbs, lets have ask the user if they know their weigh in Kg if not ask them how much lbs are they then convert it to kg. Ask them if they know they height in meter? if not convert and show them how much it is if the know in feet and inches.

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
  • Over 25 but below 30 they are slightly overweight
  • Over 30 but below 35 they are obese
  • Above 35 they are clinically obese.

https://cdn.fs.teachablecdn.com/qTOp8afxSkGfU5YGYf36

The BMI is calculated by dividing a person’s weight (in kg) by the square of their height (in m):

https://cdn.fs.teachablecdn.com/jKHjnLrNQjqzdz3MTMyv

Warning you should round the result to the nearest whole number. The interpretation message needs to include the words in bold from the interpretations above. e.g. underweight, normal weight, overweight, obese, clinically obese.

Example Input

weight = 85height = 1.75

Example Output

85 ÷ (1.75 x 1.75) = 27.755102040816325

Your BMI is 28, you are slightly overweight.

e.g. When you hit run, this is what should happen:

https://cdn.fs.teachablecdn.com/mGRynIETXuVqoDk8unci

The testing code will check for print output that is formatted like one of the lines below:

"Your BMI is 18, you are underweight.""Your BMI is 22, you have a normal weight.""Your BMI is 28, you are slightly overweight.""Your BMI is 33, you are obese.""Your BMI is 40, you are clinically obese."

Hint

  1. Try to use the exponent operator in your code.
  2. Remember to round your result to the nearest whole number.
  3. Make sure you include the words in bold from the interpretations.

Test Your Code

reference:
https://data-flair.training/blogs/python-comparison-operators/
Udemy Course:100 Days of Code — The Complete Python Pro Bootcamp for 2021

one solution:
https://replit.com/@KhemlallMangal/day-3-2-exercise-1#main.py

what’s your solution?

Leap Year

💪This is a Difficult Challenge 💪

Instructions

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:

https://www.youtube.com/watch?v=xX96xng7sAE

This is how you work out whether if a particular year is a leap year.

on every year that is evenly divisible by 4 **except** every year that is evenly divisible by 100 **unless** the year is also evenly divisible by 400

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)

Warning your output should match the Example Output format exactly, even the positions of the commas and full stops.

Example Input 1

2400

Example Output 1

Leap year.

Example Input 2

1989

Example Output 2

Not leap year.

e.g. When you hit run, this is what should happen:

https://cdn.fs.teachablecdn.com/AthNqKoSm6JD4sMom2X2

Hint

  1. Try to visualize the rules by creating a flow chart on www.draw.io
  2. If you really get stuck, you can see the flow chart I created:

Alright guys so we learn about % mod…. and i think we may need to use this …Now i have created this using a function and calling that function. Since you have not see function yet, we will do this the other way first.

# 🚨 Don't change the code below 👇year = int(input("Which year do you want to check? "))# 🚨 Don't change the code above 👆#Write your code below this line 👇#without function# is it clearly divisible by 4?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")

Let enhance this……but in future lesson we will use function to do this. but let me just give you another way of doing this…

# 🚨 Don't change the code below 👇year = int(input("Which year do you want to check? "))# 🚨 Don't change the code above 👆# Default function to implement conditions to check leap yeardef CheckLeap(Year):# Checking if the given year is leap yearif((Year % 400 == 0) or(Year % 100 != 0) and(Year % 4 == 0)):print(“leap Year”);# Else it is not a leap yearelse:print (“Not leap Year using function”)# Printing resultCheckLeap(year)

Alright, as we saw that we may need multiple If statement, not just if, elif or else, we may want to have multiple if statements to check if condition A and b and c matches then do xyz….

Now lets remember in previous lesson we build a roller-coaster ticket system. Let imagine that we want to add another question if the user want a the deluxe treat after the ride which include photo and a burger. If they do want to add that, then add 10.00 to their price if not then just skip straight to giving them their price for their ticket. Regardless of age.

see replit for implementation.

Let look at this code and the thing i want to to drive home is that indentation in python matters a whole lot when you write this code. Play around with code and ensure you understand what going on.

CODE CHALLENGE- BurgerOrder

Instructions

Congratulations, you’ve got a job at Python Burger. Your first job is to build an automatic Burger order program.

Based on a user’s order, work out their final bill.

Small Burger: $15Medium Burger: $20Large Burger: $25Pepperoni for Small Burger: +$2Pepperoni for Medium or Large Burger: +$3Extra cheese for any size Burger: + $1

Example Input

size = "L"add_pepperoni = "Y"extra_cheese = "N"

Example Output

Your final bill is: $28.

e.g. When you hit run, this is what should happen:

https://cdn.fs.teachablecdn.com/p1evEkwQxGNR4WlolIb4

Hint

  1. Think about what you’ve learnt about multiple if statements and see if you can reduce the number of lines of code while having the same functionality.

Test Your Code

Logical Operator

In Python, Logical operators are used on conditional statements (either True or False). n Python, Logical operators are used on conditional statements (either True or False). They perform Logical AND, Logical OR and Logical NOT operations.

https://www.geeksforgeeks.org/python-logical-operators-with-examples-improvement-needed/

Logical AND operator

Logical operator returns True if both the operands are True else it returns False.

Let try to incorporate this operator into existing code we wrote previously for rollercoaster rides. Say we want to add another check that if a person is between a certain age (mid-life crisis), they pay nothing.

elif age >= 45 and age <= 55:

print(“Everything is going to be ok. Have a free ride on us!”)

love calculator! fork this replit and lets start. https://replit.com/@KhemlallMangal/day-3-5-exercise-1#main.py

Love Calculator

💪 This is a Difficult Challenge 💪

Instructions

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

e.g.

name1 = "Angela Yu"

name2 = "Jack Bauer"

T occurs 0 times

R occurs 1 time

U occurs 2 times

E occurs 2 times

Total = 5

L occurs 1 time

O occurs 0 times

V occurs 0 times

E occurs 2 times

Total = 3

Love Score = 53

Print: “Your score is 53.”

Example Input 1

name1 = "Kanye West"name2 = "Kim Kardashian"

Example Output 1

Your score is 42, you are alright together.

Example Input 2

name1 = "Brad Pitt"name2 = "Jennifer Aniston"

Example Output 2

Your score is 73.

e.g. When you hit run, this is what should happen:

https://cdn.fs.teachablecdn.com/nfSILIPSNaIOwWhPR5vr

The testing code will check for print output that is formatted like one of the lines below:

"Your score is 47, you are alright together.""Your score is 125, you go together like coke and mentos.""Your score is 54."

Hint

  1. The lower() function changes all the letters in a string to lower case.

https://stackoverflow.com/questions/6797984/how-do-i-lowercase-a-string-in-python

  1. The count() function will give you the number of times a letter occurs in a string.

https://stackoverflow.com/questions/1155617/count-the-number-occurrences-of-a-character-in-a-string

Test Your Code

Before checking the solution, try copy-pasting your code into this repl:

Alright, here is my solution for what we have learned so far. We can definitely improve this as we learned about function etc but this how you solve this so far. :

# 🚨 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 👇combinedName = name1+name2lowercasestring = combinedName.lower()t= lowercasestring.count('t')r =lowercasestring.count('r')u= lowercasestring.count('u')e= lowercasestring.count('e')true = t+r+u+el=lowercasestring.count('l')o=lowercasestring.count('o')v=lowercasestring.count('v')e=lowercasestring.count('e')love = l+o+v+elove_score = str(true) + str(love)int_score = int(true) + int(love)print(love_score)if (int_score <10) or (int_score>90):print(f"Your score is {love_score}, you go together like coke and mentos")elif int_score<=40 and int_score<=50:print(f"Your score is {love_score}, you are alright together.")else:print(f"Your score is {love_score}.")

My replit:

Finally lets do our treasure island and create your own. Give it a try. You can get asci art and create your own! https://www.asciiart.eu/space/astronauts

Good luck!!!

--

--

Khemlall Mangal

I am a passionate coder, QA Engineer, and someone who enjoys the outdoors.