CS 303e Discussion Notes
Topics: functions and for loops
Q&A about Exam 1
for loops are definite loops - they execute the loop body a certain
number of times.
for <loopCounter> in <list>:
for i in range(3):
0 1 2
Exercise: Write a for loop that
prompts the user for 5 quiz grades, and then prints the average. Print
two digits after the decimal point in the average.
In the sample output, the user's inputs are underlined. Match the
sample output exactly.
Enter quiz score 1: 10
Enter quiz score 2: 8
Enter quiz score 3: 9
Enter quiz score 4: 10
Enter quiz score 5: 10
Your quiz average is 9.40.
A function is a chunk of code with a name.
To define a function:
def <functionName>(<parameter1>, <parameter2>,
<statement(s)> # this is the function
Note: If the function is
performing a calculation and returning the result to the user, the last
statement in the function body is a return statement.
def makeSentence(word1, word2, word3):
sentence = word1 + " " + word2 + " " + word3
sent1 = makeSentence("I", "love", "CS303e")
sent2 = makeSentence("Elvis", "totally", "rocks")
sent3 = makeSentence("It", "snowed", "Tuesday")
I love CS 303e
Elvis totally rocks
It snowed Tuesday
Exercise: Write a program that
contains two functions: a main() function and an area function that
takes as arguments the length and width of a rectangle, and returns the
area of a rectangle. The main method should ask the user to enter
the length and width of two different rectangles, and then report which
one has the largest area. Use the area function to compute the area of
Length of rectangle 1? 3
Width of rectangle 1? 4
Length of rectangle 2? 6
Width of rectangle 2? 4
The area of rectangle 2 is larger, since 24 > 12.