Python - limiting input to certain characters

Joined
Jan 18, 2025
Messages
1
Reaction score
0
I am trying to limit a user's input to either the letter y or n. I am using this code. However, even when I enter n or y it still loops. I would appreciate someone letting me know where I have gone wrong! Thank you very much.

while parking_pass != 'n' or 'y':
print ("Error Contains illegal characters")
print("Would you like a free parking pass y/n?")
parking_pass = str(input())
else:
print("Your parking pass has been added to your order")
 
Joined
Jan 14, 2025
Messages
13
Reaction score
2
I am trying to limit a user's input to either the letter y or n. I am using this code. However, even when I enter n or y it still loops. I would appreciate someone letting me know where I have gone wrong! Thank you very much.

while parking_pass != 'n' or 'y':
print ("Error Contains illegal characters")
print("Would you like a free parking pass y/n?")
parking_pass = str(input())
else:
print("Your parking pass has been added to your order")
The or 'y' part is always true, which means the loop will not terminate as expected.
Check if parking_pass is not equal to both 'n' and 'y'. The condition should use the and operator instead of or.
Hope this helps.
 
Joined
Jul 4, 2023
Messages
567
Reaction score
75
BTW,
Python:
parking_pass = str(input())

'''
   when you write str(input()), you are performing an unnecessary type conversion 
   because the result of input() is already of type str.
'''
parking_pass = input()

user friendly ;)
Python:
while parking_pass not in ('y', 'Y', 'n', 'N'):

# or
    
while parking_pass.lower() not in ('y', 'n'):
 
Joined
Sep 21, 2022
Messages
215
Reaction score
32
The interesting thing to me about this error is that when read out loud, while parking_pass != 'n' or 'y' sounds right. Its the way an english speaker would phrase it.

Makes me wonder what other statements read perfectly fine, but are actually completely wrong.

The other thing is, why is there an else: in your while statement?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,167
Messages
2,570,913
Members
47,455
Latest member
Delilah Code

Latest Threads

Top