为什么在这种特殊情况下没有定义?

时间:2015-06-25 16:41:11

标签: python python-2.7

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

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()

2 个答案:

答案 0 :(得分:6)

\uFFF0实际上会尝试评估您传递给它的任何内容。你想要input()

有关raw_input() vs input()的详细信息,请参阅this question

答案 1 :(得分:0)

我发现使用python 2的输入可以很好地使用Codecademy教授的raw_input。使用python 3,它的input()函数运行良好。访问strikes和point时出现问题,应该在main()中声明为全局,并且最好将a和b放入main(),这样当main()重新运行时用户会重新掷骰子,否则会被卡住相同的滚动,可以在3次播放中终止,也可以永不终止。 if-then逻辑可以使用一些修复,以便" n"答案会按照以下建议终止游戏以及其他一些更改,例如格式化初始消息,使其不会打印到正常大小的窗口之外:

import random
points = 0
strikes = 0

def main():
    a = random.randint(1, 6)
    b = random.randint(1, 6)
    global points
    global strikes
    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!"""
    answer = raw_input('Play? y for yes, n for n: ')
    if answer == "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.")
                exit(1)
            else:
                main()
    elif answer == "n":
        print ("Game over. You earned this many points.")
        print points

main()

通过将罢工计算为罢工 - =点数和终止时使用" n"来抵消点数罢工可能会很有趣。使用点数进行抵消积分 - =罢工。

Codecademy免费提供Python 2的所有实践培训。我最近经历了它并且很好。对于Python 3,Bill Lubanovic的Python介绍是非常好的,因为它从初学者级别开始并逐步发展到中级专业知识,非常易读,在章节结尾处有练习,附录中的解决方案和github上的代码与其相对较短一些Python论文(例如学习Python和编程Python) - 它涵盖了200-250页的7-9章中的核心Python 3,其余的是更专业和可选但有趣的领域,如NoSQL数据库访问,Web服务和风格。