Python 为什么即使我说“它也在掷骰子?”;否";当它问我是否想再做一次时?

Python 为什么即使我说“它也在掷骰子?”;否";当它问我是否想再做一次时?,python,function,Python,Function,我在写掷骰子游戏,但当我问“你想再掷一次骰子吗?”我说“不”时,它还是滚了。我猜这与答案变量有关。然而,我希望它打印“也许下次”而不是。你能帮助我吗?这是我的密码: import random def response(): if answer == "yes" or answer == "Yes" : rolldice() else: print("Maybe next time!") def rolldice(): randomnumb = random

我在写掷骰子游戏,但当我问“你想再掷一次骰子吗?”我说“不”时,它还是滚了。我猜这与
答案
变量有关。然而,我希望它打印“也许下次”而不是。你能帮助我吗?这是我的密码:

import random

def response():
  if answer == "yes" or answer == "Yes" :
    rolldice()
  else:
    print("Maybe next time!")


def rolldice():
    randomnumb = random.randrange(1,7)
    print("You got number " + str(randomnumb) + "!")
    answer = input("Would you like to roll the dice again? \n ")
    response()


answer = input("Would you like to roll the dice? \n")
response()

试试这个。您必须将答案作为参数传递给函数响应:

import random

def response(answer):
    if answer == "yes" or answer == "Yes" :
      rolldice()
    else:
      print("Maybe next time!")


def rolldice():
    randomnumb = random.randrange(1,7)
    print("You got number " + str(randomnumb) + "!")
    response(input("Would you like to roll the dice again? \n "))

response(input("Would you like to roll the dice? \n"))

这是真的吗
rolldice()
没有按应有的方式缩进,我想python解释器应该会抱怨需要缩进的块。刚刚试过-在第5行给出
IndentationError:我需要缩进的块。将代码复制到网站是一个错误。我没有那样运行它。问题是
rolldice
正在创建一个名为
answer
的局部变量,而不是重新分配全局变量。如果希望以这种方式使用全局变量,则需要在每个函数体顶部使用
global answer
声明它们。但更好的解决方案是不使用全局变量将值作为参数传递,并在有意义时返回值,当您无法在没有共享状态的情况下编写类的函数和方法时,使用
self.answer
。缺少
,第二行到最后一行(带文本)