我正在学习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()
如何修复我的代码,以便在输入负价格时打印“错误”消息?
当用户向
price
输入提交负值时,您的代码将运行 if price != 0:
。
为了更轻松地弄清楚发生了什么,我在 python shell 中运行了以下代码:
>>> 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
那么 only code1
将运行。如果不是 cond2
将被检查,如果为 True 那么 only code2
将 tun,因此单词“else”(elif 与 else if 相同)
在你的问题中:
修改代码,使负数改为给出错误消息 (但不要结束循环)提示:elif 是你的朋友。
在您的代码中,如果价格为负,则
price != 0
为 True。
所以因为使用 elif,only 这会运行:
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()
def checkout():
total = 0
count = 0
moreItems = True
while moreItems:
price = float(input('Enter price of item (0 when done): '))
if price < 0:
price = False
elif price != 0:
count = count + 1
total = total + price
print('Subtotal: $', total)
else:
moreItems = False
average = total / count
print('Total items:', count)
print('Total $', total)
print('Average price per item: $', average)
结帐()重新