List Comprehension, Conditional, and Looping Statements (Quick Code-Python)

Shreedhar Vellayaraj
Geek Culture
Published in
10 min readSep 5, 2021
Credit: Unsplash

In this fourth chapter of the Quick Code-Python series, we are going to understand and implement various Conditional and looping statements available in python. Along with that, we’ll see how to use list comprehension to write your code efficiently.

Note: I’ve written the Quick Code-Python series in a linear fashion so that even a newbie can follow along the series to get a grasp of what python can actually do. For folks that are good with the fundamentals, you can follow along with the series to refresh your concepts or choose any of the chapters in the series that you want to know more about.

Comparison Operators

Before understanding the conditional and looping statements, let’s understand what comparison and logical operators are. A comparison operator can be defined as comparing two values. The output would either be True or False ( boolean).

The basic comparison operators are given below,

Credit: engineering big data
12 == 12
O/P: True
12 > 8
O/P: True
z = 5
x = 4
z == x
O/P: False
a = 'makeshift'
b = 'makeshift'
a == b
O/P: True
a = 'makeshift' #python is case-sensitive
b = 'Makeshift'
a == b
O/P: False
12 != 3
O/P: True

Logical Operators

Logical Operators are mostly used in conditional statements, which when true executes the statements or when it is false doesn’t execute them. The most important logical operator that we would use in python are Logical AND, Logical OR.

If you are familiar with logical gates, then the same principle applies here.

#AND operator
1 and 0 = 0
1 and 1 = 1
0 and 1 = 0
0 and 0 = 0
#OR operator
1 or 1 = 1
1 or 0 = 1
0 or 0 = 0
0 or 1 = 1

Note that in the above explanation you can replace 0 as False and 1 as True. Example, TRUE and FALSE = FALSE , TRUE OR FALSE = TRUE and so on.

Conditional Statements

Conditional statements are if, elif, and else statements that we use in python in order to use them as checks to see if the given condition is true or false.

if the condition is True then the code within the if condition will run and if it is False then it won’t run.

elif the condition given in the elif is True then the code within the elif will run and if it is False it won’t run.

else when no other condition is True then the code within the else statement will run.

if 3 == 4:
print('First statement is true')
elif 2 == 4:
print('Second statement is true')
else:
print('Last statement is true')
O/P:
Last statement is true

Code to block sam inside the college campus

name = input('Enter your name: ')if name == 'sam':
print('Sam You are Blocked here')
else:
print('Welcome!!')
O/P:
Enter your name: sam
Sam You are Blocked here

Sam may trick us by using his friend's name to enter the campus, let’s make sure that doesn’t happen

name = input('enter your name: ')if name == 'sam' or name == 'josh' or name == 'kate':
print('Access Denied')
else:
print('Access Granted')
O/P:
enter your name: josh
Access Denied

Code to return only elements from the dictionary that are greater than 25. Note that there are more efficient ways to do this, but for now let’s do this with if condition.

inp_dict = {'a': 23, 'b': 40, 'c': 34}
out_dict = []
if inp_dict['a'] >= 25:
out_dict.append(inp_dict['a'])
if inp_dict['b'] >= 25:
out_dict.append(inp_dict['b'])

if inp_dict['c'] >= 25:
out_dict.append(inp_dict['c'])
else:
print('No Elements Found!!')

out_dict
O/P:
[40, 34]

Code to check if a randomly generated number and the user inputted number are the same

import random
random_val = random.randint(1,50)
user = int(input('enter numbers 1 to 50: '))
if random_val == user:
print('You got it right !!')
print('random value is: ',random_val)
elif random_val > user:
print('Nope !! little higher')
print('random value is: ',random_val)
else:
print('Nope!! little lower')
print('random value is: ',random_val)
O/P:
enter numbers 1 to 50: 34
Nope!! little lower
random value is: 2

Code to indicate the number of digits in an integer

x = int(input('Enter a positive integer: '))if 0 <= x <= 9:
print("Number is single digit")
elif 10 <= x <= 99:
print("Number is double digit")
elif 100 <= x <= 999:
print("Number is 3 digits")
elif 1000 <= x <= 9999:
print("Number is 4 digits")
else:
print("Number is more than 4 digits")
O/P:
Enter a positive integer: 134
Number is 3 digits

Code to find if a number is even or odd

x = int(input("Enter an integer: "))if x % 2==0:
print('Number is Even')
else:
print('Number is odd')
O/P:
Enter an integer: 34
Number is Even

Append marks to a list from a dictionary only if they are greater than 75

marks_dict = {'math': 45, 'science': 89, 'physics': 90}
output_list = []
z = list(marks_dict.values())if z[0] >= 75:
output_list.append(z[0])
if z[1] >= 75:
output_list.append(z[1])
if z[2] >= 75:
output_list.append(z[2])

output_list
O/P:
[89, 90]

For Loop

Loops in python are used to check if a condition is true then they execute a chunk of code within the block continuously until the condition becomes false. The main looping statements in python are for, nested loops, while and other concepts such as list comprehension, range are also important to understand.

  • break() is used to exit a for loop or a while loop
  • continue() is used to skip the current block, and return to the For or while statement.
names = ['sam', 'kate','aj', 'moen','john']for i in names:
print(i)
O/P:
sam
kate
aj
moen
john

The i in the for loop is used to run through the loop and get the values for us from the list.

Using the break statement in the loop to break out of the loop

names = ['sam', 'kate','aj', 'moen','john']for i in names:
print(i)
if i == 'moen':
break
O/P:
sam
kate
aj
moen

Using the Continue statement in the loop to print the odd numbers in a list

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]for i in my_list:
if i%2 == 0:
continue
print(i)
O/P:
1
3
5
7
9

In the above code we are telling the for loop to check for even numbers and if it is true, then do nothing on the if condition and continue with the for loop. It would have been very difficult for us to do the same operation using only an if condition. We’ll have to write conditions for every element in a list and check if they are even or odd

credit meme overflow

Calculate the sum of the numbers in a list

num_list = [3,4,5,6,7,8]sum_num = 0for i in num_list:
sum_num = sum_num + i
print(sum_num)O/P:
33

Let’s give our student’s list an index using enumerate()

names = ['sam', 'kate','aj', 'moen','john']for i,name in enumerate(names):
print(i,name)
O/P:
0 sam
1 kate
2 aj
3 moen
4 john

List Comprehension

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or a looping statement. They can also be created based upon a condition set upon a particular list and put the results in a new list.

Let’s see two versions of code to square the elements in the list using the normal method and the other version using list comprehension.

Without using list comprehension

my_list = [1, 2, 3, 4]output_list = []for i in my_list:
output_list.append(i **2)
print(output_list)O/P:
[1, 4, 9, 16]

Using list comprehension

out_list = [i**2 for i in my_list]
out_list
O/P:
[1, 4, 9, 16]

Looks simple right !! I love list comprehensions because it allows me to not write more lines of code for simple list operations and calculations.

Credit: meme generator

Let’s take a look at another example, printing the square of even numbers from a given list

Without using list comprehension,

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]even_list = []for i in numbers:
if i % 2==0:
even_list.append(i**2)
print(even_list)
O/P:
[4, 16, 36, 64, 100]

Using list comprehension,

even_list = [i**2  for i in numbers if i %2 ==0  ]
even_list
O/P:
[4, 16, 36, 64, 100]

Nested Loops

Nested loops are simply a loop within a loop. We can use a nested loop when we want to loop within the primary for a loop. An example would be printing multiplication tables.

Printing the 4th and 5th multiplication table

for x in range(4,6):
for y in range(1,11):
print('{} * {} = {}'.format(x,y,x*y))
O/P:
4 * 1 = 4
4 * 2 = 8
4 * 3 = 12
4 * 4 = 16
4 * 5 = 20
4 * 6 = 24
4 * 7 = 28
4 * 8 = 32
4 * 9 = 36
4 * 10 = 40
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

Let’s go through the above code to understand what’s going on.

The first For loop x, loops through 4 and 5 (upper limit-1 when using the range function). When we are at 4( starting the loop) we enter into another loop y which loops through 1 to 10. Then we print the tables using the print function. After completing the 4th table, i.e printing from 1 to 10, we move back to the x loop, start with 5 and print the same way.

Range

We use the range function in a for loop, to specify the number that iterates during the execution of a loop.

Indexes in the range start with 0 and end with (n-1).

Example : range(0,11) means iterate through 0 to 10

for i in range(4, 10):
print(i)
O/P:
4
5
6
7
8
9

We can even use a step number in the range, to specify the increase or decrease in range while iterating the loop

for i in range(1, 10, 2):
print(i)
O/P:
1
3
5
7
9
for i in range(10, 0, -2):
print(i)
O/P:
10
8
6
4
2

While loop

A while loop can be used to execute a set of statements as long as a certain condition remains True. Remember to specify the condition in the end, else the program would run infinitely and you’ll have to interrupt and restart the kernel again. Trust me it’s happened to me multiple times, best to avoid that problem.

Credit: ah see it

Creating a simple while loop to print numbers

i = 0while i <=5:
print(i)
i = i +1
O/P:
0
1
2
3
4
5

We’ll see how to run a loop keeping it Trueduring inital stage, while specifying the condition in the end.

i = 3
while True:
print(i)
i = i +1
if i >=7:
break
O/P:
3
4
5
6

Keep in mind that inserting a colon after a conditional or looping statement is mandatory so that the IDE would automatically indent the next block of code.

Credit: Meme generator

Some Practical examples using the above concepts

Printing the numbers from an input string using list comprehension

statement = 'my name is shreedhar and I am 22 years old'
number = [i for i in statement if i.isdigit()]
print(number)
O/P:
['2', '2']

Printing every name in the list except ‘Kate’

names = ['sam', 'kate','aj', 'moen','john']i = 0
while i < len(names):
name = names[i]
i += 1

if name == 'kate':
continue

print(name)
O/P:
sam
aj
moen
john

Code to generate the following table

1 1 1
2 4 8
:
(upto)
:
10 100 100
for x in range(1, 11):
print('{} {} {}'.format(x, x*x, x*x*x))
O/P:
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000

Print the numbers between a given range that are only even

min = int(input('lower limit: '))
max = int(input('upper limit: '))
for i in range(min,max):
if i % 2 == 0:
print(i)
O/P:
lower limit: 12
upper limit: 34
12
14
16
18
20
22
24
26
28
30
32

Code to generate a password for a user using random letters, punctuations, numbers depending on the length that the user provides

import string
import random
password_char = string.ascii_letters + string.punctuation + string.digitslength = int(input('Enter the length of the password: '))
password = ""
for i in range(0, length):
password = password + random.choice(password_char)
print(password)O/P:
Enter the length of the password: 13
Oha/(CJU^Wxxx

Sorting the words in a sentence from the reply given by the user

sentence = input("How are you doing : ")words = sentence.split()
words.sort()
print("Here are the sorted words :")
for word in words:
print(word)
O/P:
How are you doing : I am doing very good
Here are the sorted words :
I
am
doing
good
very

Hope you’ve understood how to implement looping, conditional statements and using list comprehension to reduce the size of your code significantly.

Note: If you are reading the blog in a smartphone, the codes may not be very presentable to you. If you can’t understand the code properly, read the blog in a PC/MAC

Just reading the blog isn’t enough. Run the code by copy-pasting on an IDE. Change the variables for yourselves and see how the output changes. Finally, try to write your own code.

Check out the previous chapter of the Quick Code-Python series.

--

--