我正在学习Python,并试图编辑有以下错误的代码:
如果您输入一个负数,它将被添加到总数和计数。修改代码,使负数给出错误消息(但不结束循环)提示:elif是你的朋友。
def checkout():
total = 0
count = 0
moreItems = True
while moreItems:
price = float(input('Enter price of item (0 when done): '))
if price != 0:
count = count + 1
total = total + price
print('Subtotal: $', total)
# This `elif` block is the code I edited
elif price<0:
print('Error')
price= False
else:
moreItems = False
average = total / count
print('Total items:', count)
print('Total $', total)
print('Average price per item: $', average)
checkout()
我如何修复我的代码,使其打印"Error"输入负价格时的消息?
当用户向price
输入提交一个负值时,您的代码将运行if price != 0:
。
>>> total = 0
>>> count = 0
>>> moreItems = True
>>> price = float(input('Enter price of item (0 when done): '))
Enter price of item (0 when done): -5
>>> price != 0
True
你可能想要的是:
if price > 0:
...
elif price < 0:
print("Error")
你必须改变这一行:
if price != 0:
:
if price > 0:
在if else
或if elif
语句中,else
或elif
内部的代码只有在if
的条件不满足时才会执行。
,
if cond1:
code1
elif cond2:
code2
else:
code3
如果cond1
是true
,那么只能code1
将运行。如果不是,cond2
将被检查,如果为True,则仅code2
将转,因此单词";else"(elif与else if相同)
在你的问题中:
修改代码,使负数给出错误消息(但不要结束循环)提示:elif是你的朋友。
在你的代码中,如果price是负的,那么price != 0
是True。因为使用elif,只能这将运行:
count = count + 1
total = total + price
print('Subtotal: $', total)
代码修复:
def checkout():
total = 0
count = 0
moreItems = True
while moreItems:
price = float(input('Enter price of item (0 when done): '))
**if price > 0:
count = count + 1
total = total + price
print('Subtotal: $', total)
elif price < 0:
print('Error')
price= False**
else:
moreItems = False
average = total / count
print('Total items:', count)
print('Total $', total)
print('Average price per item: $', average)
checkout()
这是你所期望的吗?我只做了一些小改动。
def checkout():
total = 0
count = 0
moreItems = True
while moreItems:
price = float(input('Enter price of item (0 when done): '))
if price > 0:
count += 1
total += price
print(f'Subtotal: $ {total}')
elif price < 0:
print('**Error**, Please enter a positive value')
else:
moreItems = False
average = total / count
print(f'Total items: {count}')
print(f'Total $ {total}')
print(f'Average price per item: $ {average}')
checkout()