寻找单词之间的差异

时间:2014-07-22 22:10:44

标签: python python-3.x

我正在尝试让我的代码区分以不同字母开头的八个单词,而我能得到的是一个if-else语句,我无法在没有八个输入的情况下获得if-elif语句弹出。我知道这是一个类似的问题,但我是python的新手。

我的代码:

if input().lower().startswith('z'):
    print('yes')
elif input().lower().startswith('x'):
    print('no')

3 个答案:

答案 0 :(得分:4)

将输入存储在变量中,然后测试该变量

text = input().lower()

if text.startswith("z"):
     # etc

答案 1 :(得分:3)

你不应该每次都致电input()。每次调用input()都会向用户请求更多文字。在开始时只做一次并将其保存到某个变量,然后进行比较。

input_str = input().lower()
if input_str.startswith("z"):
  print "yes"
elif input_str.startswith("x"):
  print "no"

答案 2 :(得分:1)

扩展@ Padraic_Cunn​​ingham的评论:

您可以创建一个存储起始字母(if)和期望输出(elif)的字典,而不是写出多个key value语句。那封信。

letter_dict = {"a": "starts with an a",
               "h": "starts with an h",
                ...
               }

>>> word = input()
>>> Hello
>>> letter_dict[word[0].lower()]
>>> 'starts with an h'