Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 寻找单词之间的差异_Python_Python 3.x - Fatal编程技术网

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-else语句,如果没有八个输入弹出,我就无法得到if-elif语句。我知道这是一个简单的问题,但我对python还是新手

我的代码:

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(),“以其他内容开头”)