Entering in data using while
Q1. Enter this code into Python and get it 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 >>> ')
Q3. Write a program that allows a user to keep entering in their favourite foods, until they enter -999. The program should print out their list of favourite foods.
Q4. Do some research. What is a 'sentinel' in programming? Identify the sentinel used in Q3.
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 | |||