I am very new to Python (started 3 days ago) and I am trying to make a loop where whenever the user inputs an invalid input, the code will respond and tell them to reenter their response but I cannot seem to get it.
while sub1!= "A,B,C,D,F":
print("Invalid Entry,try again:")
James Z
12.3k10 gold badges28 silver badges50 bronze badges
3 Answers 3
The user_inputs list and the for loop is to simulate different user inputs.
user_inputs = ['G','H','I','A','C']
for i in range(len(user_inputs)):
# if user input is not in the list print valid (or do whatever you want to do)
while user_inputs[i] not in ['A','B','C','D','F']:
i+=1
print('valid input')
# if user input is in the list, then print invalid input... and break out of the loop
else:
print('invalid input')
break
Sign up to request clarification or add additional context in comments.
Comments
You can use if also to check condition
sub1 = "Z"
if not sub1 in ['A','B','C','D','F']:
..print("Invalid Entry,try again:")
answered Sep 18, 2020 at 4:04
Krishna Singhal
6616 silver badges9 bronze badges
using while loop and try-except:
while True:
try:
user_input = input()
if user_input in "A, B, C, D, F".split(','):
print("Valid Entry")
break
else:
print("Invalid entry please try again")
except ValueError:
print("Provide A or B or C or D or F")
continue
answered Sep 18, 2020 at 4:22
Tasnuva Leeya
2,8351 gold badge17 silver badges24 bronze badges
Comments
lang-py
A,B,C,D,F. Then change while loop towhile sub1 not in ("A", "B", "C", "D", "F"):