Python
Control Structures
INTRODUCTION
• Programs are written for the solution to the
real world problems.
• A language should have the ability to control
the flow of execution so that at different
intervals different statements can be
executed.
• A language which supports the control
structures is called a structured
programming language
TYPES OF CONTROL STRUCTURES
A Structured programming is an important
feature of a programming language which comprises
following logical structure:
1. SEQUENCE
2. SELECTION
3. ITERATION OR LOOPING
4. BRANCHING OR JUMPING STATEMENTS
SEQUENCE SELECTION ITERATION
CONDITIONAL AND ITERATIVE
STATEMENTS
2. SELECTION
A selection statement causes the program control
to be transferred to a specific flow based upon
whether a certain condition is true or not.
CONDITIONAL CONSTRUCT – if else STATEMENT
CONDITIONAL CONSTRUCT – if else STATEMENT
Conditional constructs (also known as if statements)
provide a way to execute a chosen block of code based
on the run-time evaluation of one or more Boolean
expressions.
In Python, the most general form of a conditional is
written as follows:
Contd.. Next Slide
CONDITIONAL CONSTRUCT – if else STATEMENT
: Colon Must
if first condition:
first body
elif second condition:
second body
elif third condition:
third body
else:
fourth body
CONDITIONAL CONSTRUCT – if else STATEMENT
FLOW CHART
False
Condition ? Statement 1 Statement 2
Main True
Body
Statement 1
else
Statement 2 body
CONDITIONAL CONSTRUCT – if else STATEMENT
Each condition is a Boolean expression, and each body
contains one or more commands that are to be
executed conditionally.
If the first condition succeeds, the first body will be
executed; no other conditions or bodies are evaluated in
that case.
EXAMPLES – if STATEMENT
else is missing,
it is an optional
statement
OUT PUT
EXAMPLE – if else STATEMENT
: Colon Must
else is
used
OUT PUT
Python Data
Structures
Built in Types
• Lists
• Tuples
• Sets
• Dictionaries
Terms We'll Use
• Data structure-A way of organizing or storing
information.
• Ordered-The data structure has the elements
stored in an ordered sequence
• Mutable-The contents of the data structure can
be changed.
• Immutable-The contents of the data structure
cannot be changed.
Lists
• An ordered group of items
• Does not need to be the same type
– Could put numbers, strings or donkeys in the same list
– List contain items separated by a comma, and enclosed within
square brackets[]. They are mutable.
• List notation
– A = [1,”This is a list”, c, Donkey(“Kong”)]
Methods of Lists
• List.append(x)
– adds an item to the end of the list
• List.extend(L)
– Extend the list by appending all in the given list L
• List.insert(I,x)
– Inserts an item at index I
• List.remove(x)
– Removes the first item from the list whose value is x
Examples of other methods
• a = [66.25, 333, 333, 1, 1234.5] //Defines List
– print (a.count(333), a.count(66.25), a.count('x') ) //calls method
– 2 1 0 //output
• a.reverse() //Reverses order of list
– print (a.reverse()) //Prints reversed list
– [1234.5, 1, 333, 333, 66.25] //Output
• print(a.sort())
– [ 1, 66.25, 333, 333, 1234.5] //Output
• a.index(333)
– print(a.index(333)) //Returns the first index where the given value appears
– 1//output
• print(a[0]) Output?????????
• print(a[1:3]) Output???????
Tuples
Tuples are ordered, immutable collections of
elements.
The only difference between a tuple and a list is
that once a tuple has been made, it can't be
changed!
Tuples contain items separated by a comma, and are enclosed
in parenthesis.
Making a tuple:
a = (1, 2, 3)
Examples
a = (66.25, 333, 333, 1, 1234.5) //Defines Tuple
• print(a) //Prints tuple a
– 66.25, 333, 333, 1, 1234.5 //Output
• a.index(333)
– print(a.index(333) )//Returns the first index where the given value
appears
– 1 //output
• print(a[0])Output?????????
• print(a[0:3]) Output???????
• print(a+a) Output ???????
Tuples So Far
Why would you want a tuple?
Sometimes it's important that the contents of
something not be modified in the future.
Instead of trying to remember that you shouldn't't
modify something, just put it in a tuple.
Sets
A set is an unordered collection of elements where
each element must be unique. Attempts to add
duplicate elements are ignored.
Sets
Creating a set:
mySet = set(['a', 'b', 'c', 'd'])
Or:
myList = [1, 2, 3, 1, 2, 3]
mySet2 = set(myList)
Note that in the second example, the set
would consist of the elements ??????
Sets
Things we can do with a set:
mySet = set(['a‘])
# Add an element:
mySet.add(‘e')
print(mySet)
mySet.add(‘a')
print(mySet)
Output ???????????
#Remove an element:
mySet.remove('b')
print(mySet)
Output ????????????
Sets
There is also support for combining sets.
Returns a new set with all the elements from both
sets:
mySet.union(someOtherSet)
Returns a new set with elements that were in both
sets:
mySet.intersection(someOtherSet)
Tons more methods can be found here:
https://docs.python.org/3/tutorial/datastructures.html
Dictionaries
Lists can be viewed as a structure that map
indexes to values.
If I make the list:
myList = ['a', 'b', 'c']
I have created a mapping from 0 to 'a', 1 to 'b',
and so on. If I put in 0, I'll get 'a' back.
Dictionaries
Dictionaries let use whatever kind of keys we
want!
Instead of having 1 correspond to 'b', I can have
"hello" correspond to 'b'.
Before: Now I
can do things like:
0 'a' "Hello"
'a'
1 'b'
1 'b'
2 'c'
3.3 'c'
Dictionaries
myDict = {}
Keys are enclosed in single quotes (‘’)
plus a colon separated by a comma.
Values are enclosed in double quotes if
they are strings. (“”)
e.g.
myDict ={‘student’: “John”, ‘age’: 20}
Dictionaries
When you look up something in a dictionary, the
thing you're putting in (like the index in a list) is
called a key.
What we get out is called a value. A dictionary
maps keys to values.
myDict["hello"] = 10
^ ^
Key Value
Dictionaries
If we want to get just the keys, or just the values,
there's a function for that!
listOfKeys = myDict.keys()
listOfValues = myDict.values()
Dictionaries
e.g
dict= {‘name’: “Rise”, ‘code’:8, ‘dept’: “CS”}
Determine the Output of the following:
print(dict[‘name’])
print(dict)
print(dict.values())
print(dict.keys())
Dictionaries
Homework
Imagine you have a bunch of university students,
and you're storing their grades in all their classes.
Use a dictionary to look up grades by name: