问题
I am working on a python exercise asking for Write Python programs that read a sequence of integer inputs and print
The smallest and largest of the inputs.
My code so far
def smallAndLarge():
num1 = int(input("Enter a number: "))
num2 = int(input("Enter a number: "))
if num1 > num2:
print(num1,"is the largest number, while",num2,"is the smallest number.")
else:
print(num2,"is the largest number, while",num1,"is the smallest number.")
smallAndLarge()
I am using def smallAndlarge(): since my instructor wants us to use a def function for all of our programs in the future.
My question is how do I ask for multiple inputs from a user until they decided they dont want to add anymore inputs. Thanks for your time.
回答1:
You could let the user flag when they are finished. (live example)
numbers = [];
in_num = None
while (in_num != ""):
in_num = input("Please enter a number (leave blank to finish): ")
try:
numbers.append(int(in_num))
except:
if in_num != "":
print(in_num + " is not a number. Try again.")
# Calculate largest and smallest here.
You can choose any string you want for the "stop", as long as it's not the same as the initial value of in_num
.
As an aside, you should add logic to handle bad input (i.e. not an integer) to avoid runtime exceptions.
In this specific example, you'd also probably want to create smallest
and largest
variables, and calculate their values after each input. Doesn't matter so much for a small calculation, but as you move to bigger projects, you'll want to keep the efficiency of the code in mind.
来源:https://stackoverflow.com/questions/46436223/asking-for-a-sequence-of-inputs-from-user-python3