【问题标题】:How do you convert inputted data to uppercase so that it is recognised by a while loop?如何将输入的数据转换为大写,以便被 while 循环识别?
【发布时间】:2014-01-07 12:08:21
【问题描述】:

我正在尝试创建一个程序,只要用户输入的是“是”或某种形式的“是”,就可以继续使用该程序。我已经创建了程序,它可以工作并继续循环,只要他们以大写形式输入 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()

【问题讨论】:

  • but this does not work - 真的吗?在我看来它应该如此。你能展示一下你尝试过的版本吗?
  • 您使用哪种语言?
  • 不直接相关,但 cmets 不应该只说代码的作用。代码说明了代码的作用;您无需在询问用户Do you want to use the program again? 的行上评论Asks user if they want to use the program again.。
  • 我已经编辑了我的代码以显示我尝试过的原始版本#user2357112
  • 不相关,但是if dice in ["4", "6", "12"]: 然后randint(1, int(dice)) 怎么样?

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


【解决方案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 等忽略空格的语言时,您不会遇到此类问题。

【讨论】:

  • 不,while 后面的空格没问题。 Python 可能会以这种缩进样式抛出异常,这不太可能导致他的问题。
  • 好吧,我不熟悉 Python。我刚刚用谷歌搜索了教程。更好的答案总是受欢迎的! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-16
  • 1970-01-01
  • 2018-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-17
相关资源
最近更新 更多