【问题标题】:How do I get my program to only accept certain inputs in python 2.x如何让我的程序只接受 python 2.x 中的某些输入
【发布时间】:2016-07-10 20:42:35
【问题描述】:

我希望这个程序只接受 "yes ,"y", "Yes" 中的任何一个作为输入文本,但由于某种原因,当我输入其中一个时没有任何反应,并且下面的循环似乎没有运行:

import time

print ("Welcome to my first ever RPG! created 10/07/2016")
time.sleep(2)
begin = raw_input("Would you like to start the game?")

Start = False

if begin == ("yes" , "y" , "Yes" ):
    Start == True        

while Start == True:   
    player_name = raw_input("What would you like to name your character")
    print ("welcome " + player_name.capitalize())

(PS:首选最简单的解决方案,我对python有点陌生)

【问题讨论】:

    标签: python-2.7 input python-2.x


    【解决方案1】:

    begin 是一个字符串,("yes" , "y" , "Yes" ) 是一个元组。因此,begin == ("yes" , "y" , "Yes" ) 永远不会是真的。但是,元组中有三个字符串可以与begin 进行比较。这样做的详细方法是写:

    for element in ("yes" , "y" , "Yes" ):
        if element == begin:
            Start = True
    

    Python 有一种方便的方法,可以使用 in 关键字在更少的代码行中执行此操作:

    if begin in ("yes" , "y" , "Yes" ):
        Start = True
    

    请注意,我还将Start == True 更改为Start = True,因为== 仅用于比较,在这里您可能需要使用= 完成的分配。

    捕捉用户输入的更多变体(“Yes”、“YES”、“yES”、“y”、“Y”等):

    begin = begin.strip().lower()
    if begin in ("y", "yes"):
        Start = True
    

    【讨论】:

      【解决方案2】:

      您可以使用原始解决方案,然后像这样更改它(不推荐):

      if begin.strip() == "yes" or begin.strip() == "y" or begin.strip() == "Yes":
      

      或者只是检查元组中的包含:

      if begin.strip() in ("yes" , "y" , "Yes" ):
      

      甚至更好:

      if begin.strip().lower().startswith('y'):
      

      .strip() 处理用户可能输入的任何空格。

      你也想改变

      Start == True
      

      Start = True
      

      因为前一行是相等测试而不是赋值,所以在您的情况下,Start 始终为 False。

      【讨论】:

      • if begin.strip().lower().startswith('y'): 将匹配任何以“y”开头的单词...
      • @jDo 是的,但它是一个足够简单的程序,觉得还不如 eh
      猜你喜欢
      • 2023-03-30
      • 1970-01-01
      • 2017-12-16
      • 1970-01-01
      • 2011-05-15
      • 1970-01-01
      • 1970-01-01
      • 2015-10-08
      • 1970-01-01
      相关资源
      最近更新 更多