我是Python的新手,我正在写一段代码来展示一个人在玩幸运七游戏时是如何输钱的。下面是代码:
import random
# ask for the input
def main():
money = int(input("Enter the amount of money would like to lose:"))
global max_money
max_money = money
global count_max
count_max = 0
global count
count = 0
# loop
die1 = random.randint(1,6)
die2 = random.randint(1,6)
count += 1
while True:
if die1 + die2 == 7:
money += 5
else:
money -= 1
if money > max_money:
max_money = money
count_max = count
print("You have gone broke after", str(count), "rolls")
print("You should stop after", count_max, "when you had $", max_money)
main()
每当我尝试执行代码时,我都会在终端中收到一条错误消息,指出变量“count”,“count_max”和“max_money”没有定义。我甚至尝试在main函数中将变量设为全局变量,但仍然得到相同的消息。我做错了什么?
1条答案
按热度按时间mzillmmw1#
你的变量是在
main
函数中定义的,所以在你调用这个函数之前它们不会被定义。你是在尝试打印之后调用main()
的,所以它们还没有被定义。在
print
行之前调用main()
。