【问题标题】:Converting input to lower case to accept in a while loop将输入转换为小写以在while循环中接受
【发布时间】:2014-01-07 10:57:11
【问题描述】:

我正在尝试创建一个程序,该程序接受输入并将任何输入(例如 Yes / YES)转换为小写,以便在下面的 while 循环中接受。我试过这样做,但没有用。有什么想法吗?

#Import the random function - This only needs to be imported once.
import random

#Use a while loop to allow the user to repeat the process 
repeat = "YES"

while repeat == "yes":

#User is able to input which sided dice they want to throw.    
    dice = input("What side dice do you want to use? 4, 6, or 12?\n")
#4 sided
    if dice == "4":
        #Outputs what sided dice has been chosen and the score thay they rolled.
        print(dice, "sided dice chose.\nYou rolled a", random.randint(1,4))
#6 sided
    elif dice == "6":
        print(dice, "sided dice chose.\nYou rolled a", (random.randint(1,6)))
#12 sided
    elif dice == "12":
        print(dice, "sided dice chose.\nYou rolled a", (random.randint(1,12)))
#Incorrect value entered
    else:
        #Informs the user that the number they have chosen is not a valid option.
        print(dice, "is not a valid choice")
#Asks user if they want to use the program again.
    print("Do you want to use the program again? Yes or No?")
    #Links back to the start of the while loop.
    repeat = input()

【问题讨论】:

  • 您的repeat初始值是大写似乎是个问题;)
  • 你尝试了什么?您的小写尝试在您发布的代码中不可见。

标签: python input case-sensitive lowercase


【解决方案1】:

您的代码甚至永远不会进入while 循环,因为您将重复设置为“是”,然后立即检查它是否为“是”,而事实并非如此。

【讨论】:

    【解决方案2】:

    我会用另一种方式解决这个问题

    while True:
        dice = input(....)
        #etc
        repeat = ''
        while repeat.lower() not in ['yes', 'no']:
            repeat = input('Do you want to use the program again? (yes/no)?')
        if repeat.lower() == 'no':
            break
    

    这将要求用户输入是或否,并继续询问直到提供是或否。

    【讨论】:

      【解决方案3】:

      丹尼尔完全正确。代码开头的'YES' 应格式化为'yes',因为显然'YES 不等于'yes',因此while 循环根本不会运行

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-16
        • 1970-01-01
        • 2013-01-06
        • 1970-01-01
        • 1970-01-01
        • 2014-12-11
        • 2018-02-22
        • 2017-04-26
        相关资源
        最近更新 更多