尝试使用循环并添加到variab

2024-06-01 01:48:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个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等等

我只需要一点帮助,关于如何将多个值相加,然后维护我所在的循环的总值。你知道吗

如果有人能指点我,我想知道一个函数或循环的例子,或者告诉我该去哪里,那太好了!你知道吗


Tags: or用户loopforinputtotal成本enter
3条回答
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()

注意

试着把这个例子转化成你的问题

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))

您可以尝试使用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)

相关问题 更多 >