Verify if user input number is greater than 0 in Python

avatar

Borislav Hadzhiev

Last updated: Aug 26, 2022

banner

Photo from Unsplash

Verify if user input number is greater than 0 in Python #

To verify if a user input number is greater than 0:

  1. Use a while loop to iterate until the user provides a positive number.
  2. On each iteration, check if the user provided a number greater than 0.
  3. If both conditions are met, break out of the while loop.
main.py
while True: user_input = input('How old are you? ') try: age = int(user_input) if age >= 0: print(age) break else: print("Age must be a positive integer") continue except ValueError: print('Specify a positive integer for your age.')

verify input number greater than zero

The code snippet checks if the value is greater than or equal to 0. If you only need to check if the input value is greater than 0, update the if statement to if age > 0:.

We used a while loop to iterate until the user provides a positive number.

The input function takes an optional prompt argument and writes it to standard output without a trailing newline.

The function then reads the line from input, converts it to a string and returns the result.

The input() function is guaranteed to return a string even if the user enters a number.

We used a try/except statement to handle the case where the user enters a value that cannot be converted to an integer.

main.py
while True: user_input = input('How old are you? ') try: age = int(user_input) if age >= 0: print(age) break else: print("Age must be a positive integer") continue except ValueError: print('Specify a positive integer for your age.')

If the int() class throws an error, the except block runs, prints a message and we prompt the user again.

If the provided value is a valid integer, the if statement checks if it is greater than 0.

If the value is greater than 0, we use the break statement to break out of the while loop.

The break statement breaks out of the innermost enclosing for or while loop.

When validating user input in a while loop, we use the continue statement when the input is invalid.

If the input is valid, we use the break statement to exit out of the while loop.

If the input value is a valid integer but is not greater than 0, the else block runs where we use the continue statement to prompt the user again.

The continue statement continues with the next iteration of the loop.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.