Professional Documents
Culture Documents
Week 2
Week 2
Week 2
BRANCHING &
ITERATION
CS115
Introduction to Programming in Python
Week 2
Slides are mostly adapted from MIT Open Courseware 1
LAST WEEK
▶ syntax and semantics
▶ scalar objects
▶ simple operations
▶ expressions, variables and values
2
THIS WEEK
▶ string object type
▶ string manipulations
▶ input / output
▶ output formatting
▶ branching and conditionals
▶ indentation
▶ iteration and loops
3
STRINGS
▶ Strings are a sequence of case sensitive characters
▶ May be letters, special characters, spaces, digits
▶ Strings are enclosed in quotation marks or single quotes
hi = "hello there"
name = ‘ana’
▶ Strings may contain numeric values, but the values are
stored as Strings
num = 57
numStr = "56"
4
5
6
String Operations – indexing
▶ Indexing can be used to extract individual characters from a string
▶ If the index given is outside the bounds of the string, an error message
will be displayed
s[3]
IndexError: string index out of range
▶ If negative indexes are given, indexing starts from the end of the string
s[-1]
Out[5]: 'c'
s[-2]
Out[6]: 'b'
s[-3]
Out[7]: 'a'
s[-4]
IndexError: string index out of range
7
8
String Operations - slicing
▶ Slicing is used to extract substrings of arbitrary length
▶ If s is a string, the expression s[start:end] denotes the substring of s that starts at
index start, and ends at index end-1 (step is 1 by default)
s = "abcdefgh"
s[0:len(s)]
Out[8]: 'abcdefgh'
s[0:len(s)-1]
Out[9]: 'abcdefg'
s[2]
Out[10]: 'c'
s[2:4]
Out[11]: 'cd'
s[:]
Out[12]: 'abcdefgh' 9
String Concatenation
▶ String concatenation operator (+): joins two strings
name = "ana"
name = 'ana'
greet = hi + name
greeting = hi + " " + name
▶ To join data of other types to string, you must first convert the
data to a string using the str() function
"a" + 5
TypeError: must be str, not int
13
14
15
Input/Output Example:
▶ Note the difference between outputting string using the
concatenation operator versus the comma in the print
statements below
17
Example: Write a script that inputs the hourly wage of an employee and the
number of hours worked, and calculates and displays the employee’s s salary.
Sample Run:
Enter your hourly wage: 12.5
18
Formatting output
▶ To format numeric or string values, use the str format()
method
▶ Usage:
'my_format_template_string'.format(values)
Output:
Your salary is 7512.32165
vs
salary = 7512.32165
print('Your salary is {0:.2f}'.format(salary ))
Output:
Your salary is 7512.32
20
Format Field {variable_index:format_type}
Output:
Name: Jane Age: 00032 Salary: 7510.27
Output:
Salary and age of Jane are 7510.269 32
22
BRANCHING
23
Flow of Control
24
Branching and Boolean Expressions
▶ Branching (a conditional statement) lets us choose
which statement will be executed next
▶ Conditional statements are implemented using
if / elif / … / else statements
▶ A Boolean expression evaluates to True or False
▶ Boolean expression may include arithmetic
expressions, logical and comparison operators, etc.
25
26
COMPARISON OPERATORS on strings: in, not in
▶ Python has two operators that can also be applied to strings: in and not in
▶ Usage:
<string> <operator> <string>
▶ Examples
'way' in 'John Wayne'
Out[1]: False
29
30
Branching - if Statements
condition must be a
if is a Python Boolean expression, which
reserved word evaluates to True or False
if condition:
statements
31
Flow chart for branching
Conditonal statement
if num % 2 == 0:
print("num is even")
35
36
Example: Write a code fragment (or script) that inputs the
hourly wage of an employee and the number of hours
worked, and calculates and displays the employee’s salary.
The employee will receive 100$ more if he/she has worked
more than 40 hours.
Sample Run:
Enter your hourly wage: 12.5
37
if/else Statement
▶ An else clause can be added to an if statement to make an if-else
statement
if condition:
statement1
else:
statement2
38
if/else Example:
x, y = 2, 3
if x > y:
print('x is larger')
else:
print('y is larger')
print('Done')
Output:
y is larger
Done
39
Example:
x, y = 2, 2
if x > y:
print('x is larger')
elif x < y:
print('y is larger')
else:
print('x is equal to y')
print('Done')
Output:
x is equal to y
Done
40
Example: Write a code fragment (or a script) that inputs the
hourly wage of an employee and the number of hours
worked, and calculates and displays the employee’s salary.
The employee will receive 50% more for each extra hour
he/she has worked above 40 hours.
hourly_wage = float(input('Enter your hourly wage: '));
hours = int(input('How many hours have you worked? '));
if hours < 40:
salary = hourly_wage * hours
else:
salary = 40*hourly_wage + (hours-40)*hourly_wage*1.5
print('Your salary is: ' + str(salary) + ' $')
Sample Run:
Enter your hourly wage: 20
How many hours have you worked? 60
Your salary is: 1400.0 $ 41
Example - Assigning letter grades to students
Range Grade
100 >= grade >90 A
90 >= grade > 80 B
80 >= grade > 70 C
70 >= grade > 60 D
grade <= 60 F
42
grade = float(input('Enter your grade: '))
print('Done')
Sample Runs:
Enter your grade: 78.5
C
Done
44
ITERATION
45
CONTROL FLOW: Iteration / Repetition
▶ for loops
46
CONTROL FLOW: while LOOPS
50