## exercises

### high-low part 4

Now make `hilo.py`

use a loop to make the user keep guessing until
they get it right:

>>> *%Run hilo.py*
Pick a number: **3**
Wrong! Guess again.
Pick a number: **4**
Wrong! Guess again.
Pick a number: **1**
You got it right!

If you’re stuck, look at the password program on the previous page.
The structure of that program is similar to what we need to do here.

Show solution

```
import random
computer_number = random.randint(1, 5)
guess = int(input("Pick a number: "))
while guess != computer_number:
print("Wrong! Guess again.")
guess = int(input("Pick a number: "))
print("You got it right!")
```

### high-low part 5

For the next feature, we’ll make `hilo.py`

tell you if your guess was
too small or too large:

>>> *%Run hilo.py *
Pick a number: **3**
Your guess is too high.
Pick a number: **1**
Your guess is too low.
Pick a number: **2**
You got it right!

Show solution

```
import random
computer_number = random.randint(1, 5)
guess = int(input("Pick a number: "))
while guess != computer_number:
if guess < computer_number:
print("Your guess is too low.")
else:
print("Your guess is too high.")
guess = int(input("Pick a number: "))
print("You got it right!")
```

Now that this feature is done, you can make the program pick a number
between 1 and 100 instead of 1 and 5.

### high-low part 6

Modify `hilo.py`

so that it will tell you how many guesses you have
left. Don’t worry about making the problem actually stop when you run
out of guesses. We’ll handle that later.

>>> *%Run hilo.py *
You have 7 guesses left
Pick a number: **50**
Your guess is too high.
You have 6 guesses left
Pick a number: **45**
Your guess is too high.
You have 5 guesses left
Pick a number: **40**
Your guess is too high.
You have 4 guesses left
Pick a number: **35**
Your guess is too high.
You have 3 guesses left
Pick a number: **30**
Your guess is too high.
You have 2 guesses left
Pick a number: **25**
Your guess is too high.
You have 1 guesses left
Pick a number: **20**
Your guess is too high.
You have 0 guesses left
Pick a number: **15**
Your guess is too low.
You have -1 guesses left
Pick a number: **17**
Your guess is too high.
You have -2 guesses left
Pick a number: **16**
You got it right!

Show solution

```
import random
guesses_left = 7
computer_number = random.randint(1, 100)
print("you have", guesses_left, "guesses left")
guess = int(input("Pick a number: "))
guesses_left -= 1
while guess != computer_number:
if guess < computer_number:
print("Your guess is too low.")
else:
print("Your guess is too high.")
print("you have", guesses_left, "guesses left")
guess = int(input("Pick a number: "))
guesses_left -= 1
print("You got it right!")
```

previous: counting
next: and, or, not