When writing a program you need to think about errors the user can do and one of them is not entering anything when you ask to input something. I'll show show on two examples how to prevent it and print an error for user.
![]() |
viteac.blogspot.com - Check if user input is emopty |
You're asking user to input some data and want to store it in variable to use later but user of some reasons or by mistake can enter nothing and just press Enter. There's a few ways to detect it.
Example 1:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
while True: # initiate infinite loop | |
u_input = input('Enter: ') | |
if not u_input: #if u_input is False | |
print('Try again. Enter something') | |
else: # otherwise print & break | |
print(u_input) | |
break |
Enter something:
Try again.
Enter something:
Try again.
Enter something: something
something
Process finished with exit code 0
Example 2:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
while True: | |
try: | |
u_input = input("Enter something: ") | |
if not u_input: | |
raise ValueError | |
except ValueError as error: | |
print('Error. Try again and enter something') | |
else: | |
print(f' This is what you entered: {u_input}') | |
break |
Enter something:
Error. Try again and enter something
Enter something: something
This is what you entered: something
Process finished with exit code 0
You
can donate me so I can afford to buy a coffee myself, this will help me
to keep going and create more content you find interesting.
Many thanks
Stay Happy and Keep Coding :-)
Stay Happy and Keep Coding :-)
Comments
Post a Comment