减少 while 循环条件 - python

Reduce a while-loop condition - python

我正在尝试创建一个约束,以便“lettera”输入变量是此代码 *1 中 a 和 h 之间的字母,但我认为有更好的方法来编写循环条件.

谢谢,如果有人能帮我弄清楚如何将它改写得更小。

*1

while (lettera != 'a' and lettera != 'b' and lettera != 'c' and lettera != 'd' and lettera != 'e' and lettera != 'f' and lettera != 'g' and lettera != 'h'):
    lettera= input('Inserisci un valore lettera a-h ')
while lettera not in 'abcdefgh':

你可以使用python的ord()函数来获取字母/字符的ascii码并检查范围,a-h是97-104。

lettera= input('Inserisci un valore lettera a-h ')
ttt = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
b = all([x != lettera for x in ttt])
while b:
    print(b)

正在创建一个包含必要字母的列表(ttt)。 在列表生成器中创建一个列表,其中的值为 True 或 False。

[x != lettera for x in ttt]

我们对其应用 all 函数(如果至少有一个 False 值,它将 return False。

constraint ... is a letter of the alphabet between a and h

直接翻译成Python会是

letter_a = ...
while not 'a' <= letter_a <= 'h':
    letter_a = read("Please try again: ")

这样可以很容易地将 'h' 提高到例如'n'。如果能加个字母,@yzhang的回答更合适

flag=True
while (flag):
    lettera=input()
    ascii_val = ord(lettera)
    print(ascii_val)
    if ((ascii_val>=97) and (ascii_val<=104)):
        flag=False

您可以使用 filter 函数从输入中过滤

lettera= filter(lambda x: x not in "abcdefgh ", input('Inserisci un valore lettera a-h '))

print(*lettera)