I am trying to create a function that receives input from a user, re-prompts until one character is entered. Strip() is used to removed whitespace so only characters are counted.
Here is my current code:
def inputSomething(prompt, errorMessage = 'Atleast one character must be used'):
while True:
value = (prompt)
Response = value.strip()
if len(Response) >=1:
print ('Valid')
else:
print(errorMessage)
continue
inputSomething(input('Enter str: '))
The problem I'm having is with the loop. Right now it loops the result infinitely. Should I not be using if else?
The problem is that the input
is outside the loop:
import sys
def inputSomething(prompt, errorMessage = 'Atleast one character must be used'):
while True:
value = input(prompt)
Response = value.strip()
if Response:
print ('Valid')
return Response
else:
print(errorMessage, file=sys.stderr)
something = inputSomething('Enter str: ')
Note that an empty string equates to False
.
I was confused with recursion, because of the indentation used in your question.