函数嵌套Python

时间:2017-02-19 22:06:13

标签: python

我是一名历史专业学生,因为我对编写这个课程很有挑战,所以请假设我对编码知之甚少。

我以为我的程序即将完成,但是收到的错误是roll函数中的变量没有定义。但是,当我自己运行roll功能时没有问题。我确定这是一个简单的错误,但是,想知道如何纠正它,以及为什么。 (学习东西很酷)

import random

def roll():
    die1 = random.randint(1, 6)
    die2 = random.randint(1, 6)          
    r =  die1 + die2
return r

def Turn():
    pScore = 0
    cScore = 0
    turn = True
    while turn == True:
        pChoice = str(input("Would you like to roll? Type yes or no."))
        if pChoice == "yes":
            roll()
            if r == 2:
                turn = False
                pScore = 0
                print("You have rolled snake eyes. Your turn is over and         your score is 0.")
            elif die1 == 1 or die2 == 1:
                turn = False
                pScore += r
                print("You rolled {}, {} and your score is {}. your turn is     over".format(die1, die2, pScore))
            else :
                turn = True
                pScore += r
            print("You rolled {}, {} and your score is {}".format(die1, die2, pScore))
        if pChoice == "no":
            turn = False
            print("You have chosen not to roll. Your score is {}.".format(pScore))

    while turn == False:
        roll()
        if r == 2:
            turn = True
            cScore = 0
            print("The computer has rolled snake eyes. It's turn is over")
        elif die1 == 1 or die2 == 1:
            turn = true
            print("The computer {}, {} and its score is {}. Its turn is over".format(die1, die2, cScore))
        else:
            turn = False
            pScore =+ r
            print("The computer {}, {} and its score is {}.".format(die1, die2, cScore))

def main():
    pScore = 0
    cScore = 0
    while pScore <100 and cScore <100:
        Turn()
    if pScore >= 100:
        print("Your score is {} you win!".format(pScore))    
        return
    elif cScore >= 100:
        print("The computer score is {} you lose!".format(cScore))
        return
main()

1 个答案:

答案 0 :(得分:0)

Turn中,您引用不在范围内的r;见https://docs.python.org/3/reference/executionmodel.html。你想要的似乎是r = roll(),而不仅仅是roll()

其他一些需要注意的事项:

  • 出于与上述相同的原因,pScorecScore永远不会在main中实际更新;您需要从Turn返回这些值,以便能够在main中使用它们。特别是,main中出现的循环是无限的。
  • while turn == True可以简写为while turn。同样,while turn != True可以写为while not turn
  • turn = True保证为turn时,True不会做任何事情。
  • return中的main语句不执行任何操作。