Day 3 — Loops and Conditional Statements in Python

Understanding loops and conditional statements in Python

Rishika Gupta
Python in Plain English

--

Day — 3: Loops and Conditional Statements in Python
Photo by Artturi Jalli on Unsplash

Hello readers!
In this article, we will be looking at conditional statements (if..else/ nested if…else/ if…elif…else) and loops (for/while) in Python. We can interpret these as decision-makers in programming languages. Like in real life, let us assume we decide to own a new mobile phone of 20k+ rupees, following which we complete the below tasks:

  • Take a backup of old phone data on a Laptop/PC
  • Review the specifications of phones available in the market according to our requirements
  • Visit offline/online stores and make a purchase

Basically here, once we decided to own a new mobile phone, we executed a specific set of tasks. Similar is the decision-making process of Python or any other programming language for that matter, wherein if the condition is satisfied (the decision is made/condition holds True), the block of code following the condition gets executed.

Before we go ahead, it is essential to about indentation (given the relevance to loops and conditional statements). In programming languages other than Python, the codes comprise curly brackets — {} to define the loop/condition body (or the block of code), whereas Python relies on indentation.

Conditional Statements in Python:

  • If-Else
    -
    The if signifies, that if the specified condition is true, the following block of statements will be executed, but not when the condition holds false, which is where the else comes into play.
    - The else is used when a block of code needs to be executed, only and only when the specified condition is false.
    - Note that all the lines of code after if and else will be executed by default. Once, either if or else block is executed, the compiler/interpreter exits from the if-else block and jumps to the immediate next line of code after the if-else block.
num = 35if num >= 10:
print('Number is greater than or equal to 10')
else:
print('Number is less than 1')
print('If-Else block completed')
  • If-Elif-Else Ladder (Chained If-Else)
    In this decision-making block, a user gets the opportunity to choose among several options. All the if-else blocks are executed from top to bottom. If any of the conditions controlling the code holds true, the associated lines/block is executed and the rest of the ladder(if/elif/else) blocks are skipped/bypassed. Also, when none of the conditions hold true, the ultimate else block gets executed.
num = 35if num < 0:
print('Number is negative')
elif num == 0:
print('Number is equal to 0')
elif num > 0 and num < 100:
print('Number is positive but less than 100')
else:
print('Number is positive and greater than 100')
print('If-Elif-Else Ladder block completed')
  • Nested If-Else
    Nested statements imply, one statement inside another. So, nested if-else simply means, if-else inside another if-else block. This can be interpreted as, for instance, when the main condition: a whole number (as in this case — the number is positive or equal to zero) is split into two cases, a number strictly greater than 0 and a number equal to 0, and corresponding lines of codes need to be executed for each underlying conditions.
num = 45if num >= 0:
if num > 0:
print('Number is positive')
else:
print('Number is equal to 0')
else:
print('Number is negative 0')
print('Nested If-Else block completed')
  • Shorthand If
    This comes to use when only a single if only a single statement/line of code needs to be executed and without an else block. The single statement inside if-body can be written after indentation, or in the line as that of if.
num = 45# Method-1:
if num > 0:
print('Number is positive')
print('Shorthand If block completed')
# Method-2:
if num > 0: print('Number is positive')
  • Shorthand If-Else
    This is an extension of “Shorthand If”, wherein we can write single lines of code in both if and else blocks.
num = 45print('No is +ve or 0') if num >= 0 else print('No is negative')
print('Shorthand If-Else block completed')

Loops in Python:

  • For Loop
    - For loops are used to iterate over a sequence, say — a list, a tuple, an array, a dictionary, or a range (Don’t worry in case you don’t know these sequences, we will cover them in further articles). If you know C/any other programming languages, you might be familiar with for loop, wherein we need to set the indexing/iterating variable beforehand. But, it is not the case in Python.
    - Furthermore, the for loop kind of works as an iterating method. Note that, in all the cases, the for states to execute the following lines of code, once for each item in the sequence of a list, a tuple, etc.
    - The range essentially returns a sequence of numbers, (by default starting from 0 and incrementing by 1 and ending at the specified number(exclusive)) that can be used to loop a block of code a specified number of times.
# Print numbers from 1 to 100for i in range(101):
print(i)
print('For Loop completed')

- Guess what, even strings are iterable objects. How? They contain a sequence of characters.

str = 'fruits'for character in str:
print(character)

- Along with the loops in Python, you may come across the keyword break, which is used to terminate the loop before it has looped through all the items. In this case, we are iterating over a shape sequence and we want to terminate our execution once we stumble upon an item that has the shape of a circle.

shapes = ['square','circle','rectangle']for shape in shapes:
print(shape)
if shape == 'circle':
break

- Similar to the break, there is continue, wherein we can stop the current iteration of the loop, and begin with the next one. In this case, we are iterating over a shape sequence and we would like to skip our execution codes when we come across a square.

shapes = ['square','circle','rectangle']for shape in shapes:
print(shape)
if shape == 'square':
continue

- Note that loops cannot be empty in Python. There needs to be at least a single line of code inside it. Say for some reason, you have no content (or don’t want to execute/do anything) for a particular instance, you can put the pass to avoid facing any errors in the code. This simply lets the compiler know that we need to move to the next block of code (the for loop holds null and void).

for i in range(10):
pass #Do nothing#
  • While Loop
    This loop can be executed as long as the condition holds true. Note that, unlike in for loop, while loop requires the iterating variables to be set/assigned beforehand.
# Print numbers from 1 to 100
i = 1
while i < 101:
print(i)
i = i + 1
print('While completed')

Congrats readers for stepping a little further in Python Programming.

Thanks for reading! Do subscribe and share with everyone in your community and don’t forget to like and comment. Follow my Medium Page Rishika Gupta. You can find the entire Python programming Series or Python List of my articles in my stories. Please find the links below.

Rishika's List of Python Programming

10 stories

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Join our community Discord.

--

--

Erasmus Mundus Master Student. Senior Developer. Computer Engineer. | Writing: Python, Programming & Bioinformatics | Let’s connect via LinkedIn — rishika_g