检测输入错误然后在 Python 上打印该错误
detect an input error to then print that error on Python
我的问题很简单,我会要求用户给我一个输入(我使用的是 2.7 python),但我想检测用户是否给我一个错误的信息。例如,如果让他写出太阳系的第一颗行星,而他写下了地球(不是),我想给出一个说明错误的打印件(他需要输入 "mercury")。
示例:
planet = input ('please enter the first planet of the solar system')
print ('your planet is '), planet
如果这个人,我只想打印错误,比如说进入地球或者甚至不是行星,比如床或房子。
只需使用 if 语句检查输入字符串。
planet = input ('Please enter the first planet of the solar system: ')
if (planet != 'Mercury'):
print("Incorrect Input")
else:
print ('your planet is '), planet
如果您担心输入的大小写(例如:mercury 或 Mercury),可以先将输入字符串转换为小写再检查。
赞:
lower_planet = planet.lower()
或者您可以在用户提示中提及限制。
我的问题很简单,我会要求用户给我一个输入(我使用的是 2.7 python),但我想检测用户是否给我一个错误的信息。例如,如果让他写出太阳系的第一颗行星,而他写下了地球(不是),我想给出一个说明错误的打印件(他需要输入 "mercury")。
示例:
planet = input ('please enter the first planet of the solar system')
print ('your planet is '), planet
如果这个人,我只想打印错误,比如说进入地球或者甚至不是行星,比如床或房子。
只需使用 if 语句检查输入字符串。
planet = input ('Please enter the first planet of the solar system: ')
if (planet != 'Mercury'):
print("Incorrect Input")
else:
print ('your planet is '), planet
如果您担心输入的大小写(例如:mercury 或 Mercury),可以先将输入字符串转换为小写再检查。
赞: lower_planet = planet.lower()
或者您可以在用户提示中提及限制。