我从 pydev 获得"undefined variable"下面的代码。有人可以告诉我出了什么问题吗



这是我编写的代码。我只是python的初学者,这是我第一次练习的一部分。所以,问题是我在最后一行代码中得到了dieFace1和dieFace2的"未定义变量"错误。

def rollDie():
    die1 = [1,2,3,4,5,6] 
    die2 = [1,2,3,4,5,6]
    dieFace1 = int(random.shuffle(die1))
    dieFace2 = int(random.shuffle(die2))
    dieFaceTotal = dieFace1+dieFace2
    while (userIn > pot or userIn < 0): 
       userIn = (raw_input(" Invalid bet, please enter the right bet amount"))
    print "You rolled a ", dieFace1, "and ", dieFace2

random.shuffle()不返回任何内容。在你的代码中,你应该得到这样的东西:

TypeError: int() argument must be a string or a number, not 'NoneType'

简单地说,只需在自己的行上执行random.shuffle(die1)即可。但在您的情况下不需要这样做:如果您想要列表中的随机值,请使用random.choice():

dieFace1 = random.choice(die1)

检查变量。是dieFace2还是dieFace2?

您的代码有很多问题,我已经更正了它,并提供了注释,以便您学习。

import random
def rollDie(pot): #we need pot defined, so pas the value of the pot in
    die1 = [1,2,3,4,5,6] 
    die2 = [1,2,3,4,5,6]
    random.shuffle(die1) #.shuffle works in place so die1 is modified it returns None
    random.shuffle(die2) #same as above
    #ALL of the above is essentially redundant, use randint(1,6) below instead
    dieFace1 = die1[0] #this is superflous, use randint(1,6)
    dieFace2 = die2[0] #this is superflous, use randint(1,6)
    dieFaceTotal = dieFace1+dieFace2
    userIn = int(raw_input("Bet: ")) #use input for python 3
    while (userIn > pot or userIn < 0):  #pot was passed in from function call
         userIn = int(raw_input(" Invalid bet, please enter the right bet amount")) #again input for Python 3, we also need to conver to int
    return dieFace1, dieFace2
dieFace1, dieFace2 = rollDie(5) #store the values retuned in dieFace1 and dieFace2 THESE are in scope for this block level
print "You rolled a ", dieFace1, "and ", dieFace2 #ensure names are capitialised

相关内容

最新更新