不确定我的标题是否正确,这是我的第一篇文章,请原谅我,如果在其他地方得到解答,但我确实尝试研究它并试图找到特定于我的问题的答案。
我是Python新手,我正在构建我的第一个程序,一切正常,除了代码部分要求用户知道他们的名字长度。
我正在尝试为"是"添加多个答案。而对于" no"因此,如果用户输入的内容类似于"是的"或" nope"它仍然会接受答案。我为可能的答案建立了列表。然而,它只是跳过我的if语句,我的elif声明,并且直接进入我的其他声明。我也试过不使用列表,但"和"还有"或"没有运气。
# prints the length of name if user desires, if not it goes onto ask age
print('Would you like to know the length of your name?')
answer = input()
affirmative = ['yes', 'Yes', 'yeah', 'Yeah', 'yup', 'Yup', 'y', 'Y', 'yea',
'Yea']
negative = ['No', 'no', 'Nope', 'nope', 'N', 'n', 'Nah', 'nah']
if answer == affirmative:
print('The length of your name is ' + str(int(len(myName))))
elif answer == negative:
print('Ok! Thats fine! I didn\'t want to tell you anyway!')
else:
print('Ok then.....next question')
我使用的是最新版本的Python。提前谢谢你,如果在其他地方得到了回答,那就再说一遍。
答案 0 :(得分:0)
以下是一些可以帮助您的建议。
# prints the length of name if user desires, if not it goes onto ask age
answer = input('Would you like to know the length of your name?')
# Rather than printing, input can take the string to print (helps with figuring out what the input is used for)
affirmative = ['yes', 'Yes', 'yeah', 'Yeah', 'yup', 'Yup', 'y', 'Y', 'yea',
'Yea']
negative = ['No', 'no', 'Nope', 'nope', 'N', 'n', 'Nah', 'nah']
if answer in affirmative:
print('The length of your name is ' + str(int(len(myName))))
elif answer in negative:
print('Ok! Thats fine! I didn\'t want to tell you anyway!')
else:
print('Ok then.....next question')
通过使用in
关键字,您可以检查您的字符串是否在列表中。
答案 1 :(得分:0)
# prints the length of name if user desires, if not it goes onto ask age
# prints the length of name if user desires, if not it goes onto
ask age
answer = input('Would you like to know the length of your name?')
# Rather than printing, input can take the string to print (helps with figuring
out what the input is used for)
affirmative = ['yes', 'Yes', 'yeah', 'Yeah', 'yup', 'Yup', 'y', 'Y', 'yea',
'Yea']
negative = ['No', 'no', 'Nope', 'nope', 'N', 'n', 'Nah', 'nah']
if answer in affirmative:
print('The length of your name is ' + str(int(len(myName))))
elif answer in negative:
print('Ok! Thats fine! I didn\'t want to tell you anyway!')
else:
print('Ok then.....next question')