0

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 ')
2
  • 2
    Please do not post code as images; include the code as text instead. Commented Mar 20, 2022 at 11:32
  • while lettera not in {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}: Commented Mar 20, 2022 at 11:36

6 Answers 6

4
while lettera not in 'abcdefgh':
Sign up to request clarification or add additional context in comments.

5 Comments

This doesn't work if the user enters an empty string'' (e.g. by pressing enter). To fix this, you could check if the string is not blank e.g. (lettera == '') or (lettera not in 'abcdefgh') or use @gajendragarg's method of converting the string into a list lettera not in list('abcdefgh')
@honk, I deleted my comment. But you could see my comment. 🤔
@gajendragarg I saw it just before it disappeared. Don't worry, it's definitely gone now!
@honk, got it! :)
@gajendragarg Why did you delete it tho?
0

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.

Comments

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

Comments

0

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)

Comments

0

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.

Comments

0
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)

Creating a list(ttt) of the necessary letters. Creating a list in the list generator in which the values are True or False.

[x != lettera for x in ttt]

We apply the all function to it (if there is at least one False value, it will return False.

1 Comment

Hi, can you pelase update your answer to include an explanation about how it works and how does is solve the question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.