0% found this document useful (0 votes)
127 views39 pages

2 Python Control Structures

This document discusses Python control structures like Booleans, comparison operators, if/else statements, and lists. Booleans represent true and false values. Comparison operators like == and != are used to compare values and return a Boolean. If/else statements allow running code conditionally based on if an expression evaluates to true. Additional elif statements and nested ifs allow for more complex conditional logic. Boolean operators like and, or, and not can be used to chain multiple conditions together. Lists are used to store multiple items of different data types. Items in a list can be accessed by their index. Lists can be nested within other lists.

Uploaded by

Arya Bhatt
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
127 views39 pages

2 Python Control Structures

This document discusses Python control structures like Booleans, comparison operators, if/else statements, and lists. Booleans represent true and false values. Comparison operators like == and != are used to compare values and return a Boolean. If/else statements allow running code conditionally based on if an expression evaluates to true. Additional elif statements and nested ifs allow for more complex conditional logic. Boolean operators like and, or, and not can be used to chain multiple conditions together. Lists are used to store multiple items of different data types. Items in a list can be accessed by their index. Lists can be nested within other lists.

Uploaded by

Arya Bhatt
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 39

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

Comparison operators are also called Relational operators.


Python also has operators that determine whether one number (float or
integer) is greater than or smaller than another. These operators are > and <
respectively.
print( 7 > 5 ) # prints True
print( 10 < 10 ) # prints False

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")

The expression determines whether 10 is greater than 5. Since it is, the


indented statement runs, and "10 greater than 5" is output. Then, the
un-indented statement, which is not part of the if statement, is run,
and "Program ended" is displayed.

Notice the colon at the end of the expression in the if statement.


Else statement
The if statement allows you to check a condition and run some statements, if the
condition is True.
The else statement can be used to run some statements when the condition of the if
statement is False.

As with if statements, the code inside the block should be indented.


x = 4
if x == 5:
print("Yes")
else:
print("No")

Notice the colon after the else keyword.


elif Statements
Multiple if/else statements make the code long and not very readable. The elif (short for else if) statement is a shortcut to
use when chaining if and else statements, making the code shorter. The same example from the previous part can be
rewritten using elif statements:
num = 3
if num == 1:
print("One")
elif num == 2:
print("Two")
elif num == 3:
print("Three")
else:
print("Something else")

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")

Indentation is used to define the level of nesting.


Boolean Logic
Boolean logic is used to make more complicated conditions for if statements that rely on more than one condition.
Python's Boolean operators are and, or, and not.

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

You can chain multiple conditional statements in an if statement using


the Boolean operators.
Operator Precedence
Operator precedence is a very important concept in programming. It is an extension
of the mathematical idea of order of operations (multiplication being performed
before addition, etc.) to include other operators, such as those in Boolean logic.

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

Python's order of operations is the same as that of normal mathematics:


parentheses first, then exponentiation, then multiplication/division, and then
addition/subtraction.
Chaining Multiple Conditions
You can chain multiple conditional statements in an if statement using the Boolean operators. For example, we can
check if the value of a grade is between 70 and 100:grade = 88
if (grade >= 70 and grade <=100):
print("Passed!")
You can use multiple and, or, not operators to chain multiple conditions together.
What is the result of this code?
x = 4
y = 2
if not 1 + 1 == y or x == 4 and 7 == 8:
print("Yes")
elif x > y:
print("No")
• Yes No
• Yes
No
Quiz
1. What part of an if statement should be indented?
The statements within it
• All of it
• The first line
2. What is the output of this code?
spam = 7
if spam > 5:
print("five")
if spam > 8:
print("eight")
• eight
• nothing
 five
3. What is the output of this code?
num = 7
if num > 3:
print("3")
if num < 5:
print("5")
if num ==7:
print("7")
•What is the result of this code? •What is the result of this code?
if 1 + 1 == 2:
if 2 * 2 == 8: if not True:
print("if") print("1")
else:
print("else") elif not (1 + 1 == 3):
•There is no output print("2")
else else:
•If
•What is the result of this code? print("3")
•What is the result of this code?
if (1 == 1) and (2 + 2 > 3):
print("true") if 1 + 1 * 3 == 6:
else: print("Yes")
print("false") else:
true print("No")
•true false No
•false •Yes
Lists
Lists are used to store items of different data types.
A list is created using square brackets with commas separating items.
words = ["Hello", "world", "!"]

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])

The first list item's index is 0, rather than 1, as might be expected.


create a list and print its 3rd element.
list = [42, 55, 67]
print(list[2])
Sometimes you need to create an empty list and populate it later during the program. For example, if you are
creating a queue management program, the queue is going to be empty in the beginning and get populated with
people data later. An empty list is created with an empty pair of square brackets.
empty_list = []
print(empty_list)

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

Trying to access a non-existing index will produce an error.


Typically, a list will contain items of a single item type, but it is also possible to include several
different types. Lists can also be nested within other lists.
number = 3
things = ["string", 0, [1, 2, number], 4.56]
print(things[1])
print(things[2])
print(things[2][2])
Nested lists can be used to represent 2D grids, such as matrices.
For example:
m = [
[1, 2, 3],
[4, 5, 6]
]
print(m[1][2])
A matrix-like structure can be used in cases where you need to store data in row-column format. For
example, when creating a ticketing program, the seat numbers can be stored in a matrix, with their
corresponding rows and numbers. The code above outputs the 3rd item of the 2nd row.
List Operations
The item at a certain index in a list can be reassigned.
For example:
nums = [7, 7, 7, 7, 7]
nums[2] = 5
print(nums)
You can replace the item with an item of a different type.
What is the result of this code?
nums = [1, 2, 3, 4, 5]
nums[3] = nums[1]
print(nums[3]) #prints 2
List Operations 2
Lists can be added and multiplied in the same way as strings.
For example:
nums = [1, 2, 3]
print(nums + [4, 5, 6])
print(nums * 3)

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

letters = ["a", "b", "c"]


letters.append("d")
print(len(letters))

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.

An example use case of break:


An infinite while loop can be used to continuously take user input. For example, you are making a calculator and need to take
numbers from the user to add and stop, when the user enters "stop".

In this case, the break statement can be used to end the infinite loop when the user input equals "stop".

Using the break statement outside of a loop causes an error.


continue
Another statement that can be used within loops is continue. Unlike break, continue jumps back to the
top of the loop, rather than stopping it. Basically, the continue statement stops the current iteration and
continues with the next one.

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.

Using the continue statement outside of a loop causes an error.


for Loop
The for loop is used to iterate over a given sequence, such as lists or strings.

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 example: str = "testing for loops"


count = 0

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)

In order to output the range as a list, we need to explicitly convert it to


a list, using the list() function.
Range 2
If range is called with one argument, it produces an object with values from 0 to that
argument.
If it is called with two arguments, it produces values from the first to the second.
For example:
numbers = list(range(3, 8))
print(numbers)
print(range(20) == range(0, 20))
Remember, the second argument is not included in the range, so range(3, 8) will not
include the number 8.
What is the result of this code? o/p  3
nums = list(range(5, 8))
print(len(nums))
Range 3
range can have a third argument, which determines the interval of the sequence
produced, also called the step.
numbers = list(range(5, 20, 2))
print(numbers)
We can also create list of decreasing numbers, using a negative number as the third
argument, for example
list(range(20, 5, -2))
What is the result of this code?
nums = list(range(3, 15, 3))
print(nums[2])
• 3
 9
• 0
• 12
for Loops with range
The for loop is commonly used to repeat some code a certain number
of times. This is done by combining for loops with range objects.
for i in range(5):
print("hello!")

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])

You might also like