【发布时间】:2020-05-27 15:04:35
【问题描述】:
我有一个关于引用错误的快速问题
我的代码在 Jupyter 中运行良好,但是
我在 CMD 中运行代码时出错。
我在几个定义中使用了虚拟变量。
CMD 似乎无法识别虚拟变量 '_'
我得到的错误:
Traceback (most recent call last):
File "Vending_Machine.py", line 86, in <module>
print (' {} ({}) {} ({})'.format(drink[0], Vending(_, drink[0]).outofstock(), drink[1],
Vending(_, drink[1]).outofstock()))
NameError: name '_' is not defined
有什么方法可以在 CMD 中处理这段代码吗?
谢谢。
class Vending:
def __init__(self, selection, soda):
self.__selection = selection
self.__soda = soda
def selection(self):
return self.__selection
def soda(self):
return self.__soda
def outofstock(self):
if stock[self.__soda] == 0:
return 'x'
else: #
return " "
class Deposit(Vending):
Total = 0
Change = 0
def __init__ (self, selection, soda):
Vending.__init__(self, selection, soda)
def operating(self):
try:
if self.selection() in Accept_coin:
Deposit.Total += int(self.selection())/100
if Deposit.Change != 0:
Deposit.Change = 0
return Deposit.Change
return Deposit.Total
elif self.selection() not in Accept_coin:
if Deposit.Change != 0: #
Deposit.Change = 0 #
if self.selection() == 'Quit':
Breaking.append('Break')
elif self.selection() not in drink:
Deposit.Change += int(self.selection())/100
return Deposit.Change
if self.selection() in drink:
if Deposit.Change != 0:
Deposit.Change = 0
if Deposit.Total < 0.5:
print('You do not have enough money to purchase it')
if Deposit.Total >= 0.5:
stock[self.selection()] -= 1
Deposit.Change = Deposit.Total - 0.5
Deposit.Total = 0
except ValueError:
print('You put wrong input. Try again')
Accept_coin = ['5', '10', '25']
drink = ['Coke', 'Jolt', 'Pepsi', 'Diet']
stock = {'Coke':2, 'Jolt':2, 'Pepsi':2, 'Diet':2}
Breaking = []
while True:
print ('————————————————')
if 0 not in stock.values():
print (' {} ( ) {} ( )'.format(drink[0], drink[1]))
print (' {} ( ) {} ( )'.format(drink[2], drink[3]))
print ('Total: {:,.2f} Change: {:,.2f}'.format(Deposit.Total, Deposit.Change))
else:
print (' {} ({}) {} ({})'.format(drink[0], Vending(_, drink[0]).outofstock(), drink[1], Vending(_, drink[1]).outofstock()))
print (' {} ({}) {} ({})'.format(drink[2], Vending(_, drink[2]).outofstock(),drink[3],Vending(_, drink[3]).outofstock()))
print ('Total: {:,.2f} Change: {:,.2f}'.format(Deposit.Total, Deposit.Change))
a = Deposit(input('==:').title(), _).operating()
if 'Break' in Breaking:
break
【问题讨论】:
-
您提供的代码实际上并未在其中任何地方定义
_,因此错误是正确的。如果它在 Jupyter 中有效,那么您一定在某处错过了变量的定义。 -
@HampusLarsson 我使用 '_' 作为虚拟变量。我没有什么要补充的。有没有在那里使用 dummy ?
-
Python 中没有“虚拟变量”这样的东西。
_有时用于此目的,但它们总是在某个地方定义,它本身不起作用。 -
_是一个全局变量,在 IPython 等一些 shell 中定义,保存之前的输出。无论如何,您似乎只需要一个空参数,那么为什么不简单地写None或0或'',这取决于函数需要什么?
标签: python cmd nameerror dummy-variable trackback