Skip to main content
 首页 » 编程设计

Python if 语句不起作用

2025年05月04日10oomusou

我刚刚开始学习 python,通过“像计算机科学家一样思考”这本书,我被一些语言语法卡住了。

def amt(): 
    amount = input("Enter your amount: ") 
    amount = int(amount) 
    if amount >= 20: 
        twe = amount / 20 
        amount = amount - twe * 20 
            print("You need to pay %d twenty dollar bills" %(twe)) 
    if amount >= 10: 
        ten = amount / 10 
        amount = amount - ten * 10 
        print("You need to pay %d ten dollar bills" %(ten)) 
    if amount >= 5: 
        five = amount / 5 
        amount = amount - five * 5 
        print("You need to pay %d five dollar bills" %(five)) 
    if amount >= 1: 
        one = amount / 1 
        amount = amount - one * 1 
        print("You need to pay %d one dollar bills" %(one)) 
 
amt() 

当我使用输入 7 运行此命令时,我收到如下错误消息:

Traceback (most recent call last): 
  File "dollars.py", line 21, in <module> 
    amt() 
  File "dollars.py", line 7, in amt 
    print("You need to pay %d twenty dollar bills" %(twe)) 
UnboundLocalError: local variable 'twe' referenced before assignment 

为什么 if 语句不能正常工作?即使输入值小于 20,它仍然进入第一个 if 语句

请您参考如下方法:

它在视觉上并不明显,但您混合了制表符和空格。看起来 print 语句在 if 中,但实际上不是。

这是您的源代码在 Stack Overflow 的文本编辑器中的样子: