Home/Blog/Learn to Code/How to take integer input in Python
Home/Blog/Learn to Code/How to take integer input in Python

How to take integer input in Python

Mohsin Abbas
Feb 16, 2024
8 min read

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

Python is an excellent choice for applications because it’s easy to use. In Python programming, one of the fundamental tasks is accepting and processing user inputs, particularly numerical data. A common requirement is to obtain integer inputs that form the basis of many interactive Python applications, from simple calculators to complex data processing systems. This guide explores various scenarios and techniques for effectively capturing integer input in Python, and provides detailed insights to cater to both beginner and experienced programmers.

The input() function#

The primary technique for recording user inputs, which are inherently read as strings, is the input() function available in Python. Converting these strings to numbers and ensuring they satisfy specified criteria (such as being positive, falling within a given range, etc.) is an essential skill in Python programming. The input() function in Python is designed to accept user input, returning whatever the user types as a string. This necessitates the conversion of this string to an integer when numerical input is needed. However, this conversion process can be prone to errors if the input is not a valid integer. This highlights the importance of proper error handling and input validation.

Scenario 1: Basic integer input#

The foundation of taking integer input in Python starts with understanding the basic process of capturing and converting user input. Imagine a user interacting with a basic calculator application designed to perform arithmetic operations. The application requires the user to input numbers to execute tasks like addition or subtraction. Users might wrongly type a word or a mix of letters and numbers when prompted to enter a number.

The script below initially captures the input as a string and then attempts to convert it to an integer. If the conversion is successful, the application proceeds with the calculation. This prevents the application from crashing and maintaining a smooth user experience. Such scripts ensure the processing of valid numerical inputs, making them more robust and reliable for everyday use.

Example code#

number_str = input()
try:
number = int(number_str)
print(f"You entered {number}")
except ValueError:
print("This is not an integer. Please enter a valid integer.")

Enter the input below

Detailed explanation#

  • Initial input capture: number_str = input()

    • This line stores the input as a string in the variable number_str.

  • Attempted conversion to integer: number = int(number_str)

    • The int() function is used to convert the string to an integer.

    • This line is wrapped in a try block to catch any exceptions that might occur during conversion.

  • Successful conversion output: print(f"You entered {number}")

    • This displays the successfully converted integer.

  • Error handling for invalid inputs: except ValueError:

    • This catches a ValueError when the conversion fails (e.g., if the input is not a numeric string).

  • Prompt for correct input on error: print("This is not an integer. Please enter a valid integer.")

    • This informs the user of the incorrect input and prompts for a valid integer.

Sample input and output#

  • Input: 23

  Output: You entered 23

  • Input: hello

  Output: This is not an integer. Please enter a valid integer.

Scenario 2: Positive integer validation#

In many applications, such as when counting objects, specifying age, or setting up quantities in a transaction, negative numbers or zero may not be valid. One such application might be an educational application designed for young learners to practice math problems. Here, it is required that the input should be a positive integer, as zero or negative numbers would not make sense in this context.

The provided script is designed to handle such cases. It initially receives the input as a string and then attempts to convert it into an integer. The script checks if the number is positive if this conversion is successful. In the case of a positive integer, the script accepts the input that can be used to allow the app to generate the specified number of math problems.

This type of script ensures the integrity of user input and maintains the logical flow of the application, enhancing its usability and reliability. These can be used in various applications, such as an educational app.

Example code#

try:
number = int(input())
if number > 0:
print(f"Valid input: {number}")
else:
print("Please enter a positive integer.")
except ValueError:
print("This is not an integer. Please enter a valid integer.")

Enter the input below

Detailed explanation#

  • Conversion and positivity check: if number > 0:

    • This validates that the entered integer is greater than zero, indicating a positive number.

  • Handling non-positive integers: The else block

    • This informs the user if the entered number is not positive and requests a new input.

  • Non-integer input error handling: except ValueError:

    • This catches and handles cases where the input is not convertible to an integer.

Sample input and output#

  • Input: 5

  Output: Valid input: 5

  • Input: -3

  Output: Please enter a positive integer.

  • Input: abc

  Output: This is not an integer. Please enter a valid integer.

Scenario 3: Range validation#

Certain applications require input within a specific range, such as setting thresholds, defining age limits, or specifying dimensions within acceptable limits. Consider, for instance, an online registration form for a community sports league. This form might require participants to enter their age to ensure eligibility, with the league being open only to individuals within a certain age range, say 18 to 40 years old. In this scenario, the input must not only be a valid integer but also fall within the specified age range. The script below checks whether the age falls within the 18 to 40 years range. If the age is within this range, the script acknowledges the valid input, allowing the registration process to proceed.

However, if the entered age is outside this range or the input is not a valid integer, the script informs the participant of the invalid entry.

This type of functionality is useful in applications like sports league registration, ensuring that only eligible individuals can register. It helps maintain the specific requirements, enhancing the application’s overall efficiency and user experience.

Example code#

min_val = 18
max_val = 40
try:
number = int(input())
if min_val <= number <= max_val:
print(f"Valid input: {number}")
else:
print(f"Please enter an integer within the range of {min_val} to {max_val}.")
except ValueError:
print("This is not an integer. Please enter a valid integer.")

Enter the input below

Detailed explanation#

  • Defining acceptable range: min_val = 18 and max_val = 40

    • This sets the lower and upper boundaries for the input.

  • Range checking: if min_val <= number <= max_val:

    • This validates whether the input exists within the defined range.

Sample input and output#

  • Input: 20

  Output: Valid input: 20

  • Input: 150

  Output: Please enter an integer within the range of 18 to 40.

  • Input: text

  Output: This is not an integer. Please enter a valid integer.

Scenario 4: Multiple integer inputs#

Collecting a sequence of integers from the user is necessary in many practical situations. These situations might include conducting surveys, recording measurements, or documenting multiple financial transactions. Each of these integers is crucial in ensuring accurate data collection and processing. Consider the example of a scientific research survey where participants are asked to input three different data points:

  • Their age

  • The number of hours they sleep daily

  • The number of steps they take on average daily

Each of these inputs needs to be an integer to ensure the accuracy and reliability of the data collected for the study. The script provided is tailored to meet such requirements. It begins by setting num_inputs = 3, indicating that three separate integer inputs are needed. Once a valid integer is entered, it’s appended to the numbers list, and the script moves on to the next input. After all three integers are collected, the script concludes by displaying the entered integers. This method is highly effective in scenarios requiring multiple integer inputs, as it ensures each input is valid before proceeding to the next, therefore maintaining the integrity and accuracy of the data collected.

This approach may be used in applications like surveys and data entry systems, where precise and valid numerical inputs are required.

Example code#

num_inputs = 3
numbers = []
output = 1
for _ in range(num_inputs):
try:
number = int(input())
numbers.append(number)
except ValueError:
print("Please enter valid integer inputs.")
output = 0
if output:
print("You entered the integers:", numbers)

Enter the input below

Please input integers one at a time, pressing “Enter” after each number. Space separation will not work on our platform and may lead to errors.

Detailed explanation#

  • Setting the number of inputs: num_inputs = 3

    • This defines how many integers the program should collect.

  • Loop for capturing integer: for _ in range(num_inputs):

    • This iterates to capture the specified number of integers.

Sample input and output#

  • Inputs: 3, 7, 9

  Output: You entered the integers: [3, 7, 9]

  • If a non-integer input is entered

  Output: Please enter valid integer inputs.

Conclusion#

Handling integer input in Python is critical for creating interactive and user-friendly applications. This blog has thoroughly explored various scenarios, from basic integer input to complex validations such as ensuring positivity, checking ranges, and collecting multiple integers. It is possible to ensure that our Python programs are robust, user-friendly, and capable of properly managing various user input scenarios once we have a solid understanding of these strategies and include them in our programming. In applications that are implemented in the real world, the capability to reliably process and validate user input is mandatory. It ensures that the collected data is accurate. It also enhances the overall user experience by supporting users in overcoming input errors and ensuring that the integrity of the application is maintained.

Our journey as a Python programmer will be considerably facilitated by developing these skills. It will enable us to design more dynamic, efficient, and dependable programs.

Next learning steps#

For further advancement in Python programming, explore the array of specialized courses on the Educative platform listed below:

These courses are designed to enhance your Python skills, covering a spectrum from basic principles to more intricate concepts. You’ll have the opportunity to deepen your understanding of Python and its diverse applications and gain valuable skills essential for your professional growth. Begin your journey toward Python mastery by enrolling in these Educative courses today!


  

Free Resources