Week 2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

STRINGS,

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

"a" + str(5) -> "a5"


10
11
String Repetition Operator
▶ Repetition operator (*): the expression n*s, where n is an
integer value and s is a string, evaluates to a String with n
repeats of s
▶ Just as 3 * 2 is equal to 2 + 2 + 2, the expression 3 * "a" is
equivalent to "a" + "a" + "a" ("aaa")
▶ Example:
silly = hi + " " + name * 3
▶ Error:
'a' * 'a'
TypeError: can't multiply sequence by non-int
of type 'str'
12
Character Encoding
▶ For a computer, there is no text, only bytes
▶ Text is an interpretation, a way to visualize bytes in
human-readable form. And if you interpret bytes wrong,
you get strange looking characters, or an error
▶ Character encoding is one specific way of interpreting
bytes: It's a look-up table that says, for example, that a
byte sequence with the value 97 represents 'a'
▶ By default, Python assumes the character encoding
format, UTF-8

13
14
15
Input/Output Example:
▶ Note the difference between outputting string using the
concatenation operator versus the comma in the print
statements below

name = input("Enter your name: ")


Enter your name: Lisa

print("Are you really " + name +"?")


Are you really Lisa?

print("Are you really", name, "?")


Are you really Lisa ?
16
Scripts
▶ As mentioned before, a Python program, a script, is a
sequence of definitions and commands stored in a file
with the extension .py

▶ These definitions are evaluated and the commands are


executed by the Python interpreter in the shell (same
place where we have been executing our commands)

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.

hourly_wage = float(input('Enter your hourly wage: '))


hours = int(input('How many hours have you worked? '))
salary = hourly_wage * hours
print('Your salary is: ' + str(salary) + ' $')

Sample Run:
Enter your hourly wage: 12.5

How many hours have you worked? 37


Your salary is: 462.5 $

18
Formatting output
▶ To format numeric or string values, use the str format()
method
▶ Usage:
'my_format_template_string'.format(values)

▶ Format string includes format fields, enclosed in curly


braces {0}, {1}, {2},... where {0} refers to the first value
in values
▶ The format fields are used to embed formatted values in
the format string, and include special characters that
indicate how the values should be formatted (type of data
and how it will be displayed)
19
Example - Formatting output
salary = 7512.32165
print('Your salary is', salary)

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}

print('Your salary is {0:m.nf}'.format(salary))

m: number of characters reserved for value, including decimal point


n: number of decimal places
f: format specifier for float values
(Note: each optional)

print('Your age is {0:md}'.format(age))


m: places reserved for value
d: format specifier for int values

print('Your name is {0:ms}'.format(name))


m: places reserved for value
s: format specifier for string values
21
Another example - Formatting output
salary = 7510.2685
age = 32
name = 'Jane'

print('Name:{0:10s} Age:{1:05d} Salary: {2:.2f}'.format(name,


age, salary))

Output:
Name: Jane Age: 00032 Salary: 7510.27

print('Salary and age of {0:s} are {2:12.3f}


{1:5d}'.format(name, age, salary))

Output:
Salary and age of Jane are 7510.269 32
22
BRANCHING

23
Flow of Control

▶ Order of statement execution is called flow of control


▶ Unless specified otherwise, the order of statement
execution is linear: one after another

▶ Some programming statements allow us to make decisions


and perform repetitions

▶ These decisions are based on boolean expressions (also


called conditions) that evaluate to true or false

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

'way'.lower() in 'John Wayne'.lower()


Out[2]: True

'was' not in 'I was happy'


Out[3]: False

'was' not in 'I am happy'


Out[4]: True
27
28
Python Operator Precedence

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

If condition is True, the statements are executed.


If it is False, the statements are skipped.

31
Flow chart for branching

Conditonal statement

▶ Test is a boolean expression


▶ If Test is True, True Block is executed
▶ If Test is False, False Block is executed
▶ After the conditional statement is executed, execution
resumes at the code following the statement
32
33
Indentation
▶ Semantically meaningful in Python
▶ Most other programming languages ignore whitespace, and
indentation is for the reader of the code
▶ Python is unusual in that indentation is required and is strictly
enforced during execution
▶ Example:
x = 5 x = 5 x = 5
if x > 10: if x > 10: if x > 10:
print( x ) print( x ) print( x )
print("done") print("done")
Output: ERROR
Output: Output: -
done
34
Branching - if Statements (Example)

if num % 2 == 0:
print("num is even")

# non-zero values evaluate to True


if 5:
print("Condition is true")

# zero values evaluate to false


if 0:
print("Condition is false")

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.

hourly_wage = float(input('Enter your hourly wage: '))


hours = int(input('How many hours have you worked? '))
salary = hourly_wage * hours
if hours > 40:
salary += 100
print('Your salary is: ' + str(salary) + ' $')

Sample Run:
Enter your hourly wage: 12.5

How many hours have you worked? 50


Your salary is: 725.0 $

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

▶ If the condition is true, statement1 is executed; if the condition is


false, statement2 is executed

▶ One or the other will be executed, but not both

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: '))

if grade > 100 or grade < 0:


print('Value out of range')
elif grade > 90:
print('A')
elif grade > 80:
print('B')
elif grade > 70:
print('C')
elif grade > 60:
print('D')
else:
print('F');

print('Done')

Sample Runs:
Enter your grade: 78.5
C
Done

Enter your grade: 105


43
Value out of range
Done
Exercises
1. Input a number from the user, and output ‘[number] is divisible by 5 or 7’ if the
number is divisible by 5 or 7.
2. Write a Python program that initializes a number between 1-9 and prompts the user
to guess the number. If the user guesses incorrectly display the message, “Wrong
Guess!”, on successful guess, user will see a "Well guessed!" message.
3. Input a word and give an appropriate message if the word has the same letter at the
beginning and the end of the word or not.
4. Write a Python program that inputs the height and radius of a cylindrical tank and
the amount of water in the tank (litres) and determines the amount of empty space.
Your program should validate the amount of water (cannot be more than capacity).
5. Input a user’s height (in metres) and weight (in kgs) and calculate his/her BMI and
output the BMI category according the following:
bmi >= 30 Obese
25 >= bmi <30 Overweight
20 >= bmi <25 Normal
bmi < 20 Underweight
See: if-exercises.py

44
ITERATION

45
CONTROL FLOW: Iteration / Repetition

▶ Repetition statements allow us to execute a


statement multiple times
▶ Often they are referred to as loops
▶ Like conditional statements, they are controlled by
Boolean expressions
▶ Python has two kinds of repetition statements:
▶ while loops

▶ for loops

46
CONTROL FLOW: while LOOPS

▶ <condition> evaluates to a Boolean

▶ if <condition> is True, do all the steps inside the while code


block

▶ check <condition> again

▶ repeat until <condition> is False


47
Flow chart for iteration

▶ Test is a boolean expression


▶ As long as Test is True, Loop Body is executed
▶ If Test is False, execution resumes at the code following
the statement
48
While Loop Examples
▶ Write a Python script that does the following. Assume you deposit 10000TL into a
bank account, output the number of years it takes to double the original
investment, assuming a yearly interest rate of 15%.
▶ See: investment.py
▶ In a biology experiment a microorganism population doubles every 10 hours. Write a
Python program to input the initial number of microorganisms and output how long
(days and remaining hours) it will take to have more than 1000000 organisms.
▶ See: biology.py
▶ Write a Python script that inputs positive integers until a negative value is input.
The program should output the average of the values input.
▶ See: average.py
▶ Write a Python guessing game program. The program should generate a random int
between 1 and 10. The user has 3 guesses to guess correctly. The program should
output an appropriate message if the user guesses correctly/does not guess
correctly.
▶ See: while_game.py
49
Terms of Use
➢ This presentation was adapted from lecture materials provided in MIT
Introduction to Computer Science and Programming in Python.
➢ Licenced under terms of Creative Commons License.

50

You might also like