I'm trying to create a constraint so that the "lettera" input variable is a letter of the alphabet between a and h on this code *1 but I think there's a better way to write the condition for the loop.
Thanks if someone could help me figuring out how re-write it smaller.
*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 ')
CodePudding user response:
while lettera not in 'abcdefgh':
CodePudding user response:
you could use python's ord() function to get the ascii code of a letter / character and check against a range, a-h are 97-104.
CodePudding user response:
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 == False:
print(b)
CodePudding user response:
constraint ... is a letter of the alphabet between a and h
Direct translation to Python would be
letter_a = ...
while not 'a' <= letter_a <= 'h':
letter_a = read("Please try again: ")
This would make it easy to raise 'h'
to e.g. 'n'
. If any letter could be added, the answer from @yzhang is more suitable.
CodePudding user response:
flag=True
while (flag):
lettera=input()
ascii_val = ord(lettera)
print(ascii_val)
if ((ascii_val>=97) and (ascii_val<=104)):
flag=False
CodePudding user response:
You can use filter
function to filter from input
lettera= filter(lambda x: x not in "abcdefgh ", input('Inserisci un valore lettera a-h '))
print(*lettera)