Python 3 – Conditional Statements and Logical operators

BMI Calculator, Leap Year finder, and Largest Number Finder in Python

Introduction

In the previous lessons, we talk about Mathematical signs, operations, and string manipulation. I hope you understand everything about our lessons.
From this lesson, we will learn all about conditional statements such as if, if-else, else-if, and logical operators. End of this lesson we are going to make Simple Coin fliping game. So lets move to the lesson.

Conditional Statements in Python

In python has a flow to execute the coding that we write. You can see in our previous programs, the code execute from top to bottom. We can control this flow using control statements. let’s look at the below flow chart.

image 2021 01 11 011238
Python Flow

This is a simple program to tell users to can they drink or not?. Here when running the program, the flow will be high. And ask the user to enter the age. After the user enters the age, the flow comes to comparison. Here there are two branches. So the program will go only one flow at a time. So if age greater than or equal to 21 is true, the flow will go left side and the result will be Show “You may drink”, else age is smaller than 21, the flow will go right side and the result will be shown “You can’t drink”.

This the way we can control the flow of python using conditional statements. It totally depends on the conditional statement. It should do either the first path or the second path. It can’t do both paths. If we write this flow in python language, it should use the keyword “if”, and have to write the condition and must place the colon. and below write the code to execute that if the condition is true. What should we do if the condition is false?. To do this, another keyword used “else” which is used if the condition was false. So let’s write in python code for the above flow chart.

age = int(input("Enter Your Age."))

if age >= 21:
  print("You May Drink.")
else :
  print("You Can't Drink.")

Output :

Enter Your Age. 20
You Can't Drink.

How this output has come?

  1. The input statement ask “Enter Your Age.”, then we gave 20.
  2. So age is equal to 20.
  3. The flow came to if statement and check the condition. 20 is not greater than or equal to 21.
  4. So condition was false.and flow went to else statement.
  5. Else statement print the message. “You Can’t Drink.”

First of all, you have noticed the spacing and indentation in python. You have to avoid to write the above print function in the same vertical line. If we write without spacing, the “IndentationError: expected an indented block” will appear in the result. Make sure that everything is clean and clear from indentation level errors.

You have noticed that comparision symbol. such as greater than or equal. these type of symbols called comparision element. You can use below chat instead of above sign,

OperatorName
>=Greater Than or Equal To
<=Less Than or Equal To
>Greater Than
<Less Than
==Equal
!=Not Equal

Don’t Confuse on equal sign. You may look in our previous program, we use only one equal sign, but here using two equal sign. The question may raise, What are the differents between two equal sign and one equal sign? there is adifferent. One equal signs means we assigning some value to variables. for example, age = 20. Two equal signs means, we are checking if the left value is equal to right value.

Now we look at another program see what we learned. The program is used to find the Odd or Even value of numbers. How we can find the odd or even value in real life?. If a number divisible by two without remainder, that is an even value. And if the number divisible by two and if we got remainder, that is an odd value number.

How can we find the odd, even value in programming? First of all, there is a sign called “modulo”. Simply we can use by percentage symbol ( % ) to find the Odd, even value. For Example 5 % 2 means 2 + 2 + 1. Here five divided by 2 times two and remainder of one. This the way that we have to use it. Before going to start, the digit should be in integer data type. So let’s do it now in python.

digit = int(input("Enter the Number "))

if digit % 2 == 0 :
  print("It is Even Number")
else:
  print("It is odd Number")

Nested If in Python

In the above lesson, we learned the “if/else” condition with a single conditional statement. Here we are going to use two or more conditional statements. That’s pretty simple. Let’s have a look at this example.

image 2021 01 11 152032
Flowchart

Let’s convert it into python.

height = int(input("Enter Your Height in cm : "))

if height >= 120:
  age = int(input("Enter Your Age : "))
  if age >= 18:
    print("You can go for rollar Coaster.")
  else:
    print("You can't allow. Your are under 18 years.")
else:
  print("You can't allow. Your are under 120cm height.")

Output

Enter Your Height in cm : 130
Enter Your Age : 20
You can go for rollar Coaster.

There is another method “elif” in python. Through this keyword, we can add another condition in addition to “if” and “else”. Let’s modify the above example.

image 2021 01 11 154250
height = int(input("Enter Your Height in cm : "))

if height >= 120:
  age = int(input("Enter Your Age : "))
  if age <= 12:
    print("You cann't allow. You under 12 years.")
  elif 12 < age < 18:
    print("You can go for rollarcoaster with your parent.")
else:
  print("You can't allow. You under 120 cm height.")

What’s happening in the above flow chart? Computer asks for height. and check if the height is greater than or equal to 120. if not system print “You can’t allow. You under 120 cm height.”. But if it is true, the system asks to enter your age. whenever enter your age check the condition. if age is smaller than or equal to 12 then the system print “You can’t allow. You under 12 years.” But if the condition is false, again check another condition. here we used two conditional signs. So condition should check those two conditions. if one of these conditions passed and another fails, the total condition will fail. if age greater than 12 and less than 18, the system print “You can go for rollarcoaster with your parent.”. if one condition fails, the system prints “You can’t allow. You under 120 cm height.”.

BMI Calculator 2.0 in python

here we can add more “elif” keywords to check more conditional statements. Now it is our turn to upgrade our previous programs.Lets change our BMI Calculator program according to this table.

Under Weight<= 18.4
Normal18.5 – 24.9
Over Weight25.0 – 29.9
Obese30.0 – 34.9
Severely Obese35.0 – 39.9
Morbid Obese<=40.0
BMI Table

Let’s start to coding.

# Getting user input
Height = input("What is Your Height in M? ")
Weight = input("What is Your Weight in kg? ")

# Converting into float
Height_as_float = float(Height)
Weight_as_float = float(Weight)

# Calculation part
BMI = Weight_as_float / Height_as_float ** 2

# Round the float into 1 decimal
BMI_Round = round(BMI,1)

# Print the result
 using if else and elif
if BMI_Round <= 18.4:
  print(f"You are Under Weight. Your BMI is : {BMI_Round}")
elif 18.5 <= BMI_Round <= 24.9:
  print(f"You are Normal Weight. Your BMI is : {BMI_Round}")
elif 25.0 <= BMI_Round <= 29.9:
  print(f"You are Over Weight. Your BMI is : {BMI_Round}")
elif 30.0 <= BMI_Round <= 34.9:
  print(f"You are obese Weight. Your BMI is : {BMI_Round}")
elif 35.0 <= BMI_Round <= 39.9:
  print(f"You are Severly Obese Weight. Your BMI is : {BMI_Round}")
else:
  print(f"You are Morbid Weight. Your BMI is : {BMI_Round}")

Output :

What is Your Height in M? 1.8
What is Your Weight in kg? 65
You are Normal Weight. Your BMI is : 20.1

We have changed to one decimal value. So it will easy to understand. The system asks the user to enter the Height and weight. So we gave 1.8 for height and 65 for weight. The String value converted to a float value and it saved into a new variable. Next weight divided by height to the power of two. so the answer was 20.06172839506173. and using the round function is converted to one decimal place as 20.1. Now, let’s check the condition which was the true condition for our input. First statement true for less than or equal 18.5. So the first condition was false. If check the second “elif” condition, if it is in the range of 18.6 to 24.9. So our input in this range. So Our input is true, and print the message”You are Normal Weight. Your BMI is : 20.1″. Hereafter the flow will end and the program will exit. Once your condition matched with the statement, the Below statements never check if it will true or not. This is the way if/else and elif worked. Still, it didn’t understand use thonny Python IDE for step by step.

Leap Year Finder in Python

Let’s take one another challengeto find the leap year. Look below picutre get understand the concept from microsoft.

image 2021 01 11 201858
Credit : Microsoft.com

If you so confused let’s take a look on flow chart.

image 2021 01 11 204000
Flow Chart for Leap Year

I think you got a idea. So Let’s begin the Code in Python.

first of all ask the user to enter the year which they want to check the year. And save it to the integer variable by string to int type converson.

year = int(input("Enter the Year ex:YYYY : ")

After got the input, let’s check if it divisible by 4 without remainder value. if it is true, do this and if not print “It is not leap Year.”

if(year % 4 == 0):
  #do this
else:
  print("It is not a Leap Year.")

If the year divisible by 4 without remainder, again check that if the year divisible by 100 without remainder. if it is false print”It is a Leap Year.” otherwise, check if the year divisible by 400 without remainder. if that true print “It is a Leap Year.”. Otherwise, print “It is not a Leap Year.”.

if(year % 4 == 0):
  if(year % 100 == 0):
    if(year % 400 == 0)
      print("It is a Leap Year.")
    else:
      print("It is not a Leap Year.")
  else:
    print("It is a Leap Year.")
else:
  print("It is not a Leap Year.")

Thats all we have done.

year = int(input("Enter the Year ex:YYYY : ")

if(year % 4 == 0):
  if(year % 100 == 0):
    if(year % 400 == 0)
      print(f"{year} is a Leap Year.")
    else:
      print(f"{year} is not a Leap Year.")
  else:
    print(f"{year} is a Leap Year.")
else:
  print(f"{year} is not a Leap Year.")

Output :

Enter the Year ex:YYYY : 2021
2021 is not a Leap Year.

Logical Operator in Python

We learned everything about conditional Statements. But there is one thing remaining. That is Logical Operators. There are three types of logical operators available in python.

  1. and – The entire statement is true if all statements are true. for example. if (age < 24 and height > 130 ).
  2. or – If any statement was true, the whole statement is true. for example. if( score == 95 or score == 35).
  3. not – if a single or multiple conditions is ture,the statement is false. for example. if(not(go == true)).

Largest Number Finder in Python

We can understand the this through this program. That is used to find the largest number among three numbers. First we get the input from user.

no_one = int(input("Enter the first number: "))
no_two = int(input("Enter the second number: "))
no_three = int(input("Enter the third number: "))

Here is the our main check point. if the number one is greater than number two and number three, number one is largest number.

if(no_one > no_two and no_one > no_three):
  largest_no = no_one

If the number two is greater than number one and number three, number two is largest number.

elif(no_two > no_one and no_two > no_three):
    largest_no = no_two

if the number three is greater than number one and number two, number three is largest number.

else:
   largest_no = no_three

Finally print out the largest Number.

print(f"The Largest Number is : {largest_no}.")

So make it every thimg in one program.

# Getting the three numbers from user
no_one = int(input("Enter the first number: "))
no_two = int(input("Enter the second number: "))
no_three = int(input("Enter the third number: "))

# Checking Point
if(no_one > no_two and no_one > no_three):
  largest_no = no_one
elif(no_two > no_one and no_two > no_three):
    largest_no = no_two
else:
   largest_no = no_three

# Print out the Largest Number
print(f"\nThe Largest Number is : {largest_no}.")

Output :

Enter the first number: 10
Enter the second number: 20
Enter the third number: 30

The Largest Number is : 30.

From our today lesson we learned conditional statements and Logical operators. And used in many ways. If some question found please comment below.

Leave a Comment