0
The user can only input a string nothing else(no dots or numbers etc).How to do that?
The other issue is when a user types in a wrong input he should be given a new chance to try again AND it shouldnt count as an attempt inside the for loop. Meaning a user can type in an infinite number of wrong inputs(a number for example) but it will only count as an attempt when he types in the right way of input(meaning a string). If he for example types in 5 different names,the loop would end. https://code.sololearn.com/c7PoEd2A8I1X/?ref=app
9 Answers
+ 1
Create a helper function to check your validation of the input(). You can then use a while loop inside the for loop that will repeat the input() ability until you receive a valid input. Just make a variable before the while loop and give it an initial value that isn't valid, like None or ''. Then pass the value to the helper function to check if it is valid.
def valid_input(inp):
... # perform checks
return False # not valid
return True # valid
for _ in range(5):
inp = None
while not valid_input(inp):
inp = input()
+ 1
Lenoname
You may not need the try-except, unless this is some challenge, module project or practice requiring it. In which case, please be more specific with your question and give these details.
By checks, I mean checking to see if the input string value contains what is required or has some character that should not be included etc. For instance if the value is an empty string, has punctuation when it shouldn't, contains numbers when it shouldn't, is None, does or doesn't match a specific regex pattern, etc. Whatever your qualifiers are for a valid string.
+ 1
Ya, you misunderstood me. None is a type by itself in python. You wouldn't get None as a return value from the input() function anyway, as it is always a str type until converted. I was just using that as an example, because it is not uncommon to set a variable name to None as an initial value, as it is in the sample I provided above.
0
By string i mean only letters
0
ChaoticDawg do i put the try except under valid_input also?
0
ChaoticDawg what do u mean by checks?
0
What is this for a challenge?
0
ChaoticDawg if numbers are None then why doesnt this result in âwrong try againâ?i typed in a number as input
a = input("input: ")
if a == None :
print("wrong try again")
0
ChaoticDawg or did i misunderstand what u said?