首页 > 解决方案 > 如何避免代码重复以有效使用while循环?

问题描述

pizzaq = 2.50
riceq = 7.89

rs = ['r', 'ri', 'ric', 'rice', 'R', 'Ri', 'Ric', 'Rice', 'ice', 'ic', 'rce']
bs = ['p', 'pi', 'piz', 'pizz', 'pizza', 'P', 'Pi','Piz', 'Pizz', 'Pizza']

c = input("What is your name? ")
d = input("Hello " + c + ", what you like to order today? \n Rice or Pizza? ")
e = input("How many packets? ")
q = 0
if d in rs:
    q = int(e) * riceq
    print(c + "'s order for Rice is processed and the charges are ", "Rs.", q)
    print("Please make the payment!")
elif d in bs:
    q = int(e) * pizzaq
    print(c + "'s order for Pizza is processed and the charges are ", "Rs.", q)
    print("Please make the payment!")
else:
    pass

while q == 0:
    # main program
    op1 = ['yes', 'y', 'Yes', 'Y']
    op2 = ['no', 'n', 'No', 'N']
    qu = input("We don't have "+ "'" + d + "'" + " Would you like to try again? ")
    if qu in op1:
        c = input("What is your name? ")
        d = input("Hello " + c + ", what you like to order today? \n Rice or Pizza? ")
        e = input("How many packets? ")
        if d in rs:
            q = int(e) * riceq
            print(c + "'s order for Rice is processed and the charges are ", "Rs.", q)
            print("Please make the payment!")
        elif d in bs:
            q = int(e) * pizzaq
            print(c + "'s order for Pizza is processed and the charges are ", "Rs.", q)
            print("Please make the payment!")
    elif qu in op2:
        print("Goodbye")
        break

我试图找到一种方法使循环部分更紧凑或避免在 while 循环中再次重复它。任何人都可以建议一种更好的方法来组织这个代码,我怎样才能让它成为一个在 Windows 操作系统中运行的独立程序。

标签: python

解决方案


你可以直接从循环开始,

pizzaq = 2.50
riceq = 7.89

rs = ['r', 'ri', 'ric', 'rice', 'R', 'Ri', 'Ric', 'Rice', 'ice', 'ic', 'rce']
bs = ['p', 'pi', 'piz', 'pizz', 'pizza', 'P', 'Pi','Piz', 'Pizz', 'Pizza']
op1 = ['yes', 'y', 'Yes', 'Y']
op2 = ['no', 'n', 'No', 'N']

q=0 #no need of this if using"while True:"
while q == 0: #while True: seems better
    c = input("What is your name? ")
    d = input("Hello " + c + ", what you like to order today? \n Rice or Pizza? ")
    e = input("How many packets? ")
    if d in rs:
        q = int(e) * riceq
        print(c + "'s order for Rice is processed and the charges are ", "Rs.", q)
        print("Please make the payment!")
        break
    elif d in bs:
        q = int(e) * pizzaq
        print(c + "'s order for Pizza is processed and the charges are ", "Rs.", q)
        print("Please make the payment!")
        break
    else:
        qu = input("We don't have "+ "'" + d + "'" + " Would you like to try again? ")
        if qu in op1:
            continue
        elif qu in op2:
            print("Goodbye")
            break

推荐阅读