SyntaxWarning Python noob收到错误

时间:2014-07-09 21:51:24

标签: python

我正在编写一个简单的游戏,当我尝试运行该程序时,它说: SyntaxWarning:name' apples'在全球声明之前使用

这是我的代码。我想知道是否有人能告诉我原因!

import time
global gold
global apples
apples = 0
gold = 0

def start():
    print ("Hello and welcome to apples, made by Rahul Mathilakath")
    name = input ("What's your name: ")
    print ("Welcome " + name + "!")
    print ("The objective of the game is to collect apples and then sell them to earn gold.")
    choice = input ("Do you want to play? Y/N ")
    if choice == "Y":
        print ("Let's get started!")
        Game()
    if choice == "N":
        print ("Okay bye ...")
def Game():
    global apples
    global gold
    pick = input ("Do you want to pick an apple? Y/N ")
    if pick == "Y":
        time.sleep(1)
        print ("You picked an apple.")
        apple=apples+1
        print ("You have ",apples," apples.")
        Game()
    if pick == "N":
        sell = input ("Do you want to sell you apples? Y/N")
        if sell == "Y":
            global gold
            global apples
            print ("You currently have ",apples," apples")
            print ("You have sold your apples")
            gold = apples*5
            apples = 0
            Game()
        if sell == "N":
            Game()

感谢您的帮助!对不起,如果答案非常简单,我对此很新!

2 个答案:

答案 0 :(得分:1)

你有话

global gold
global apples

Game()函数中出现两次。您只需要为每个范围声明一次全局。由于您已在Game()中立即宣布它们为全球版,因此您无需再次在该函数中执行此操作。这应该消除语法警告。

答案 1 :(得分:0)

而不是使用“ global”,而是运行一个函数,然后从该函数内部将该函数作为您的数字返回。例如...

def add_one():
    return 1

number = input('enter a number')
number = number + add_one()

您已返回该值,该值将函数定义为1

我曾经在测试过程中学到了这一点,所以它真的卡在我身上了:D

另一个提示是,如果answer [0] =='y':,因为此人可以回答y,yes或yeseroony中的任何内容,只要它以小写y开头,它仍会继续。如果要将其转换为小写,可以执行answer.lower()然后继续。

有点题外话,但我希望对您有所帮助!