Just Python Part 5— Statements and Loops

Harman Bhatia
Feb 12 · 8 min read

I believe you are clear with Strings and Collections in Part 4 as they will act as a prerequisite for the statements and loops in which we will use strings, lists, dictionaries and sets. If not, Kindly go through the Strings and Collections.

Python Conditions and If statements

Python supports the usual logical conditions from mathematics:

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in “if statements” and loops. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times.

An “if statement” is written by using the if keyword.

a = 33
b = 200
if b > a:
print(“b is greater than a”)

Indentation

Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose.

a = 33
b = 200
if b > a:
print(“b is greater than a”) # This will give an error

Elif

The elif keyword is pythons way of saying “if the previous conditions were not true, then try this condition”.

a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

Else

The else keyword catches anything which isn’t caught by the preceding conditions.

a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
-----------------------------------------------------------------a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Short Hand If-else

If you have only one statement to execute, you can put it on the same line as the if statement.

if a > b: print("a is greater than b")  

If you have only one statement to execute, one for if, and one for else, you can put it all on the same line:

print("A") if a > b else print("B") 

You can also have multiple else statements on the same line:

print("A") if a > b else print("=") if a == b else print("B")  

Nested If

You can have if statements inside if statements, this is called nested if statements.

x = 90

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

And & OR Operators

The and keyword and or keyword are the logical operator, and are used to combine conditional statements:

a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
elif a > b or a > c:
print("At least one of the conditions is True")

The pass Statement

if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.

a = 33
b = 200

if b > a:
pass

Python For Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.

Syntax

for iterating_var in sequence:
statements(s)

Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)

The range() Function

To loop through a set of code a specified number of times, we can use the range() function,

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

for x in range(6):
print(x)

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

The break Statement

With the break statement we can stop the loop before it has looped through all the items. The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops.

If you are using nested loops, the break statement stops the execution of the innermost loop and start executing the next line of code after the block.

Syntax

The syntax for a break statement in Python is as follows −

break

Exit the loop when x is "banana":

fruits = [“apple”, “banana”, “cherry”]
for x in fruits:
print(x)
if x == “banana”:
break

The continue Statement

With the continue statement we can stop the current iteration of the loop, and continue with the nextThe continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.

The continue statement can be used in both while and for loops.

Syntax

continue

Flow Diagram

Example

Do not print banana:

fruits = [“apple”, “banana”, “cherry”]
for x in fruits:
if x == “banana”:
continue
print(x)

The pass Statement

for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error. The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example) −

Syntax

pass

Example

for x in [0, 1, 2]:
pass

Using else Statement with Loops

Python supports to have an else statement associated with a loop statement

  • If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list.
  • If the else statement is used with a while loop, the else statement is executed when the condition becomes false.
for x in range(6):
print(x)
else:
print("Finally finished!")
--------------------------------------------------------------------for num in range(10,20): #to iterate between 10 to 20
for i in range(2,num): #to iterate on the factors of number
if num%i == 0: #to determine the first factor
j=num/i #to calculate the second factor
print('%d equals %d * %d' % (num,i,j))
break #to move to the next number, the #first FOR
else: # else part of the loop
print(num, 'is a prime number')

When the above code is executed, it produces the following result −

10 equals 2 * 5
11 is a prime number
12 equals 2 * 6
13 is a prime number
14 equals 2 * 7
15 equals 3 * 5
16 equals 2 * 8
17 is a prime number
18 equals 2 * 9
19 is a prime number

The while Loop

With the while loop we can execute a set of statements as long as a condition is true.

Syntax

The syntax of a while loop in Python programming language is −

while expression:
statement(s)

Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately following the loop.

In Python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements.

Flow Diagram

Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Example

i = 1
while i < 6:
print(i)
i += 1

Note: remember to increment i, or else the loop will continue forever.

The else Statement

With the else statement we can run a block of code once when the condition no longer is true:

i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

The following example illustrates the combination of an else statement with a while statement that prints a number as long as it is less than 5, otherwise else statement gets executed.

count = 0
while count < 5:
print(count, " is less than 5")
count = count + 1
else:
print(count, " is not less than 5")

When the above code is executed, it produces the following result −

0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

Single Statement Suites

Similar to the if statement syntax, if your while clause consists only of a single statement, it may be placed on the same line as the while header.

Here is the syntax and example of a one-line while clause −

flag = 1
while (flag): print('Given flag is really true!')
print "Good bye!"

It is better not try above example because it goes into infinite loop and you need to press CTRL+C keys to exit.

This is all about Loops and Statements. If you have any doubt, please drop a comment or visit www.harmanbhatia.com.

Exceptional creative achievers apply a mentality of granularity instead of mindset of superficiality. So don’t just read this to complete the topic, practice too.

Next we will be going through Python Functions. Happy Python!

Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

Harman Bhatia

Written by

Entrepreneur | Business Enhancer | Developer

Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade