python - 不使用 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 语句的情况下缩短它?
解决方案
你是这个意思吗:
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':
...
推荐阅读
- java - 每次用户单击加号按钮时如何添加+30?
- ios - 使用 Xamarin UITest 在 iOS 选取器中选择一个项目?
- c# - C# 获取带有超过一年附件的电子邮件
- c - 如何在 C 中使用 char 数组添加两个大的非负整数?
- jenkins - 我无法在后台启动 Jenkins(地址已在使用中)
- cluster-analysis - 如何处理插补没有意义的 NaN 值?(对于 PCA)
- c# - 如何在 MVC 中获取视图以正确引用所需的模型
- angular - Angular 7,递归对象表行
- android - React Navigation 速度极慢
- reactjs - react 最好的表格插件是什么?就像我们在 jquery 中有 DataTable