Entering in data using while - Answers
Q1. Enter the code working:
poem = [] #Create an empty list. Each element will be a line in the poem.
print('Write a poem .... ')
print('Press <ENTER> again to quit.')
line = input('Enter the first line >>> ') # initalise line
while line != '': # while line is not empty
poem.append(line)
line = input('Please enter the next line >>> ')
print('\n')
print('Your poem is:')
for line in poem:
print(line)
Q2. Explain how this block of code works:
line = input('Enter the first line >>> ') # initalise line
while line != '': # while line is not empty
poem.append(line)
line = input('Please enter the next line >>> ')
This code works by asking the user to enter in the first line, which is stored in the variable line. While line is not empty, the contents are appended to the poem and the user is asked to enter another line. If they just press the enter key line != '' becomes false and the block exits.
Q3. To write a program that allows a user to keep entering in their favourite foods, until they enter -999:
food = [] #Create an empty list.
print('Please enter a food you like >>> ')
print('Enter -999> to quit.')
line = input('Enter the first food >>> ') # initalise line
while line != '-999': # while line is not empty
food.append(line)
line = input('Please enter the next food >>> ')
print('\n')
print('Your favourite foods are:')
for item in food:
print(item)
Q4. A 'sentinel' in programming is a value used to guarantee the termination of a loop construct. The value chosen for the sentinel would not be part of the data any user is likely to enter. In the last program, -999 was the sentinel whereas the data being enter was food items.
Q5. Enter this code:
1 #Add up lots of numbers ...
2 print('Keep entering numbers. Enter -999 to quit')
3 temp = 0
4 total = 0
5 while temp != -999:
6 temp = float(input('Please enter a number >>> '))
7 total = total + temp
8 print('The total is ...',total)
It should allow the user to keep entering in numbers, until they enter -999. It should then add up the numbers and display the total. The program doesn't work. Investigate why by dry-running the code using a trace table. Remember, only enter in a new value on a new line when that value actually changes. The trace table has been started for you. Enter the following data into the trace table: 17, 4, 5, -999 When you have identified the problem, correct it and test the program with your own values to check it works.
line | temp | total | temp != -999 | Output |
2 | Message | |||
3 | 0 | |||
4 | 0 | |||
5 | True | |||
6 | 17 | |||
7 | 17 | |||
5 | True | |||
6 | 4 | |||
7 | 21 | |||
5 | True | |||
6 | 5 | |||
7 | 26 | |||
5 | True | |||
6 | -999 | |||
7 | -973 | |||
8 | The total is -973 | |||
Lines 6 and 7 in the program should be swapped around to make the program work as intended.