【问题标题】:while loop exiting instead of looping when criteria not met当条件不满足时,while循环退出而不是循环
【发布时间】:2022-01-13 22:11:15
【问题描述】:

我正在编写一个函数作为一个更大的整体类项目的一部分,并且我在这个循环语句中遇到了多个问题,你们中的任何人都可以告诉我它是如何不循环的,即使它不符合退出标准?我得到了我需要的东西直到循环,我试图让它要求你选择一个要添加的项目,打印出打印语句,然后重新开始,如果你选择了两次相同的项目,把它添加到购物车

print("**********ITEMS**********")
print("1................Shirts - $10")
print("2.................Pants - $20")
print("3.................Shoes - $40")
print("4.................Dress - $50")
print("Complete Purchase")
cart = []
items = 0
def addItems():
    items = int(input("please add an item to your cart: "))
    while items > 0:
        if items == 1:
            print("Shirts,{}x,${}".format(+1, +10))
            cart.count("Shirt")
            cart.append("Shirt")
            print(cart)
            return cart
        elif items == 2:
            print("Pants,{}x,${}".format(+1, +20))
            #cart.count("Pants")
            cart.append("Pants")
            return cart
        elif items == 3:
            print("Shoes,{}x,${}".format(+1, +40))
            #cart.append("Shoes")
            cart.count("Shoes")
            return cart
        elif items == 4:
            print("Dress,{}x,${}".format(+1, +50))
            #cart.append("Dress")
            cart.count("Dress")
            return cart
        elif items > 5:
            break
        #return cart
   # print(cart.count("Shirt") * 10 + cart.count("Pants") * 20 + cart.count("Shoes") * 40 + cart.count("Dress") * 50)


addItems()

这是我下面的输出

please add an item to your cart: 1
Shirts,1x,$10
['Shirt']

Process finished with exit code 0

【问题讨论】:

  • 你认为return 会做什么?
  • 一个while循环在满足条件时重复,所以它应该在不满足条件时退出。
  • 条件是循环条件,不是退出条件。
  • cart.count("Shirt") 什么都不做。它会返回计数,但您永远不会对该结果执行任何操作。
  • 无论如何,解决你的主要问题就是去掉所有的return cart 行。

标签: python python-3.x list while-loop


【解决方案1】:

您应该从 if-elif 阶梯中删除“返回购物车”并将其添加到 while 循环之外。除了前一个,您还可以在 while 循环结束时在 while 循环中获取用户的输入。

def addItems():
    items = int(input("please add an item to your cart: "))
    while items > 0:
        if items == 1:
            print("Shirts,{}x,${}".format(+1, +10))
            cart.count("Shirt")
            cart.append("Shirt")
            print(cart)
        elif items == 2:
            print("Pants,{}x,${}".format(+1, +20))
            #cart.count("Pants")
            cart.append("Pants")
        elif items == 3:
            print("Shoes,{}x,${}".format(+1, +40))
            #cart.append("Shoes")
            cart.count("Shoes")
        elif items == 4:
            print("Dress,{}x,${}".format(+1, +50))
            #cart.append("Dress")
            cart.count("Dress")
        elif items > 5:
            break
        items = int(input("please add an item to your cart: "))
    return cart    

【讨论】:

    猜你喜欢
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-18
    • 1970-01-01
    • 2022-01-25
    • 2019-01-29
    • 2013-11-22
    相关资源
    最近更新 更多