表示未定义变量时出错?

2024-09-21 09:42:30 发布

您现在位置:Python中文网/ 问答频道 /正文

#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

Tags: theinyouiftimedefsleeprestart
1条回答
网友
1楼 · 发布于 2024-09-21 09:42:30

addCheckaddStrawberries中的一个局部变量,这意味着它不能在函数之外看到。我建议将其作为参数传递给lel,即调用lel(addCheck),并将lel定义为def lel(addCheck)。或者,您可以通过在赋值之前在addStrawberries中插入语句global addCheck,使addCheck成为一个全局变量,但是全局变量往往是讨厌的。你知道吗

相关问题 更多 >

    热门问题