简体   繁体   中英

Asking for a sequence of inputs from user python3

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.

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM