0

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
asked Sep 18, 2020 at 3:59
3
  • 1
    I suppose you want the user input to be any of A, B, C, D, F. Then change while loop to while sub1 not in ("A", "B", "C", "D", "F"): Commented Sep 18, 2020 at 4:04
  • what is invalid input in your case? Commented Sep 18, 2020 at 4:04
  • please add your invalid input Commented Sep 18, 2020 at 4:07

3 Answers 3

1

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
answered Sep 18, 2020 at 4:13
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

OP wants the user to retry in case of invalid input. So a loop will be better
OP wants an iterative solution not a if condition
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.