为什么我收到此错误?图片有详细信息。我需要让_spent值打印适当的次数。所以,比如它经过循环3次,我需要它打印3.我认为这是1来自哪里。我不喜欢它!
pennies = 10
nickels = 10
dimes = 10
quarters = 10
print("\nWelcome to change-making program.")
in_str = input("\nEnter the purchase price (xx.xx) or `q' to quit: ")
while in_str.lower() != 'q':
dollar_str, cents_str = in_str.split(".")
if in_str.lower() == 'q':
quit()
in_int = int(float(in_str) * 100)
if in_int < 0:
print("Error: purchase price must be non-negative.")
in_str = input("\nEnter the purchase price (xx.xx) or `q' to quit: ")
if in_int > 0:
payment = input("\nInput dollars paid: ")
payment_int = int(float(payment) * 100)
change = payment_int - in_int
#determines if there payment input
if payment_int < in_int:
print("Error: Insufficient payment.")
payment = input("\nInput dollars paid: ")
payment_int = int(float(payment) * 100)
if change == 0:
print("No change.")
#determines how many quarters, dimes, nickels, and pennies are left
while change >= 25 and quarters > 0:
change = change - 25
quarters_spent = 0
quarters_spent += 1
quarters = quarters - quarters_spent
print(quarters_spent)
while change >= 10 and dimes > 0:
change = change - 10
dimes_spent = 0
dimes_spent += 1
dimes = dimes - dimes_spent
print(dimes_spent)
while change >= 5 and nickels > 0:
change = change - 5
nickels_spent = 0
nickels_spent += 1
nickels = nickels - nickels_spent
print(nickels_spent)
while change >= 1 and pennies > 0:
change = change - 1
pennies_spent = 0
pennies_spent += 1
pennies = pennies - pennies_spent
if quarters == 0 and dimes == 0 and nickels == 0 and pennies == 0:
print("Error: ran out of coins.")
quit()
print("\nCollect Payment Below:")
print(10 - quarters, "Quarters")
print("\nStock: ", quarters, "Quarters, ", dimes, " Dimes, ", nickels, " Nickels, ", pennies, " Pennies ")
in_str = input("\nEnter the purchase price (xx.xx) or `q' to quit: ")
pennies = pennies
nickels = nickels
dimes = dimes
quarters = quarters
答案 0 :(得分:1)
此错误表示您在尝试使用之前未定义值nickels_spent
。
我猜错误就在这一行:print (nickels_spent)
。
可能发生的情况是,当您尝试运行该变量时,用于为该变量赋值的while
语句条件不正确,因此它尚未定义,但您仍尝试用它。
在while
循环之前尝试调试,看看到底发生了什么。
答案 1 :(得分:0)
您只在while循环
中定义并初始化了此变量nickels_spent
但是,如果不满足条件,程序将跳过循环并跳转以执行此print(nickels_spent)
语句,其中此变量尚未定义。
你可以
或者
取决于您的计划的目的