2 Python Control Structures
2 Python Control Structures
SoloLearn 2
Booleans
Another type in Python is the Boolean type. There are two Boolean values:
True and False. They can be created by comparing values, for instance by
using the equal operator ==.
my_boolean = True
print(my_boolean) # prints True
print(2 == 3) # prints False
print("hello" == "hello") # prints True
Be careful not to confuse assignment (one equals sign) with comparison
(two equals signs).
Comparison
Another comparison operator, the not equal operator (!=), evaluates to True
if the items being compared aren't equal, and False if they are.
print( 1 != 1 ) # prints False
print("eleven" != "seven") # prints True
print(2 != 10) # prints True
Different numeric types can also be compared, for example, integer and float.
Comparison
The greater than or equal to, and smaller than or equal to operators are >= and <=.
They are the same as the strict greater than and smaller than operators, except that they return
True when comparing equal numbers.
print(7 <= 8) #prints True
print(9 >= 9.0) #prints True
Greater than and smaller than operators can also be used to compare strings lexicographically
(the alphabetical order of words is based on the alphabetical order of their component letters).
For example:
print("Annie" > "Andy") # prints True
The first two characters from "Annie" and "Andy" (A and A) are compared. As they are equal, the
second two characters are compared. Because they are also equal, the third two characters (n
and d) are compared. And because n has greater alphabetical order value than d, "Annie" is
greater than "Andy".
What is the output
1. print(7 != 8)
• False
True
2. print( 7 > 7.0 )
• True
False
3. print( 8.7 <= 8.70 )
• False
True
• An error occurs
if Statements
You can use if statements to run code if a certain condition holds.
If an expression evaluates to True, some statements are carried out.
Otherwise, they aren't carried out.
An if statement looks like this:
if expression:
statements
Python uses indentation (white space at the beginning of a line) to delimit
blocks of code. Depending on program's logic, indentation can be
mandatory. As you can see, the statements in the if should be indented.
Here is an example if statement:
if 10 > 5:
print("10 greater than 5")
print("Program ended")
As you can see in the example above, a series of if elif statements can have a final else block, which is called if none of the
if or elif expressions is True.
The elif statement is equivalent to an else/if statement. It is used to make the code shorter, more readable, and avoid
indentation increase.
Nested Ifs
To perform more complex checks, if statements can be nested, one inside the
other. This means that the inner if statement is the statement part of the
outer one. This is one way to see whether multiple conditions are satisfied.
For example:
num = 12
if num > 5:
print("Bigger than 5")
if num <=47:
print("Between 5 and 47")
The and operator takes two arguments, and evaluates as True if, and only if, both of its arguments are True. Otherwise,
it evaluates to False.
print( 1 == 1 and 2 == 2 ) # prints True
print( 1 == 1 and 2 == 3 ) # prints False
print( 1 != 1 and 2 == 2 ) # prints False
print( 2 < 1 and 3 > 6 ) # prints False
Boolean Or
The or operator also takes two arguments. It evaluates to True if either (or both) of its arguments are True, and False if
both arguments are False.
print( 1 == 1 or 2 == 2 ) # prints True
print( 1 == 1 or 2 == 3 ) # Prints True
print( 1 != 1 or 2 == 2 ) # prints True
print( 2 < 1 or 3 > 6 ) # printsFalse
Besides values, you can also compare variables. Boolean operators can be used in expression as many times as needed.
Boolean Not
Unlike other operators we've seen so far, not only takes one argument,
and inverts it. The result of not True is False, and not False goes to
True.
print(not 1 == 1) # prints False
print(not 1 > 7) # prints True
The below code shows that == has a higher precedence than or:
print( False == False or True ) # prints True
print( False == (False or True) ) # prints False
print( (False == False) or True ) #prints True
In the example above the words list contains three string items.
A certain item in the list can be accessed by using its index in square brackets.
For example:
words = ["Hello", "world", "!"]
print(words[0]) # prints first element at index 0 : Hello
print(words[1])
print(words[2])
In some code samples you might see a comma after the last item in the list. It's not mandatory, but perfectly valid.
How many items are in this list?
[2,]
• 2
1
• 3
Some types, such as strings, can be indexed like lists. Indexing strings behaves as though you are indexing a list
containing each character in the string. Space (" ") is also a symbol and has an index.For example:
str = "Hello world!"
print(str[6])
num = [5, 4, 3, [2], 1]
print(num[0])
print(num[3][0])
print(num[5]) #error
Lists and strings are similar in many ways - strings can be thought of as lists of characters that
can't be changed.
create a list, reassign its 2nd element and print the whole list.
nums = [33, 42, 56]
nums[1] = 22
print(nums)
For example, the string "Hello" can be thought of as a list, where each character is an item in
the list. The first item is "H", the second item is "e", and so on.
To check if an item is in a list, the in operator can be used.
It returns True if the item occurs one or more times in the list, and False if it
doesn't.
words = ["spam", "egg", "spam", "sausage"]
print("spam" in words) # prints True
print("egg" in words) # prints True
print("tomato" in words) # prints False
The in operator is also used to determine whether or not a string is a substring
of another string.
What is the result of this code? o/p will be 7
nums = [10, 9, 8, 7, 6, 5]
nums[0] = nums[1] - 5
if 4 in nums:
print(nums[3])
else:
print(nums[4])
To check if an item is not in a list, you can use the not operator in one
of the following ways:
nums = [1, 2, 3]
print(not 4 in nums) # True
print(4 not in nums) # True
print(not 3 in nums) # False
print(3 not in nums) # False
Fill in the blanks to print "Yes" if the list contains 'z':
letters = ['a', 'b', 'z']
if "z“ in letters:
print("Yes")
List Functions
The append method adds an item to the end of an existing list.
For example:
nums = [1, 2, 3]
nums.append(4)
print(nums)
The dot before append is there because it is a method of the list class. Methods will be
explained in a later lesson
What is the result of this code?
words = ["hello"]
words.append("world")
print(words[1])
• An error occurs
world
• hello
List Functions 2
To get the number of items in a list, you can use the len function.
nums = [1, 3, 5, 2, 4]
print(len(nums))
Unlike the index of the items, len does not start with 0. So, the list above contains 5 items,
meaning len will return 5.
What is the result of this code? o/p is 4
len is written before the list it is being called on, without a dot.
List Functions 3
The insert method is similar to append, except that it allows you to insert a new item at any
position in the list, as opposed to just at the end. Syntax list.insert(index_posn, new item)
words = ["Python", "fun"]
index = 1
words.insert(index, "is")
print(words)
Elements, that are after the inserted item, are shifted to the right.
What is the result of this code? o/p is 7
nums = [9, 8, 7, 6, 5]
nums.append(4)
nums.insert(2, 11)
print(len(nums))
List Functions 4
The index method finds the first occurrence of a list item and returns its index.
If the item isn't in the list, it raises a ValueError.
letters = ['p', 'q', 'r', 's', 'p', 'u']
print(letters.index('r'))
print(letters.index('p'))
print(letters.index('z'))
There are a few more useful functions and methods for lists.
max(list): Returns the list item with the maximum value
min(list): Returns the list item with minimum value
list.count(item): Returns a count of how many times an item occurs in a list
list.remove(item): Removes an object from a list
list.reverse(): Reverses items in a list.
For example, you can count how many 42s are there in the list using:
items.count(42) # where items is the name of our list.
while Loops
A while loop is used to repeat a block of code multiple times. For example, let's say we
need to process multiple user inputs, so that each time the user inputs something, the
same block of code needs to execute. Below is a while loop containing a variable that
counts up from 1 to 5, at which point the loop terminates.
i = 1
while i <=5:
print(i)
i = i + 1
print("Finished!")
During each loop iteration, the i variable will get incremented by one, until it reaches
5.
So, the loop will execute the print statement 5 times.
The code in the body of a while loop is executed repeatedly. This is called iteration.
While 2
You can use multiple statements in the while loop. For example, you can use an if statement to make decisions. This can
be useful, if you are making a game and need to loop through a number of player actions and add or remove points of the
player.
The code below uses an if/else statement inside a while loop to separate the even and odd numbers in the range of 1 to
10:
x = 1
while x < 10:
if x%2 == 0:
print(str(x) + " is even")
else:
print(str(x) + " is odd")
x += 1
str(x) is used to convert the number x to a string, so that it can be used for concatenation.
In console, you can stop the program's execution by using the Ctrl-C shortcut or by closing the program.
break
To end a while loop prematurely, the break statement can be used. For example, we can break an infinite loop if some condition is
met:
i = 0
while True:
print(i)
i = i + 1
if i >= 5:
print("Breaking")
break
print("Finished")
while True is a short and easy way to make an infinite loop.
In this case, the break statement can be used to end the infinite loop when the user input equals "stop".
For example:
i = 1
while i<=5:
print(i)
i+=1
if i==3:
print("Skipping 3")
continue
An example use case of continue:
An airline ticketing system needs to calculate the total cost for all tickets purchased. The tickets for
children under the age of 1 are free. We can use a while loop to iterate through the list of passengers and
calculate the total cost of their tickets. Here, the continue statement can be used to skip the children.
The code below outputs each item in the list and adds an exclamation mark at
the end:
words = ["hello", "world", "spam", "eggs"]
for word in words:
print(word + "!")
In the code above, the word variable represents the corresponding item of
the list in each iteration of the loop.
During the 1st iteration, word is equal to "hello", and during the 2nd iteration
it's equal to "world", and so on.
For loop 2
The for loop can be used to iterate over strings.
for x in str:
if(x == 't'):
count += 1
print(count)
The code above defines a count variable, iterates over the string and calculates the count of 't' letters in it.
During each iteration, the x variable represents the current letter of the string.
The count variable is incremented each time the letter 't' is found, thus, at the end of the loop it represents
the number of 't' letters in the string.
Similar to while loops, the break and continue statements can be used in for loops, to stop the loop or jump
to the next iteration.
for vs while
Both, for and while loops can be used to execute a block of code for multiple times.
It is common to use the for loop when the number of iterations is fixed. For
example, iterating over a fixed list of items in a shopping list.
The while loop is used in cases when the number of iterations is not known and
depends on some calculations and conditions in the code block of the loop.
For example, ending the loop when the user enters a specific input in a calculator
program.
Both, for and while loops can be used to achieve the same results, however, the for
loop has cleaner and shorter syntax, making it a better choice in most cases.
Range
The range() function returns a sequence of numbers.
By default, it starts from 0, increments by 1 and stops before the
specified number.
The code below generates a list containing all of the integers, up to 10.
numbers = list(range(10))
print(numbers)
You don't need to call list on the range object when it is used in a for
loop, because it isn't being indexed, so a list isn't required.
# module quiz 1
list = [1, 1, 2, 3, 5, 8, 13]
print(list[list[4]])
# Result of inner bracket list[4] --> 5 is used as arg to list[]
# list[5] --> 8
# What does this code do?
# Module Quiz 2
for i in range(10):
if not i % 2 == 0:
print(i+1)
# Module Quiz 3# Fill in the blanks to print the first element of the list, if it
contains even number of elements.
# if list has even no of elements i.e find length of the list and print first
element if there are even no of elements in the list
list = [1, 2, 3, 4]
if len(list) % 2 == 0 :
print(list[0])
# Quiz 4 What does this code output?
letters = ['x', 'y', 'z']
letters.insert(1, 'w')
print(letters[2])