python - 如何避免代码重复以有效使用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 操作系统中运行的独立程序。
解决方案
你可以直接从循环开始,
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
推荐阅读
- java - 非常大数的幂函数
- reactjs - 如何在 React 打字稿中读取 xml 文件(toolsbox.xml)
- angular - 如何从可观察的 http 请求中返回值并将其存储在局部变量中?
- reactjs - 使用 Redux 和 react hooks 获取数据
- java - 升级硬盘后重新安装 Eclipse 的问题
- html - Why does changing the height of a 'position:sticky' element alter the scroll position on Chrome but not Safari?
- javascript - 异步事件处理程序中的 setState 更新是批处理的吗?
- css - 关于媒体屏幕的简单问题。如何同时使用宽度和高度(每个都依赖于另一个)?
- css - 如何让我的 flex div 溢出到下一行?
- c# - UWP AdaptiveGridView ItemContainerStyleSelector 不起作用