## Homework for Week 4

##### After this week you can

- Execute the same piece of code multiple times with while and for loops
- Use break and continue to control the flow of the loop
- Create and use infinite loops where appropriate
- Solve common looping tasks, like finding a sum or maximum of values

### Loops and iterations

If we want to let the computer execute a piece of code several times in a row, we can create a loop. Every loop has a body that are the statements to be executed and a condition that controls how many times the body is executed. At each iteration step, the computer checks the condition and determines whether it should execute the body of the loop once more.

Two main forms of loops are indefinite loops (while) and definite loops (for). In an indefinite loop, the number of iteration steps is not known beforehand, whereas, in a definite loop, it is. Both forms of loops have important uses. There also are two commands (break and continue) that allow controlling the flow of the loop inside the loop's body.

Watch the lecture videos:

*Slides** in English*

*Textbook** in English *

### Quiz

Solve the quiz on loops and iterations in Moodle.

### Examples

#### Sum of 1 to 9

In many cases, it is possible to solve the problem using either a *while* or a *for* loop. The following two programs calculate the sum of all numbers from 1 to 9.

The first program uses *while* loop:

print("Finding the sum with while loop") sum1 = 0 a = 1 while a < 10: sum1 = sum1 + a print("Sum so far", sum1) a += 1 print("Sum of numbers 1 to 9 is", sum1)

The second program does the same with the help of *for* loop.

print("Finding the sum with for loop") sum2 = 0 for i in [1, 2, 3, 4, 5, 6, 7, 8, 9]: sum2 = sum2 + i print("Sum so far", sum2) print("Sum of numbers 1 to 9 is", sum2)

Both programs give exactly the same result. The second program is somewhat simpler because it has only one additional variable, but the *for* loop there assumes that the range of possible values is known beforehand.

Note also that the technique to find the sum is the same in both programs. We have a variable that "collects" all operands. It starts with the value 0, and at each iteration step, a new number is added to its current value. In the end, when all values are numbers to the variable one by one, the final value is the sum of all numbers.

#### Largest integer

The following program contains a loop that repeatedly prompts the user for positive integers and outputs the biggest of them at the end. The program continues asking until the user enters 'done'. If the user enters something that is not an integer, the program processes the conversion error using *try* and *except*, prints out a message, and skips to the next number. If the user enters an integer, but it is not positive, then the program finds this out by an *if* statement.

m = 0 while True: line = input("Enter positive integer or 'done': ") if line == 'done': break try: x = int(line) except: print("Please enter an integer") else: if x > 0: if x > m: m = x else: print("Your integer should be positive") if m > 0: print("Maximum is", m)

To find the largest number, we start with the value m = 0. On each iteration step, we compare the number entered with the maximum found so far. If the new number is larger, then we modify the value of variable m so that it will again be the maximum found so far. After we have exhausted all numbers, the value of m will be the maximum of all numbers.

Note also how the program repeatedly prompts for user input. Though it contains a *while True* loop and may potentially run infinitely, it checks the input at each step. If the input is 'done', then the loop is terminated with the *break* command.

### Exercises

#### 1. Number of days

Write a function *number_of_days* with one integer parameter, which represents the number of month; the functions returns the number of days in that month. The numbers of months are 1, 2, ..., 12, and let's assume that it is not a leap year. If the number is some other integer, then the function should return −1.

>>> number_of_days(9)

30

>>> number_of_days(2)

28

>>> number_of_days(100)

-1

Test the function with different arguments.

Then write a program that repeatedly asks the user for a number of month and prints the number of days in that month until the user enters 'done'. The program should perform all necessary input checks and call the function *number_of_days* only if the number of month is an integer in the range 1, ..., 12.

Enter number of month or 'done': *3*

This month has 31 days

Enter number of month or 'done': *4*

This month has 30 days

Enter number of month or 'done': *fifth*

Please enter a valid number

Enter number of month or 'done': *-1*

Number of month must be in the range 1-12

Enter number of month or 'done': *100*

Number of month must be in the range 1-12

Enter number of month or 'done': *10*

This month has 31 days

Enter number of month or 'done': *done*

*Optional modification.* Implement the function *number_of_days* in such a way that it returns 28 or 29 for February, depending on whether the current year in the system is an ordinary year or leap year.

#### 2. Product

Write a program that prompts the user for a positive integer *n* and prints out the value of the expression

{$$2\cdot\frac21\cdot\frac23\cdot\frac43\cdot\frac45\cdot\ldots\cdot\frac{2n}{2n-1}\cdot\frac{2n}{2n+1}$$}

*Hint.* Combine the fractions in the product into pairs.

Enter n: 1

The product is 2.6666666666666665

Enter n: 2

The product is 2.844444444444444

Test your program with an increasing set of inputs. Think yourself: what value does this product approach to, as *n* increases?

#### 3. Rock-paper-scissors

The objective of this task is to create a program that plays the rock-paper-scissors game with the user.

Write a function called *play*, which has two parameters: choices of both players as strings ("rock", "paper", or "scissors"). The function should return "first" if the first player wins and "second" if the second player wins. If the values given to the function are the same, then it should return "draw".

Write a program that first asks the user for a number of turns. Then it asks the user to choose either rock, paper, or scissors. It can be assumed that the inputs are correct. The program generates its random choice and outputs the result using the function *play*. At each turn, the program also outputs the current score, i.e., the number of wins of both players.

This is repeated the specified number of turns. At the end of the game, the program outputs the final result: whether the user won, lost or the game ended in a draw.

*Example*

Enter number of turns: *3*

Enter your choice: *scissors*

Computer chose scissors. Draw! You 0, computer 0.

Enter your choice: *rock*

Computer chose scissors. You win! You 1, computer 0.

Enter your choice: *rock*

Computer chose paper. Computer wins! You 1, computer 1.

The game ended in a draw.

*Hint.* To make random choices, you generate a random number from 1 to 3 and choose the value "rock", "paper", or "scissors" accordingly.

>>> from random import randint

>>> randint(1, 3)

3

>>> randint(1, 3)

1

### Submit your solutions

Submit your solutions of exercises 1, 2, 3 in Moodle under the names *home1.py*, *home2.py*, *home3.py*, respectively.