How do you write an if statement in Python?

Whenever we think about control flow, perhaps the most well known statement type is the if statement. Why? We’ll see.

If you come from other languages, you may have used “else if” with the “if” statement. Right? 

However, python is an exception in this case.

Python uses “elif” in place of “else if”.

Usually, the if statement examines whether the condition is true or false.

When it is true, the if statement has a code block ready to execute.

If the condition comes out false, the if block does not execute that block of code. Instead it sends to the else block.

However, situations may arise, when we check the condition of several options.

As a result, there can be more elif parts.

Let’s see an example.

input = int(input("Please enter an integer: "))
#output:
Please enter an integer: 12

if input < 0:
   input = 0
   print('Negative changed to zero')
elif input == 0:
  print('Zero')
elif input == 1:
  print('Single')
else:
  print(input)

#output
12

In the above code we have asked for an input.

What kind of input?

An integer.

If the user types in a String or character instead of integer, what will happen?

It will give an error, because at the very beginning we have converted the String to integer.

We have seen before how we can parse integers in python.

However, the user can type in any integer, negative or positive.

In that case, we have several elif sequences.

In fact, in python, if and elif sequence is the substitute for the switch and case statements.

Why we need if and elif sequences?

In another code, we will find the answer to the above question.

A user may type in 0, or negative number. Right?

For example, if the user types in a negative number, we have a mechanism to convert that number to 0.

Let’s see such code, where the user gives a negative number as the input.

input = int(input("Please enter an integer: "))
# output
Please enter an integer: -45

if input < 0:
   input = 0
   print('Negative changed to zero')
elif input == 0:
  print('Zero')
elif input == 1:
  print('Single')
else:
  print(input)

# output:
Negative changed to zero

Now it makes sense. 

In the coming sections, we will discuss more on python control flow.

So stay tuned.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

Flutter, Dart and Algorithm

Twitter


Posted

in

,

by

Comments

One response to “How do you write an if statement in Python?”

  1. […] the previous section, we have discussed the if statement. In this section we will learn how to use a for loop in […]

Leave a Reply