Category: Python3

Added: 11th of December 2020

Viewed: 1,568 times


Learning Python 3, check user input is an integer

When the user enters a number or character this is assigned to the variable number.

If the user enters a number, the number is displayed via the print statement. The break statement is used to terminate the current loop

If the user enters a character, a message is then displayed informing the user to an a number. The continue statement is used to return to the beginning of the while loop, and the user has to re-enter a number via the input command.

#!/usr/bin/env python3

while True:

    try:
        number = int(input('Enter a number '))
        print(number)
        break

    except ValueError:
        print("You entered a character. Please only enter numbers")
        continue