如何在Python中添加多个用户输入

How to add multiple user inputs in Python

我刚开始使用python,正在为一个任务开发一个程序。描述是,它是为一个电子设备,将连接到一个杂货车。当购物者开始购物时,设备将询问购物者他们的预算,这是购物者希望花费的最大金额。然后,它会要求购物者输入他们放入购物车中的每件商品的成本。每次向购物车中添加物品时,设备都会将物品的成本添加到购物车中所有物品的运行总成本或总成本中。一旦所有商品的成本超过预算,就会提醒购物者他们花了太多钱。

我已经制定了代码,并找到了我需要做的一切。但是我不能让它正确地添加用户的多个输入。理想情况下,它应该将用户的第一个输入与第二个、第三个等一起添加,并在用户输入"全部完成"时停止。

这是到目前为止我的代码。任何指点都会非常感谢!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
budget = 0
itemCost = 0
cartTotal = 0

print ("Hello! Welcome to the best grocery store ever!")
budget = int (input ("What is your budget for today?"))
itemCost = int (input ("Please tell me the cost of the most recent item your cart. Print ALL DONE to quit" ))

while itemCost !="All DONE" and cartTotal <= budget:
    itemCost = int (input ("Please tell me the cost of the most recent item your cart. Print ALL DONE to quit" )) #works
    cartTotal = itemCost + itemCost
    print ("OK, the items in your cart cost a total of", cartTotal)
    print ("Your budget is", budget," you have spent", cartTotal," you have", budget - cartTotal," left over.")
else:
    print ("You are a horrible budgeter!")


因此,我所做的是检查输入是否是一个数字(.isdigit),如果是,将其添加到一个运行总数中。您的代码不会接受"全部完成",因为它只接受整数输入,所以我也改变了这一点。最后,我把预算改成了浮动,因为这对我的钱更有意义。希望这有帮助!编辑:它不喜欢将浮动作为一种成本,但除此之外,我已经测试过它,而且它似乎可以工作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
budget = 0
itemCost = 0
cartTotal = 0

on ="TRUE"

print("Hello! Welcome to the best grocery store ever!")
budget = float(input("What is your budget for today?"))
while on =="TRUE" :
    itemCost = input("Please tell me the cost of the most recent item in your cart. Type ALL DONE to quit.")
    if itemCost =="ALL DONE" :
        on ="FALSE"

    elif itemCost.isdigit() :
        cartTotal += float(itemCost)
        if cartTotal < budget :
            print("Ok, the items in your cart cost a total of", cartTotal)
            print ("Your budget is", budget," you have spent", cartTotal," you have", budget - cartTotal," left over.")
        else :
            print("You are a horrible budgeter!")
            break
    else :
        print("Invalid entry!") #If neither a number nor ALL DONE was entered, this happens
        continue