-4

这是我写的代码。我只是 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
4

3 回答 3

0

您的代码存在很多问题,我已对其进行了更正并提供了评论,以便您学习。

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
于 2013-05-21T05:50:33.410 回答
0

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

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

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

dieFace1 = random.choice(die1)
于 2013-05-21T05:47:19.337 回答
0

检查你的变量。是dieFace2还是dieface2?

于 2013-05-21T05:43:22.913 回答