python-3.x - 如何验证输入
问题描述
你好,我是使用 python 编程的新手,我已经安排了这段代码,这样一个 while 循环可以在程序开始时验证 Gamble 变量,并在重新评估上述变量时。我怎样才能使程序按原样运行,但又不必编写两次?
def gamBling(Gamble):
while Gamble == 'yes' or Gamble == 'Yes' or Gamble == 'y' or Gamble =='Y':
betTing()
Gamble = input('Do you wish to play again? ')
while Gamble != 'yes' and Gamble != 'Yes' and Gamble != 'y' and Gamble != 'Y' and Gamble != 'No' and Gamble != 'no' and Gamble != 'N' and Gamble != 'n':
Gamble = input('Please anwser in either yes or no? ')
if Gamble == 'No' or Gamble == 'N' or Gamble == 'n' or Gamble == 'no':
print('okay, goodbye')
exit()
print('Any bet you make will be doubled if your number is higher than or equal to 5. Want to play? ' + '(Yes or No)')
Gamble = input()
while Gamble != 'yes' and Gamble != 'Yes' and Gamble != 'y' and Gamble != 'Y' and Gamble != 'No' and Gamble != 'no' and Gamble != 'N' and Gamble != 'n':
Gamble = input('Please anwser in either yes or no? ')
gamBling(Gamble)
我希望能够以现在运行的方式运行程序,但不必重复 while 循环,如果可以的话。
解决方案
您可以定义一个单独的函数进行验证,并在任何需要的地方使用它
def validate(Gamble):
while Gamble != 'yes' and Gamble != 'Yes' and Gamble != 'y' and Gamble != 'Y' and Gamble != 'No' and Gamble != 'no' and Gamble != 'N' and Gamble != 'n':
Gamble = input('Please anwser in either yes or no? ')
return Gamble
然后您的代码将如下所示:
def gamBling(Gamble):
while Gamble == 'yes' or Gamble == 'Yes' or Gamble == 'y' or Gamble =='Y':
betTing()
Gamble = input('Do you wish to play again? ')
Gamble = validate(Gamble)
if Gamble == 'No' or Gamble == 'N' or Gamble == 'n' or Gamble == 'no':
print('okay, goodbye')
exit()
print('Any bet you make will be doubled if your number is higher than or equal to 5. Want to play? ' + '(Yes or No)')
Gamble = input()
Gamble = validate(Gamble)
gamBling(Gamble)
推荐阅读
- spring - 在应用程序中禁用谷歌登录的弹簧安全性
- typescript - TypeScript - 非数组对象的定义/接口
- mysql - 错误 1045 使用密码是并从 wampserver 恢复数据
- c# - 编码的 UI:使用数据源而不登录网站
- android - Vuforia 在 Android Studio 中用 3D 模型替换茶壶
- c++ - 即使在我为我的应用程序授予管理员权限后,也无法从 Windows 系统复制目录
- sharepoint - Sharepoint - 工作流程不会从另一个列表开始
- java - Java 8 流。将两个参数传递给在 forEach 中调用的方法
- android - react-native-track-player 通知区域播放器 UI
- autodesk-forge - 混凝土对象内钢筋的对象选择错误