DEV Community

Cover image for Python Basics 5: Conditionals
Irfan Faisal
Irfan Faisal

Posted on • Updated on

Python Basics 5: Conditionals

Hey guys! Welcome again! Today we're gonna learn about conditionals. Python conditional is one of the core topics in learning python as a beginner and it is also really important for further topics. So understanding conditional is your top priority. With any further ado, let's get started.

What is conditional

First, let's imagine a real-world scenario. We all in our lives face any situation where we need to make a decision based on a condition. Like it's really common to say,
"If it rains, we won't play".
So you can see that here's the possibility of playing depending on if it rains or not. Here we're making a decision based on a condition.

Similarly, in programming, sometimes we also need to execute a block of code based on a decision or a program will run if it satisfies a condition. Basically this concept is known as 'Conditionals'. Now let's dive into it!

For conditionals, in python program, there are if, elif and else statements to perform this decision-making programs. We'll learn all of these one by one.

We'll try to understand conditional through a simple project:

Let's try to make a ticket system for a rollercoaster ride.

We have the following conditions:

  • If your height is over 120cm, you ride the rollercoaster.
  • If your height is less than 120cm, you can't ride the rollercoaster.
  • Your height is over 120cm but you're less than 12 years old, pay 4$
  • Your height is over 120cm but you're less than 18 years old, pay 6$
  • Your height is over 120cm but you're over 18 years old, pay 8$

To implement this real-life scenario into code, we need decision-making features. For that we're going to use conditionals.

Conditionals have if-else, if-elif-else statements. First, let's go over with the basic syntax of if-else.

If-else statement:

if (condition):
    Block of codes
else:
    Block of codes
Enter fullscreen mode Exit fullscreen mode

In 'if' statement it contains a condition and a block of codes.
If the condition is true then our program will enter the body of 'if' statement and execute it. Otherwise if it is false, then it will go to the else statement and execute it.

Here points to be noted, the colon after the condition is mendatory and the body of if statement had to follow indentation.
Now we'll look at what indentation is.

What is indentation?

In many cases, there are multiple lines of code under one condition. The usual approach is to define a group of multiple statements into one compound statement or block.A block is regarded syntactically as a single entity. So whenever a condition is true this block will be executed otherwise not.

To define a block there is a convention in python which is known as indentation. So basically indentation is the leading whitespace before a statement in python. Traditionally the amount of whitespace is four(you also can use tab button in the keybaord). The statements that have the same indentation level(same amount of whitespaces before them) are considered as a block of code in python.
Whenever a statement breaks this indentation the block ends there.

Let's implement if-else for our problem

if height>=120:
    print("You can ride the rollercoaster")
else:
    print("you can't ride the rollercoaster")
Enter fullscreen mode Exit fullscreen mode

if-elif-else:

We have three more conditions to fulfill, right? We're going to use elif(else-if) statement to exmecute them.

When your if condition is false and you want to add another condition, you can use elif statement.

if (condition 1):
    Block of codes
elif (condition 2):
    Block of codes
else:
    Block of codes
Enter fullscreen mode Exit fullscreen mode

if condition 1 is true, it's going to execute the first block of codes. If it's false, then it will go to condition 2 of elif statement. If it's true then it will execute the second block of codes, otherwise it will go to else if it's false.

Point to be noted: the rest of the three conditions are dependent on whether the first condition is executed or not. That's why we're also going to use nested if statements. Nested means having other if statements under one if statement.

if (condition 1):
    Block of codes
    if condition:
        Block of codes
    else:
        Block of codes
else:
    Block of codes
Enter fullscreen mode Exit fullscreen mode

Let's implement all of these for our problem

if height>=120:
    print("You can ride the rollercoaster")
    age=int(input("Enter your age:"))
    if age <= 12:
        print("Ticket price:4$")
    elif age <= 18:
        print("Ticket price:6$")
    else:
        print("Ticket price:$8")
else:
    print("you can't ride the rollercoaster")
Enter fullscreen mode Exit fullscreen mode

There you go! I hope this blog helps you to understand conditionals. Now I have a problem for you to solve.

Practice problem

Write a program that interprets the Body Mass Index (BMI) based on a user's weight and height.
BMI=weight(kg)/height**2(m)

It should tell them the interpretation of their BMI based on the BMI value.

Under 18.5 they are underweight
Equal to or over 18.5 but below 25 they have a normal weight
Equal to or over 25 but below 30 they are slightly overweight
Equal to or over 30 but below 35 they are obese
Equal to or over 35 they are clinically obese.

Use input functions to take weight and height input from the user.
Important: you do not need to round the result to the nearest whole number. It's fine to print out a floating point number for this exercise.

Solve this problem and share your code in the comments.
Happy coding!

Top comments (4)

Collapse
 
thaisavieira profile image
Thaísa Vieira

This is my solution to the suggested problem:

print('Welcome to Body Mass Index (BMI) calculator')
weight = float(input('Insert the weight in kg: '))
height = float(input('Insert height in m: '))
BMI = weight/(height**2)
result=(("{:.2f}".format(BMI)))

if BMI<18.5:
    print('Your BMI is',result,'and you are classified as underweight')
elif BMI>18.5 and BMI<25:
   print('Your BMI is',result,'and you are classified as normal weight')
elif BMI>25 and BMI<30:
    print('Your BMI is',result,'and you are classified as slightly overweight')
elif BMI>30 and BMI<35:
    print('Your BMI is',result,'and you are classified as obese')
else:
  print('Your BMI is',result,'and you are classified as clinically obese')
Enter fullscreen mode Exit fullscreen mode
Collapse
 
coderanger08 profile image
Irfan Faisal

Share your solution to the practice problem here in the comments!!

Collapse
 
thaisavieira profile image
Thaísa Vieira

Great article, Irfan! Also, finishing it with a problem for the readers is a great strategy.

Collapse
 
coderanger08 profile image
Irfan Faisal

Thanks so much for your comment! Much appreciated