如何使用用户输入进行“ while”循环?

问题描述 投票:0回答:4

当前使用3.8.1。

[我想知道如何像下面的示例那样进行while True:循环,但是使用用户输入的数字而不是单词(例如,等于或小于100的任何数字将打印出不同的内容。我ve看过这个网站,但对于与我类似的问题,我听不懂答案。

while True:
    question = input("Would you like to save?")
    if question.lower() in ('yes'):
        print("Saved!")
        print("Select another option to continue.")
        break
    if question.lower() in ('no'):
        print ("Select another option to continue.")
        break
    else:
        print("Invalid answer. Please try yes or no.")
python python-3.x
4个回答
1
投票
如何在您的if语句中包含小于/大于大于子句?

while True: # get user input: user_input = input("Would you like to save? ") # convert to int: number = int(user_input) if number <= 100: print("Saved!") print("Select another option to continue.") break elif number > 100: print ("Select another option to continue.") break else: print("Invalid answer. Please try yes or no.")


1
投票
您需要从输入中提取数字,然后对输入的值进行条件评估。

while True: input_val = input("Enter a #?") try: num=int(input_val) except ValueError: print("You have entered an invalid number. please try again") continue if num == 1: print("bla bla") elif num ==2: print("bla bla 2") else: ...


0
投票
input接受用户的输入并输出一个字符串。要对数字进行处理,请检查字符串是否为数字,将其转换为int并做任何您想做的事情

while True: answer = input("How many dogs do you have?") if answer.isnumeric(): num_dogs = int(answer) else: print("Please input a valid number")


0
投票
我认为您可能想要列表而不是元组。

可以这样做:

while True: number = input("Enter a number?") if int(number) in list(n for n in range(100)): print("lower!") elif int(number) in [100]: print ("exact") else: print("higher")

© www.soinside.com 2019 - 2024. All rights reserved.