155k views
3 votes
Use a loop to accept commands from the user. This loop must support the following commands:

a. "a": Ask the user for a number, and add it to a list. i. You can assume that the user will always provide a valid number.
b. "M": Find the largest number in the list, and output this value. i. If the list has no elements, print "No elements in list." ii. HINT: You can either start your search by declaring the first value in the list the maximum, or by initializing your maximum to the value sys.float_info.min, so anything will be larger than it.
c. " m ": Find the smallest number in the list, and output this value. i. If the list has no elements, print "No elements in list." ii. HINT: You can either start your search by declaring the first value in the list the minimum, or by initializing your minimum to the value sys.float_info.max, so anything will be smaller than it.
d. " q ": Stop looping and end the program.
e. Any other command is invalid. However, the loop will continue until the user

User Teboto
by
9.0k points

1 Answer

3 votes

Final answer:

To solve this problem, you can use a loop to accept commands from the user. Within the loop, you can implement logic for each command, including adding numbers to a list, finding the largest and smallest numbers in the list, and ending the program. If an invalid command is entered, an appropriate message should be displayed.

Step-by-step explanation:

To solve this problem, you can use a loop in your code that accepts commands from the user. Within the loop, you can implement the logic for each command. Here's an example:

import sys

numbers_list = []

while True:
command = input('Enter a command: ')
if command == 'a':
number = float(input('Enter a number: '))
numbers_list.append(number)
elif command == 'M':
if not numbers_list:
print('No elements in list.')
else:
max_number = numbers_list[0]
for num in numbers_list:
if num > max_number:
max_number = num
print('The largest number is:', max_number)
elif command == 'm':
if not numbers_list:
print('No elements in list.')
else:
min_number = numbers_list[0]
for num in numbers_listing:
if num < min_number:
min_number = num
print('The smallest number is:', min_number)
elif command == 'q':
break
else:
print('Invalid command.')

The question involves writing a program that loops to accept commands from the user to perform various operations on a list of numbers. The supported commands are 'a' to add a number to a list, 'M' to find and display the largest number in the list, 'm' to find and display the smallest number in the list, and 'q' to quit the loop and end the program. If the 'M' or 'm' command is invoked when the list is empty, the program should output "No elements in list." If any other command is entered, it should be considered invalid but the loop should continue prompting the user for input.

User Gerhard Stein
by
7.8k points

No related questions found