# While Loops (Level 5)

## Question Loop Examples

### A Basic Question Loop

```answer = ""

answer = input("What is the capital of Paris?")

print("Correct!")
```

### A Question Loop with a Count

Keep a count of how many attempts were made

```answer = ""
count = 0

answer = input("What is the capital of Paris?")
count = count + 1

print("Correct!")
print("You took ", count , "goes")
```

### A Question Loop with a Flag

```finished = False
number = 0
print("Denary to Binary Converter")
print("Enter -1 to finish")

while (finished == False):
number = int(input("Enter a number in Denary"))
if (number == -1):
finished = True
else:
print("{:b}".format(number))
```

### A Question Loop with a Count and a Flag

```finished = False
correct = False
tries = 3

while (finished == False):
finished = True
correct = True
elif (tries == 1):
finished = True
correct = False
else:
tries = tries - 1
print("Wrong.  You have", tries, "tries remaining")

if(correct == True):
print("You're in!")
else:
print("Locked out!")
```

## Exercise

1. Write a program that asks “Are we there yet?” and prompts the user to enter an answer. The program loops until the user enters “Yes”. The program then outputs “Hooray!”
2. Write a program that asks the user to guess a number between 1 and 10. The program loops until the user enters the correct answer . The program then outputs then the number of guesses made.
3. Modify the program from question 2 so that the user now has to guess a number between 1 and 100. The program outputs “Too low” if the guess is lower the number, “Too high” if the guess is highter than the number and “Correct” if the guess is correct. The program then terminates
4. The following code converts pounds to kilograms. Write a program that prompts the user to enter a weight in pounds or -1 to terminate. The program will output the weight in kilograms. If -1 is entered the program will print “Goodbye”
```pounds = 4
kilograms = pounds * 0.453592
print(kilograms)
```
1. A house alarm system is triggered when the front door is open. The user has three attempts to enter a four digit code. If the user enters the correct code the system outputs “Deactivated!”. If the user enters the incorrect code the system outputs the number of attempts remaining. If the user does not enter the correct code within three attempts the system outputs “Alarm!”

Write a program to simulate the above.

### Extension

Write a quiz program that asks the user 5 questions. The user is allowed 2 attempts at each question. At the end the program prints out the users score out of 5

This site uses Akismet to reduce spam. Learn how your comment data is processed.