1

I'm trying to create a login panel in the command line using python. so if the user does not insert any username, the cursor should remain on the same line but I should get an error on the next line.

I tried:

while True:
  input1  = input('username: ')
  if len(input1) == 0:
    print("Sorry, your response was not loud enough.")
    continue

  input2 = stdiomask.getpass('pasword: ')
  if len(input2) == 0:
    print("Sorry, your response was not loud enough.")
    continue

  input3 = stdiomask.getpass('cnf password: ')
  if len(input3) == 0:
    print("Sorry, your response was not loud enough.")
    continue
  

But since I'm using while loop so if I'm not inserting password I have to insert username again which I don't want also if I don't insert a username, the username is prompted on next line after showing error. so Is there any way to handle these situations?

something like this:

F:\new_file\file> python main.py
? username: # cursor remains here until a username is inserted
> Invalid input # error is prmpted on next line
1
  • try to use recursion, posted sample code Commented Aug 26, 2020 at 8:38

1 Answer 1

1

Try recursion to get input and check if valid. If it is valid then return input else call the same function again

def get_input(name, reset=0):
  if reset:
    print(end=f"> Invalid {name}\r", flush=True)
    print(f"\b", end=f"\r{name}: ", flush=True)
  else:
    print(f"{name}: \b", end=f"\r{name}: ", flush=True)
   
  inp = input()
  if len(inp)==0:
    inp = get_input(name, reset=1)
  return inp
input1=get_input('username')
input2=get_input('pasword')
input3=get_input('cnf password')
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, It worked but Is it possible to write input on the same line, i.e if no input is passed, the error is popped on the next line but the cursor remains at the same line and waits for the user to write input.
added reset logic in answer. check correct if you find it correct
Still coming on next line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.