Python 寻找单词之间的差异
我试图让我的代码能够区分以不同字母开头的八个单词,我只能得到一个if-else语句,如果没有八个输入弹出,我就无法得到if-elif语句。我知道这是一个简单的问题,但我对python还是新手 我的代码:Python 寻找单词之间的差异,python,python-3.x,Python,Python 3.x,我试图让我的代码能够区分以不同字母开头的八个单词,我只能得到一个if-else语句,如果没有八个输入弹出,我就无法得到if-elif语句。我知道这是一个简单的问题,但我对python还是新手 我的代码: if input().lower().startswith('z'): print('yes') elif input().lower().startswith('x'): print('no') 将输入存储在变量中,然后测试该变量 text = input().lower()
if input().lower().startswith('z'):
print('yes')
elif input().lower().startswith('x'):
print('no')
将输入存储在变量中,然后测试该变量
text = input().lower()
if text.startswith("z"):
# etc
将输入存储在变量中,然后测试该变量
text = input().lower()
if text.startswith("z"):
# etc
你不应该每次都那样调用
input()
。每次调用input()
都会向用户请求更多文本。在开始时只执行一次,并将其保存到某个变量中,然后进行比较
input_str = input().lower()
if input_str.startswith("z"):
print "yes"
elif input_str.startswith("x"):
print "no"
你不应该每次都那样调用
input()
。每次调用input()
都会向用户请求更多文本。在开始时只执行一次,并将其保存到某个变量中,然后进行比较
input_str = input().lower()
if input_str.startswith("z"):
print "yes"
elif input_str.startswith("x"):
print "no"
扩展@Padraic_Cunningham的评论: 不必写出多个
if
elif
语句,您可以创建一个字典来存储该字母的起始字母(键和期望输出(值)
letter_dict = {"a": "starts with an a",
"h": "starts with an h",
...
}
>>> word = input()
>>> Hello
>>> letter_dict[word[0].lower()]
>>> 'starts with an h'
扩展@Padraic_Cunningham的评论:
不必写出多个if
elif
语句,您可以创建一个字典来存储该字母的起始字母(键和期望输出(值)
letter_dict = {"a": "starts with an a",
"h": "starts with an h",
...
}
>>> word = input()
>>> Hello
>>> letter_dict[word[0].lower()]
>>> 'starts with an h'
输入
需要一些()
。我会自己编辑,但是没有足够的字符。input
需要一些()
。我会自己编辑它,但没有足够的字符。你可以把你的字母放在一个dict中,以要求的输出作为值,以避免8 if/elifs。你可以把你的字母放在一个dict中,以要求的输出作为值,以避免8 if/elifs。使用input()可能更好。lower()
无需重复调用.lower
每次检查可能最好使用input().lower()
无需重复调用.lower
每次检查+1,因为我喜欢这种方法。。。但最好是使用字母dict.get(单词[0].lower(),“以其他东西开头”)
+1,因为我喜欢这种方法。。。但最好是使用letter_dict.get(word[0].lower(),“以其他内容开头”)