简体   繁体   中英

How do I use multiple inputs in a loop?

I'm building a application that calculates your daily energy expenditure. For this I have 2 functions which will use the information given in the inputs.

Now, the problem is when an user does not provide an answer on integer, the input has to re-ask the question untill it's valid. For this, I have a loop for every input I've made, but I'd like to have it in 1 loop so I can ask the question at the end of the loop if they want to continue or end the calculator.

Below is my code (it's in Dutch)

while True:
    try:
        leeftijd = int(input("Wat is uw leeftijd in jaren ? "))
        break
    except ValueError:
        print("Vul het opnieuw in !")
while True:
    try:
        gewicht = int(input("Wat is uw gewicht in kilogrammen ? "))
        break
    except ValueError:
        print("Vul het opnieuw in !")
while True:
    try:
        lengte = int(input("Wat is uw lengte in centimeters ? "))
        break
    except ValueError:
        print("Vul het opnieuw in !")
geslacht = input("Wat is uw geslacht (m/v) ? ")
while True:
    try:
        beweging = int(input("Hoeveel wandelt u per dag (minuten) ? "))
        break
    except ValueError:
        print("Vul het opnieuw in !")

I hope this is clear enough to understand. Thanks in advance!

Actually you should check the type of the float answer too!

You could use a loop like this one, with a list of questions. Here, I store the results in a dictionnary where the key is the question, but they could be stored as a list or other objects too.

questions = [
    ["Wat is uw leeftijd in jaren ? ", int],
    ["Wat is uw gewicht in kilogrammen ? ", int],
    ["Wat is uw lengte in centimeters ? ", int],
    ["Wat is uw geslacht (m/v) ? ", float]
    ["Hoeveel wandelt u per dag (minuten) ? ", int]
]

def ask(question, variabletype):
    while True:
      try:
          answers[question] = variabletype(input(question))
          break
      except ValueError:
          print("Variable should be of type", variabletype.__name__)

answers = {}
for question, variabletype in questions:
    answers[question] = ask(question, variabletype)

Or without the loop over the question:

def ask(question, variabletype):
    while True:
      try:
          answers[question] = variabletype(input(question))
          break
      except ValueError:
          print("Variable should be of type", variabletype.__name__)

answers = {}
for question, variabletype in questions:
    answers[question] = ask(question, variabletype)

a0 = ask("Wat is uw leeftijd in jaren ? ", int)
a1 = ask("Wat is uw gewicht in kilogrammen ? ", int)
a2 = ask("Wat is uw lengte in centimeters ? ", int)
a3 = ask("Wat is uw geslacht (m/v) ? ", float)
a4 = ask("Hoeveel wandelt u per dag (minuten) ? ", int)

Put the logic for asking the integer into a function and call that with different texts. Use a loop and a conditional break to exit your endless loop:

def ask_int(text, error_text):
    while True:
        try:
            return int(input(text))
        except ValueError:
            print(error_text)

leeftijd = ask_int("Wat is uw leeftijd in jaren ? ", "Vul het opnieuw in !")
gewicht = ask_int("Wat is uw gewicht in kilogrammen ? ", "Vul het opnieuw in !")
lengte = ask_int("Wat is uw lengte in centimeters ? ", "Vul het opnieuw in !")
geslacht = input("Wat is uw geslacht (m/v) ? ")

while True:
    beweging = ask_int("Hoeveel wandelt u per dag (minuten) ? ", "Vul het opnieuw in !")
    # do something with the things - calculate & print
    print(leeftijd, gewicht, lengte, geslacht, beweging)

    if input("Calculate another time? (*/n)") == "n":
        break  # leaves the loop

Output:

# All inputes:   A,1,1,1,m,a,42,y,100,n

Wat is uw leeftijd in jaren ? A
Vul het opnieuw in !
Wat is uw leeftijd in jaren ? 1
Wat is uw gewicht in kilogrammen ? 1
Wat is uw lengte in centimeters ? 1
Wat is uw geslacht (m/v) ? m
Hoeveel wandelt u per dag (minuten) ? a
Vul het opnieuw in !
Hoeveel wandelt u per dag (minuten) ? 42
1 1 1 m 42
Calculate another time? (*/n) y
Hoeveel wandelt u per dag (minuten) ? 100
1 1 1 m 100
Calculate another time? (*/n) n

If you want to allow changing the person as well, put that into a function as well:

def ask_person():
    lee = ask_int("Wat is uw leeftijd in jaren ? ", "Vul het opnieuw in !")
    gew = ask_int("Wat is uw gewicht in kilogrammen ? ", "Vul het opnieuw in !")
    leng = ask_int("Wat is uw lengte in centimeters ? ", "Vul het opnieuw in !")
    ges = input("Wat is uw geslacht (m/v) ? ")

    return lee, gew, leng, ges  # return a tuple of your data


# get initial person data, decompose tuple into variables    
leeftijd, gewicht, lengte, geslacht = ask_person()

while True:
    beweging = ask_int("Hoeveel wandelt u per dag (minuten) ? ", "Vul het opnieuw in !")

    print(leeftijd,gewicht,lengte,geslacht,beweging)

    choice = input("Calculate another time? (y/n) or C to change person") 
    if choice == "n":
        break  
    elif choice == "C":
        # change to other person data
        leeftijd, gewicht, lengte, geslacht = ask_person()

Read Asking the user for input until they give a valid response for more inspiration on the topic.

One solution is to wrap the loop inside of a function, and call it for each question:

def question(q):
    while True:
        try:
            var = int(input(q))
            return var
        except ValueError:
            print("Vul het opnieuw in !")

leeftijd = question("Wat is uw leeftijd in jaren ? ")
gewicht = question("Wat is uw gewicht in kilogrammen ? ")
lengte = question("Wat is uw lengte in centimeters ? ")
beweging = question("Hoeveel wandelt u per dag (minuten) ? ")
geslacht = input("Wat is uw geslacht (m/v) ? ")

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