【问题标题】:The input taken in by my program is wrong(logic error)我的程序输入错误(逻辑错误)
【发布时间】:2020-06-14 06:16:17
【问题描述】:

这是我的代码:

cart = ['S/n'," "*10, 'Items', " " * 15, "Quantity", " " * 8, "Unit Price", " " * 6, "Price"]
total_pricee = 0
pricee = 0
count=1
def invalid_input(Quantitiy):
    while Quantitiy > '5' or Quantitiy < '1':
        Quantitiy = input("Please key in a valid quantity(Between 1 to 4):")
        if Quantitiy < '5' and Quantitiy > '1':
            New_Quan=Quantitiy
            break
    while not Quantitiy.isdigit():
        Quantitiy = input('Invalid input.Please enter a valid input:')
        while Quantitiy.isdecimal() == False:
            break
def add_to_cart(name, Quantity, price):
    global total_pricee, pricee,count
    cart.append('\n')
    cart.append('{:<10s}'.format(str(count)+'.'))
    cart.append('{:^10s}'.format(name))
    cart.append('{:^30s}'.format(Quantity))
    cart.append('{:^10s}'.format('$' + '{:.2f}'.format(float(price))))
    pricee = '{:.2f}'.format(float(Quantity) * price)
    cart.append('{:^23s}'.format('$' + str(pricee)))
    total_pricee += float(pricee)
    count = count +1
while True:
    print('[1] Water')
    print('[2] rice')
    print('[3] ice')
    print('[0] View Cart')
    opt = input("Select option:")
    if opt > '3' or opt < '0':
        print("Select valid option!")
    if opt == '3':
        qunt = input("How many would you like?")
        invalid_input(qunt)
        nam3 = "Ice"
        add_to_cart(nam3, qunt, 2)
    if opt == '1':
        qunt2 = input("How many would you like?")
        invalid_input(qunt2)
        nam2 = "Water"
        add_to_cart(nam2, qunt2, 3)
    if opt == '2':
        qunt1 = input("How many would you like?")
        invalid_input(qunt1)
        nam1 = "Rice"
        add_to_cart(nam1, qunt1, 5)
    if opt == "0":
        print(*cart)
        print("Total price until now:", "$" + '{:.2f}'.format(total_pricee))
        print('Would you like to check out?')
        print('[1] Yes')
        print('[2] No')
        checkout=input("Please select an option:")
        if checkout=='1':
            print('You have bought',count,'items')
            print("Please pay""$" + '{:.2f}'.format(total_pricee))
            print('Thank you for shopping with us!')
            exit()

我面临的问题是当用户输入的数量超过5时(参考invalid_input函数),程序要求它提供小于6的数量。但是,当我应用add_to_cart时,它取用户输入的原始值(大于5)。

[1] Water
[2] rice
[3] ice
[0] View Cart
Select option:3
How many would you like?6
Please key in a valid quantity(Between 1 to 4):5
[1] Water
[2] rice
[3] ice
[0] View Cart
Select option:0
S/n            Items                 Quantity          Unit Price        Price 
 1.            Ice                   6                  $2.00            $12.00 

您看到它如何要求用户输入有效数量(5)但是add_to_cart所取的数量是初始值(6)。我希望从有效数量中显示数量。请帮助!谢谢!

【问题讨论】:

    标签: python python-3.x list logic


    【解决方案1】:

    您只需将&gt; 替换为&gt;= 即可避免逻辑错误,

    def invalid_input(Quantitiy):
        #look the Qunatity>=5
        while Quantitiy >= '5' or Quantitiy < '1':
            Quantitiy = input("Please key in a valid quantity(Between 1 to 4):")
            if Quantitiy < '5' and Quantitiy > '1':
                New_Quan=Quantitiy
                break
    

    如果您只给出Qunatity&gt; 5 并输入5 会发生什么情况是条件变为假。因为5 本身不大于5。

    除了当您要求用户Please key in a valid quantity(Between 1 to 4) 时出现的这个错误之外,您并没有将其返回到您的主模块。这是您代码的修改版本,

    #replaced cart with str1
    str1="S/n\tItems\t  Quantity\tUnit Price\t\tPrice"
    total_pricee = 0
    pricee = 0
    count=1
    def invalid_input(Quantitiy):
        while Quantitiy >= '5' or Quantitiy < '1':
            Quantitiy = input("Please key in a valid quantity(Between 1 to 4):")
            if Quantitiy < '5' and Quantitiy > '1':
                New_Quan=Quantitiy
    
                #returned from here
                return Quantitiy
    
                break
        while not Quantitiy.isdigit():
            Quantitiy = input('Invalid input.Please enter a valid input:')
            while Quantitiy.isdecimal() == False:
                break
        #added the return here
        return Quantitiy
    
    def add_to_cart(name, Quantity, price):
        global total_pricee, pricee,count,str1
    
        #replaced each cart statement with str1
        str1+="\n"
        str1+=str(count)+'.'+'\t'
        str1+=str(name)+'\t\t'
        str1+=str(Quantity)+'\t\t'
        str1+=str(price)+'\t\t'
    
        pricee = '{:.2f}'.format(float(Quantity) * price)
        pricee
    
        str1+=str(pricee)
        total_pricee += float(pricee)
        count = count +1
    while True:
        print('[1] Water')
        print('[2] rice')
        print('[3] ice')
        print('[0] View Cart')
        opt = input("Select option:")
        if opt > '3' or opt < '0':
            print("Select valid option!")
        if opt == '3':
            qunt = input("How many would you like?")
    
            #getting the returned value to quant
            qunt =invalid_input(qunt)
            nam3 = "Ice"
            add_to_cart(nam3, qunt, 2)
        if opt == '1':
            qunt2 = input("How many would you like?")
            #getting the returned value to quant1
            qunt2=invalid_input(qunt2)
            nam2 = "Water"
            add_to_cart(nam2, qunt2, 3)
        if opt == '2':
            qunt1 = input("How many would you like?")
    
            #getting the returned value to quant1
            qunt1=invalid_input(qunt1)
            nam1 = "Rice"
            add_to_cart(nam1, qunt1, 5)
        if opt == "0":
    
            print(str1)
            print("Total price until now:", "$" + '{:.2f}'.format(total_pricee))
            print('Would you like to check out?')
            print('[1] Yes')
            print('[2] No')
            checkout=input("Please select an option:")
            if checkout=='1':
                print('You have bought',count,'items')
                print("Please pay""$" + '{:.2f}'.format(total_pricee))
                print('Thank you for shopping with us!')
                exit()
    

    希望对你有帮助!

    【讨论】:

    • 并非如此,手头的问题是 add_to_cart 函数不将输出(在本例中为 Quantity)作为其输入。相反,它采用用户的初始输入(大于5)并执行操作。感谢您的提示
    • 好的,我明白了!我已经编辑了我的答案看看它
    • 嗨,仍然显示错误消息:第 48 行,在 qunt1=invalid_input(qunt1) NameError: name 'qunt1' is not defined and:line 23, in add_to_cart cart.append('{ :^30s}'.format(Quantity)) TypeError: 不支持的格式字符串传递给 NoneType.__format__ 和第 51 行,在 add_to_cart(nam1, qunt1, 5)
    • 我已经编辑了我的答案,并且每次使用字符串格式时都会出现格式错误,只需删除这些格式并使用简单的代码
    • 对不起,我的意思是当数量是两位数时
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 2017-01-20
    相关资源
    最近更新 更多