如何将输入数据转换为大写,以便通过while循环识别?

时间:2014-01-07 12:08:22

标签: python input while-loop case-sensitive uppercase

我正在尝试创建一个程序,允许用户继续使用该程序,只要他们输入的是YES或是一种形式。我已经创建了程序并且它可以工作并继续循环,只要它们以大写形式输入YES。

我试图修改我的代码,以便最后当它询问是否要重复它时需要输入并将其转换为大写我知道你可以使用而重复是在[“”,“”]但是是否有更好的方法来编写代码,以便在最终输入时将输入的数据转换为大写?

我试过了

repeat = input()
repeat = repeat.upper()

但这不起作用。有什么建议吗?

#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 = repeat.upper()

1 个答案:

答案 0 :(得分:-1)

您的问题似乎是缩进。由于 Python 使用缩进识别代码块,因此正确执行此操作非常重要。

我注意到你的线条缩进如下:

    print("Do you want to use the program again? Yes or No?")
    #Links back to the start of the while loop.
        repeat = input()
        repeat = repeat.upper()

请尝试按如下方式缩进它们,它应该有效:

    print("Do you want to use the program again? Yes or No?")
#Links back to the start of the while loop.
    repeat = input()
    repeat = repeat.upper()

请查看Lines and Indentation section here

您可能还需要在while条件后删除空行。 但也许不是。

提示:使用 Java 等空格忽略语言时不会出现此类问题。