Swa*_*dra 1 python if-statement conditional-statements
我刚开始学习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()
Run Code Online (Sandbox Code Playgroud)
当我用一些输入运行时说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
Run Code Online (Sandbox Code Playgroud)
为什么if语句不能正常工作?即使输入值小于20,它仍然进入第一个if语句
它在视觉上并不明显,但你正在混合标签和空格.看起来这个print语句在里面if,但实际上并非如此.
这是您在Stack Overflow的文本编辑器中的源代码:
| 归档时间: |
|
| 查看次数: |
3351 次 |
| 最近记录: |