CS 303e Discussion Notes

Topics:
functions and for loops

for loops

for loops are definite loops - they execute the loop body a certain number of times.

Syntax:
```for <loopCounter> in <list>:     <statement(s)>```

Example:
for i in range(3):
print i,

Output:
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.

Sample Output:
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

Functions

A function is a chunk of code with a name.

To define a function:
```def <functionName>(<parameter1>, <parameter2>, ..., <parameter>):     <statement(s)>  # this is the function body```

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.

Example:
```def makeSentence(word1, word2, word3):     sentence = word1 + " " + word2 + " " + word3     return sentence  def main():     sent1 = makeSentence("I", "love", "CS303e")     sent2 = makeSentence("Elvis", "totally", "rocks")     sent3 = makeSentence("It", "snowed", "Tuesday")     print sent1     print sent2     print sent3 main() ```
Output:
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 each rectangle.

Sample Output:
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.