简体   繁体   English

如何在循环中使用多个输入?

[英]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.为此,我有 2 个函数将使用输入中给出的信息。

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.现在,问题是当用户没有在 integer 上提供答案时,输入必须重新提出问题,直到它有效为止。 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.为此,我为我所做的每个输入都有一个循环,但我希望将它放在 1 个循环中,这样我可以在循环结束时询问他们是否要继续或结束计算器。

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!实际上,您也应该检查float答案的类型!

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.将询问 integer 的逻辑放入 function 并用不同的文本调用它。 Use a loop and a conditional break to exit your endless loop:使用循环和条件break退出无限循环:

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: 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:如果您也想允许更改人员,请将其放入 function 中:

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:一种解决方案是将循环包装在 function 内,并为每个问题调用它:

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) ? ")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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