我是初学者,这是我正在上的课程。我知道关于return
,但它不允许我在这段代码中做我想做的事情
这是包含变量的函数:
def disp_cookies():
# This stuff is just for a print display
inx = 0 # Displays list vertically
while inx < len(flavor_names):
print("{}. {}".format(inx + 1, flavor_names[inx]))
inx += 1
valid_data = False
while not valid_data:
try:
# This is the variable I need
flavor = int(input("\nSelect a number for flavor> "))
if 0 < flavor <= len(flavor_names):
item_list.append(flavor)
print(flavor_names[int(flavor) - 1])
return flavor # This is the return
break
except Exception:
print("\nError. Please try again")
else:
print("\nPlease enter a valid response")
这是我尝试使用该变量的地方:
print("\n", flavor) # This is outside of the function in the previous snippet btw
print("\n{}s, {} box(es), ${} total".format(flavor_names[flavor - 1], qty_list[order_no], item_total))
这是我得到的错误:
Traceback (most recent call last):
File "C:\Users\wiche\Documents\School\Python CIS122\L8_orderCost.py", line 95, in <module>
print("\n", flavor)
NameError: name 'flavor' is not defined
我可以通过定义来消除错误flavor
在函数之外,但是当我使用它时变量中的数据是错误的。知道我能做些什么来解决它吗?
请记住,我是一个绝对的初学者,你所看到的基本上是我迄今为止对 python 的理解
谢谢你!