Tutorial 5
234128 – Introduction to
Computing with Python
Written and edited by Bronislav Demin
Today
• While Loop
• Strings
• Lists
• Lists and Strings
234128 – Introduction to Computing with Python 2
WHILE LOOP
234128 – Introduction to Computing with Python 3
While Loop
• While loop structure:
expression
While False
block
True
Statements
• As long as the expression evaluates to True, the following
indented statements will be executed.
• When the expression evaluates to False, continue with the
code following the while block.
• It is possible for indented statements to not be evaluated
at all if the expression is False right from the start.
234128 – Introduction to Computing with Python 4
Example: Get Positive Number
234128 – Introduction to Computing with Python 5
Fibonacci Numbers
• 𝐹0 = 1
• 𝐹1 = 1 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,…
• 𝐹𝑛 = 𝐹𝑛−2 + 𝐹𝑛−1
234128 – Introduction to Computing with Python 6
Fibonacci Numbers: Code
234128 – Introduction to Computing with Python 7
East Gate Restaurants Competition
• A survey of East Gate restaurants
is taking place in GTIIT.
• Write a program that collects
student votes.
• The program will count the votes
and declare what is the best
restaurant in East Gate!
234128 – Introduction to Computing with Python 8
East Gate Restaurants Competition
• Three restaurants are participating in the survey:
1. Old Number 4 老四小炒 (vote ‘1’ or ‘n4’)
2. GuoTiaoHenXi 粿条很细 (vote ‘2’ or ‘gt’)
3. RuanGuoGuo Dumpling 阮锅锅饺子 (vote ‘3’ or ‘gg’)
• Each vote is accepted by submitting the corresponding string.
• Voting stops when an empty string is received as input.
234128 – Introduction to Computing with Python 9
East Gate Restaurants Competition
234128 – Introduction to Computing with Python 10
East Gate Restaurants Competition
234128 – Introduction to Computing with Python 11
East Gate Restaurants Competition
234128 – Introduction to Computing with Python 12
CONTINUE, BREAK
234128 – Introduction to Computing with Python 13
Continue/Break Flowchart
• Break - exits the loop block
completely and stops
evaluating the expression. False
expression
• Continue - stops only the
True
current iteration and goes
continue statement break
back to evaluate the
expression.
234128 – Introduction to Computing with Python 14
Continue - Example
• Read N integer numbers from the
user.
• Sum up only positive numbers.
Negative
number?
Skip to
the next
iteration!
• If a number is negative or zero, the
sum will not be updated!
234128 – Introduction to Computing with Python 15
Break - Example
• Read N integer numbers from the
user.
• Sum up only positive numbers.
• If at any point a negative number is
given, exit the while loop completely.
Negative
number?
Stop
looping!
234128 – Introduction to Computing with Python 16
Exercise 3 – Count Digits in Number
• Write a program which gets a number x and digit d as input.
• The program finds how many times the digit d appear in number
x.
• You may assume all the numbers are positive.
• Examples:
- The digit 1 appears two times in 215610
- The digit 0 appears one time in 10
234128 – Introduction to Computing with Python 17
Exercise 3 – Count Digits: Code
234128 – Introduction to Computing with Python 18
STRINGS
234128 – Introduction to Computing with Python 19
Strings
• Thus far, we learned how to assign strings: x = ‘Hello’
• And concatenate strings: ‘bye’ + ‘bye’ → ‘byebye’
• Return length of a string: len(‘byebye’) → 6
• Strings also support indexing (positive and negative):
‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘ ‘ ‘W’ ‘o’ ‘r’ ‘l’ ‘d’
0 1 2 3 4 5 6 7 8 9 10
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
234128 – Introduction to Computing with Python 20
Strings
• To get a character in a specific location
inside a string, we use an index inside
square brackets:
• If the index is outside the
length of the string, we get
an Index Error:
Same with negative indices!
234128 – Introduction to Computing with Python 21
LISTS
234128 – Introduction to Computing with Python 22
Lists
• Lists in Python are ordered collections of items.
• To create a list, we use square brackets:
234128 – Introduction to Computing with Python 23
Lists
• A list can be empty or include a whole variety of
different objects:
234128 – Introduction to Computing with Python 24
Lists - Indexing
• Like strings, we can
access specific values
using indices:
• Invalid indices result
in an Index Error:
234128 – Introduction to Computing with Python 25
List Initialization
• We can create a simple list:
• How about a list of certain length?
• Empty list?
234128 – Introduction to Computing with Python 26
Lists: in Operator
• Using the in operator, we can check existence inside a list:
True if user
entered ‘y’ or ‘n’
Equivalent to:
if x==‘n’ or x==‘y’
False if user entered
anything which is
not ‘y’ and ‘n’
234128 – Introduction to Computing with Python 27
List – Common Use Cases
When do we need a list?
1. Calculate average or median of heights
2. Find min or max in a collection of numbers
3. Keeping track of multiple items that share similar
properties.
The items can be numbers, characters, strings, dates,
words, images, etc.
234128 – Introduction to Computing with Python 28
LISTS AND STRINGS
234128 – Introduction to Computing with Python 29
Lists and Strings
String List
Immutable – cannot be Mutable – can be changed
changed and modified
Each item in the string is a Each item can be anything,
character of size 1 even a list (nested list)
Length can be given using Length can be given using
len() function len() function
234128 – Introduction to Computing with Python 30
String Methods
• Split: Converts String → List >>> sentence = 'You cannot end a
sentence with because because because
is a conjunction.'
my_string.split(separator) >>> sentence.split(' ')
['You', 'cannot', 'end', 'a',
'sentence', 'with', 'because',
string string 'because', 'because', 'is', 'a',
'conjunction.']
• separator – any character or >>> sentence.split('')
string (Empty string – behaves like Traceback (most recent call last):
space ‘ ‘ separator). File "<stdin>", line 1, in <module>
ValueError: empty separator
• Very useful when getting input. >>> sentence.split(‘because')
• Split: Sentence → Words ['You cannot end a sentence with ', '
', ' ', ' is a conjunction.']
234128 – Introduction to Computing with Python 31
String Methods
• Join: Converts List to String >>> band_list = ['The
Beatles', 'Led Zeppelin', 'The
Rolling Stones', 'Pink Floyd',
separator.join(my_list) 'Queen']
>>> ';'.join(band_list)
string list
'The Beatles;Led Zeppelin;The
Rolling Stones;Pink
• separator – any character or Floyd;Queen'
string.
>>> ''.join(band_list)
'The BeatlesLed ZeppelinThe
Rolling StonesPink FloydQueen'
234128 – Introduction to Computing with Python 32
Encryption
• Write a program which encrypts a string in such
a way that each character will become its
successor.
234128 – Introduction to Computing with Python 33
Encryption - Code
• Write a program which encrypts a string in such a way that each
character will become its successor.
234128 – Introduction to Computing with Python 34
234128 – Introduction to Computing with Python 35