Week 4
Week 4
3
for Loops and Strings
• A for loop can examine each character in a string in order.
for name in string:
statements
4
raw_input
raw_input : Reads a string from the user's keyboard.
– reads and returns an entire line of input
>>> name
'Paris Hilton'
5
raw_input
• raw_input can be used to read a number from the user's
keyboard by casting the result as an int
– Only numbers can be cast as ints!
– Example:
age = int(raw_input("How old are you? "))
print "Your age is", age
print "You have", 65 - age, "years until
retirement"
Output:
How old are you? 53
Your age is 53
You have 12 years until retirement
6
Exercise
• Write a program that reads two employees' hours and
displays each's total and the overall total.
– Cap each day at 8 hours.
Employee 1: How many days? 3
Hours? 6
Hours? 12
Hours? 5
Employee 1's total hours = 19 (6.33 / day)
7
Formatting Text
"format string" % (parameter, parameter, ...)
8
if
if condition:
statements
– Example:
gpa = int(raw_input("What is your GPA? "))
if gpa > 2.0:
print "Your application is accepted."
9
if/else
if condition:
statements
elif condition:
statements
else:
statements
– Example:
gpa = int(raw_input("What is your GPA? "))
if gpa > 3.5:
print "You have qualified for the honor roll."
elif gpa > 2.0:
print "Welcome to Mars University!"
else:
print "Your application is denied."
10
Logical Operators
Operator Meaning Example Result
== equals 1 + 1 == 2 True
!= does not equal 3.2 != 2.5 True
< less than 10 < 5 False
> greater than 10 > 5 True
<= less than or equal to 126 <= 100 False
>= greater than or equal to 5.0 >= 5.0 True
11
Exercise
• Write a program that judges a couplet by giving it one point if it
– is composed of two verses with lengths within 4 chars of each other,
– "rhymes" (the two verses end with the same last two letters),
– alliterates (the two verses begin with the same letter).
• A couplet which gets 2 or more points is "good"
Example logs of execution:
(run #1)
First verse: I joined the CS party
Second verse: Like "LN" and Marty
2 points: Keep it up, lyrical genius!
(run #2)
First verse: And it's still about the Benjamins
Second verse: Big faced hundreds and whatever other
synonyms
0 points: Aw, come on. You can do better...
12