How to take integer input in Python?

Taking integer input is a fundamental task in Python programming. The input() function returns strings by default, so we need to convert them to integers using int(). This article explores four common approaches to handle integer input effectively.

Using input() and int() Conversion

The input() function captures user input as a string. To work with integers, we convert the string using int() function ?

Single Integer Input

# Taking single integer input
num = int(input("Enter an integer: "))
print("You entered:", num)
print("Type:", type(num))
Enter an integer: 42
You entered: 42
Type: <class 'int'>

Multiple Integer Inputs

# Taking multiple integers separated by spaces
numbers = list(map(int, input("Enter multiple integers: ").split()))
print("You entered:", numbers)
print("Sum:", sum(numbers))
Enter multiple integers: 10 20 30
You entered: [10, 20, 30]
Sum: 60

Using map() Function

The map() function applies int() conversion to each element in a sequence, making it ideal for processing multiple integers ?

# Using map() for multiple integer inputs
user_input = input("Enter integers separated by spaces: ")
numbers = list(map(int, user_input.split()))

print("Original input:", user_input)
print("Converted to integers:", numbers)
print("Each number doubled:", [x * 2 for x in numbers])
Enter integers separated by spaces: 5 15 25
Original input: 5 15 25
Converted to integers: [5, 15, 25]
Each number doubled: [10, 30, 50]

Reading Integers from Files

When working with file input, we read the content as strings and convert to integers as needed ?

# Create a sample file with integers
with open("numbers.txt", "w") as file:
    file.write("42\n")
    file.write("10 20 30 40\n")

# Read integers from the file
with open("numbers.txt", "r") as file:
    # Read single integer from first line
    single_num = int(file.readline().strip())
    print("Single number:", single_num)
    
    # Read multiple integers from second line
    multiple_nums = list(map(int, file.readline().strip().split()))
    print("Multiple numbers:", multiple_nums)
Single number: 42
Multiple numbers: [10, 20, 30, 40]

Command Line Arguments

Command line arguments are passed as strings in sys.argv. Convert them to integers for mathematical operations ?

import sys

# Convert command line arguments to integers
if len(sys.argv) > 1:
    numbers = [int(arg) for arg in sys.argv[1:]]
    print("Command line integers:", numbers)
    print("Sum:", sum(numbers))
    print("Average:", sum(numbers) / len(numbers))
else:
    print("No arguments provided")

# Run as: python script.py 10 20 30 40
Command line integers: [10, 20, 30, 40]
Sum: 100
Average: 25.0

Error Handling

Always handle cases where input might not be a valid integer ?

def get_integer_input(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Invalid input! Please enter a valid integer.")

# Safe integer input
number = get_integer_input("Enter an integer: ")
print("Valid integer entered:", number)
Enter an integer: abc
Invalid input! Please enter a valid integer.
Enter an integer: 123
Valid integer entered: 123

Comparison

Method Use Case Advantage
int(input()) Single integer input Simple and direct
map(int, input().split()) Multiple integers Handles space-separated values
File reading Batch processing Process large datasets
Command line args Script parameters Automated execution

Conclusion

Use int(input()) for single integers and map(int, input().split()) for multiple integers. Always include error handling for robust programs that gracefully handle invalid input.

---
Updated on: 2026-03-27T13:59:25+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements