非常基本的python

时间:2014-10-10 21:41:31

标签: python dice

收到错误但我不知道为什么......(我正在学习) 我的代码;

import random
input("Hit enter to roll the dice")
global answer
def rollDice():
    result = random.randrange(1,6)
    print ("It landed on.." + str(result))
    answer = input("would you like to play again? [y/n]")
rollDice();


if (answer == "y" or "Y"):
    rollDice();

错误; (一些剧本的作品)

Hit enter to roll the dice
It landed on..5
would you like to play again? [y/n]y
Traceback (most recent call last):
  File "diceRoller.py", line 11, in <module>
    while (answer == "y" or "Y"):
NameError: name 'answer' is not defined

4 个答案:

答案 0 :(得分:5)

除了答案所说的内容之外,我建议你不要使用global,而是return这个人是否想要继续,并继续以此为基础,例如:

import random
input("Hit enter to roll the dice")
def rollDice():
    result = random.randrange(1,6)
    print("It landed on.. " + str(result))
    answer = input("Would you like to play again? [y/n]")
    if answer in ("y", "Y"):
        return True
    return False

while rollDice():
    continue

此外,使用循环而不是if语句。否则,您将无法询问用户他/她是否想要无限期地继续。

答案 1 :(得分:0)

您的函数定义需要知道answer是全局的。因此,将global声明放在定义主体中。

def rollDice():
    global answer
    result = random.randrange(1,6)
    print ("It landed on.." + str(result))
    answer = input("would you like to play again? [y/n]")

另外

if (answer == "y" or "Y"):

应该是

if answer in ('y', 'Y'):

否则您要检查(answer=="y")("Y"),后者总是评估为True

如果您希望无限期地继续滚动,只要用户肯定地回答,那么您的if应该是while

while answer in ('y', 'Y'):

答案 2 :(得分:0)

global关键字必须位于函数体内。另外,像Falmarri所说,if (answer=="y" or "Y")需要“如果回答==”y“或回答==”Y“

答案 3 :(得分:0)

首先,global answer对全局范围没有影响。把它放在函数中。

但调试代码非常困难,因为回溯指的是一行代码,而这些代码并未显示在您显示的源代码中! (while vs if

无论如何,if answer = 'y' or 'Y'应为if answer in tuple('yY')