苹果为什么不增加?
问题描述:
我正在尝试做这个小游戏,并且由于某种原因,当我在“您想选择一个苹果吗?”时输入“Y”?无论我尝试什么,IT都会停留在1。这里是我的代码:苹果为什么不增加?
import time
global choice
global gold
global apples
apples = 0
gold = 0
def begin():
apples = 0
gold = 0
print ("Let's go!")
if gold > 99:
print ("You've won the game!")
play = input ("Do you want to play again? Please answer Y/N.")
if play == "Y":
begin()
if play == "N":
print ("Okay, bye then.")
pick = input ("Do you want to pick an apple Y/N?")
if pick == "Y":
print ("You pick an apple")
apples=apples+1
apples = 1
print ("You currently have,",apples," apples")
begin()
if pick == "N":
sell = input("Do you want to sell your apples Y/N?")
if sell == "Y":
gold
apples
print ("You currently have,",apples,"apples")
print("You have sold your apples")
gold=apples*10
print ("Your gold is now:",gold)
begin()
start()
print ("Hello and welcome!")
name = input("What's your name?")
print ("Welcome, "+name+"!")
print ("The goal of this game is to collect apples")
print ("After you have collected these applaes, you sell them.")
choice = input("Do you want to play? Type Y/N.")
if choice == "Y":
begin()
if choice == "N":
print ("Okay, bye then.")
如果有人可以帮助我解决这个问题,将不胜感激。我只是一个初学者,所以不要太苛刻。对不起,如果这个问题很明显,我才刚刚开始。
答
线后
苹果=苹果+ 1
你有线
苹果= 1
其复位苹果为1,使其显示您只有1个苹果。
答
您在代码的顶层有一堆global
语句。那些什么都不做。如果要使用全局变量,则需要将global
语句放入使用变量的函数中,以告诉Python使用该名称的全局变量而不是使用局部变量。
尝试:
apples = 0 # don't repeat these lines inside the function
gold = 0 # (unless you want the variables to get reset each time you call it)
def begin():
global gold # move the global statements inside the function
global apples
# ...
的choice
变量不出现在begin
功能使用,所以你不需要为它global
声明。
正如Dobellyo指出的那样,您在函数内的作业中也有一些杂乱的逻辑。您需要决定何时要增加现有值,以及何时要分配固定值。一个接一个地做这两件事通常是没有意义的。