我想创建一个while循环来提示用户是否想要输入生活费用。用户输入'y'表示是,循环将继续。
我这个循环我希望将所有输入的生活费用加起来,一旦循环结束,就存储到total_living
中的总金额。
示例
l_cost = input('Enter living cost? y or n ')
while l_cost != 'n' (loop for living cost)
totat_living = (keeps adding until I say all done
l_cost = input('Enter living cost? y or n ')
其他while和for循环用于不同的场景
total_exp = total_living + total_credit + total_debt
等
关于如何添加多个值然后保持我所在循环的总值,我只需要一些帮助。
如果有人能指出一个类似的功能或循环的例子,或者告诉我在哪里看起来会很棒!
答案 0 :(得分:0)
total_cost = 0.0
prompt = 'Enter a living cost? y or n: '
answer = input(prompt)
while answer.lower() != 'n':
cost = input('Enter your cost: ')
total_cost = total_cost + float(cost)
answer = input(prompt)
print('Total cost is $' + str(total_cost))
答案 1 :(得分:0)
您可以尝试使用while
,如下所示:
flag = input ("wish to enter cost; y or n" )
total=0
While flag != 'n':.
cost = int(input ("enter cost: "))
total = total + cost
flag = input("more ?? Y or n")
print(total)
答案 2 :(得分:0)
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)
else:
moreItems = False
average = total / count
print('Total items:', count)
print('Total $', total)
print('Average price per item: $', average)
checkout()