Skip to main content
 首页 » 编程设计

python之为什么在这种特殊情况下没有定义 y

2025年05月04日16softidea

我是 Python 2.7 的新手,我尝试创建一个简单的骰子游戏,但是我在让计算机识别 y 时遇到了一些困难,因为无论我做什么,它都不会将答案识别为 y 或 n。这是下面的代码。

import random 
a = random.randint(1, 6) 
b = random.randint(1, 6) 
points = 0 
strikes = 0 
 
def main(): 
    print """Welcome to the two dice game. Depending on the result, you will earn a point or a strike. Three strikes end the game. Good luck!""" 
    anwser = input('Play? y for yes, n for no') 
    if anwser == "y": 
       print a 
       print b 
       if a == b: 
          print ("Congrats! You earned a point!") 
          points = points + 1 
          main() 
    else: 
        print("That's a strike...") 
        strikes = strikes + 1 
        if strikes == 3: 
            print("That's three strikes, game over.") 
            break 
        else: 
            main() 
    if anwser == n: 
       print ("Game over. You earned this many points.") 
       print points 
 
main() 

请您参考如下方法:

input() 实际上会尝试评估您传递给它的任何内容。您需要 raw_input()。

参见 this question有关 input() 与 raw_input() 的更多信息。