错误的“如果”条件输出

时间:2018-12-12 22:42:43

标签: python python-3.x

想要一些帮助!

The task I recieved :

我写的代码:

guessed_letter = input('Guess a letter: ')
if len(guessed_letter) == 1 and guessed_letter in string.ascii_lowercase[:26]:
    print(guessed_letter.lower())
elif len(guessed_letter) > 1 and guessed_letter in string.ascii_lowercase[:26]:
    print("Error 1")
elif guessed_letter == 1 and guessed_letter != string.ascii_lowercase[:26]:
    print("Error 2")
elif len(guessed_letter) != 1 and guessed_letter not in string.ascii_lowercase[:26]:
    print("Error 3")

我的问题是,当我尝试输入“ aa”时,输出出现错误3而不是错误1。

我该如何进行?

1 个答案:

答案 0 :(得分:1)

尝试一下:

guessed_letter = input('Guess a letter: ')
if len(guessed_letter) == 1 and guessed_letter in string.ascii_lowercase[:26]:
    print(guessed_letter.lower())
elif len(guessed_letter) > 1:
    for letter in guessed_letter:
        if letter not in string.ascii_lowercase[:26]:
            print('Error 3')
        else:
            print('Error 1')
elif guessed_letter == 1 and guessed_letter not in string.ascii_lowercase[:26]:
    print('Error 2')

另一个没有循环的解决方案:

guessed_letter = input('Guess a letter: ')
if len(guessed_letter) == 1 and guessed_letter in string.ascii_lowercase[:26]:
    print(guessed_letter.lower())
elif len(guessed_letter) > 1:
    new_strings = list(string.ascii_lowercase[:26])
    new_strings.extend(list(set(list(guessed_letter))))
    new_strings = list(set(new_strings))
    if len(list(string.ascii_lowercase[:26])) < len(new_strings):
        print('Error 3')
    else:
        print('Error 1')
elif guessed_letter == 1 and guessed_letter not in string.ascii_lowercase[:26]:
    print('Error 2')