首页 > 解决方案 > 不使用 break 缩短

问题描述

fun = input("Enter 1 or 2:")
if fun == '1':
   print("Programming is fun!")
elif fun == '2':
   print("You're getting the hang of this.")
elif fun == 'bye':
  print("Bye, bye.")
else:
    print("Sorry that isn't a 1 or 2.")
while fun != 'bye':
    fun = input("Enter 1 or 2:")
    if fun == '1':
        print("Programming is fun!")
    elif fun == '2':
        print("You're getting the hang of this.")
    elif fun == 'bye':
        print("Bye, bye.")
    else:
        print("Sorry that isn't a 1 or 2.")

所以基本上正如标题所说,我想知道是否有办法在不使用 break 语句的情况下缩短它?

标签: pythonpython-3.x

解决方案


你是这个意思吗:

fun = ""
while fun != 'bye':
    fun = input("Enter 1 or 2:")
    if fun == '1':
        print("Programming is fun!")
    elif fun == '2':
        print("You're getting the hang of this.")
    elif fun == 'bye':
        print("Bye, bye.")
    else:
        print("Sorry that isn't a 1 or 2.")

当然,使用 Python 3.8 中新的“海象”运算符,您可以使用:

while (fun := input("Enter 1 or 2:")) != 'bye':
    ...

推荐阅读