错误说未定义变量?

时间:2016-05-27 11:50:51

标签: python call

#Intro
import time
import random

def restart():
    bowlSize = random.randint(1,100)
    bowlStrawberries = 0

def lel():
    while bowlSize > bowlStrawberries:
        if (addCheck + bowlStrawberries) > bowlSize:
            print('You´re filling the bowl..')
            time.sleep(2)
            print('...and...')
            time.sleep(2)
            print('Your mom slaps you!')
            restart()


def addStrawberries():
    print('The bowl has ' + str(bowlStrawberries) + ' strawberries in it')
    print('How many strawberries do you want to add?')
    addCheck = input()
    lel()

print('STRAWBERRY (:')
time.sleep(2)
print('Okey so you have a bowl kinda')
time.sleep(2)
print('And you have a bag with 100 strawberries')
time.sleep(2)
print('So ur mom forces you to fill the bowl')
time.sleep(2)
print('But she will slap you if a strawberry drops on the floor')
time.sleep(2)
print('So you have to fill it up in as few tries as possible without overfilling it')
time.sleep(2)

restart()

addStrawberries()

我是编程新手,今天是我的第五天,我无法理解为什么会出错。你可能有类似的问题,但我是新的,我不知道该搜索什么。当我选择比碗空间更高的值时,我基本上希望它重新启动。

确切错误:

Traceback (most recent call last):
  File "C:/Users/***/Documents/strenter code herew.py", line 44, in <module>
    addStrawberries()
  File "C:/Users/***/Documents/strw.py", line 27, in addStrawberries
    lel()
  File "C:/Users/***/Documents/strw.py", line 14, in lel
    if (addCheck + bowlStrawberries) > bowlSize:
NameError: name 'addCheck' is not defined

1 个答案:

答案 0 :(得分:0)

addCheckaddStrawberries中的局部变量,这意味着它不能在函数外部看到。我建议将其作为参数传递给lel,即致电lel(addCheck)并将lel定义为def lel(addCheck)。或者,您可以通过在分配addCheck之前在global addCheck中插入语句addStrawberries来使SELECT f.id, f.takeoff, f.arrival, ct.name as fromCity, f.toCity, c.name as company, p.name as plane , cf.name FROM flights f, companies c, planes p, cities ct,cities cf WHERE f.idCompany = c.id AND f.idPlane = p.id AND f.fromCity = ct.id AND f.toCity = cf.id ORDER BY f.takeoff ASC 成为全局变量,但全局变量往往是icky。