Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # for http://stackoverflow.com/q/38299137/1431750
- user_input = raw_input('Please provide your name:')
- while user_input != "Q" and user_input != "q":
- if user_input == "":
- print "Your input is required"
- user_input = raw_input('Please provide your name:')
- else:
- print "Youre name has been recorded:", user_input
- break
- In action:
- >>> user_input = raw_input('Please provide your name:')
- Please provide your name:
- >>> while user_input != "Q" and user_input != "q":
- ... if user_input == "":
- ... print "Your input is required"
- ... user_input = raw_input('Please provide your name:')
- ... else:
- ... print "Youre name has been recorded:", user_input
- ... break
- ...
- Your input is required
- Please provide your name:
- Your input is required
- Please provide your name:
- Your input is required
- Please provide your name:A
- Youre name has been recorded: A
- >>> # it has exit the program
- ...
- >>> user_input = '' # reset `user_input` and run the while loop again
- >>> while user_input != "Q" and user_input != "q":
- ... if user_input == "":
- ... print "Your input is required"
- ... user_input = raw_input('Please provide your name:')
- ... else:
- ... print "Youre name has been recorded:", user_input
- ... break
- ...
- Your input is required
- Please provide your name:
- Your input is required
- Please provide your name:q
- >>>
- # Ideally, what you could do instead is:
- while True:
- user_input = raw_input('Please provide your name:')
- if user_input == "Q" or user_input == "q":
- break
- elif user_input == "":
- print "Your input is required"
- continue # unnecessary but clearer since there's no other code which will run for this block
- else:
- print "Youre name has been recorded:", user_input
- break
- # And the shortest way to do it with clarity:
- while True:
- user_input = raw_input('Please provide your name:')
- if user_input in ("Q", "q"):
- break
- if user_input == "":
- print "Your input is required"
- continue # necessary in this case
- print "Youre name has been recorded:", user_input
- break
- Please provide your name:
- Your input is required
- Please provide your name:
- Your input is required
- Please provide your name:q
- >>>
- >>> # run the loop again to test valid input
- ...
- Please provide your name:
- Your input is required
- Please provide your name:A
- Youre name has been recorded: A
- >>>
Add Comment
Please, Sign In to add comment