Python input() Guide: Basics to Advanced Techniques

目次

1. Introduction

Python is a programming language that combines simple syntax with powerful features, and it is used by a wide range of developers from beginners to experts. In particular, the ability to receive input from users is essential when creating interactive programs. In this article, we will explain in detail how to receive user input in Python. It covers everything from the basic usage of the input() function to numeric conversion, handling multiple inputs, error handling, and advanced input processing, structured to be easy to understand for readers ranging from beginners to intermediate users. By reading this article, you will learn the following:
  • Basic usage of Python’s input() function
  • How to handle string input and numeric conversion
  • How to receive multiple values
  • Error handling during input (try-except)
  • Advanced input processing (file input, command-line arguments, password input)
Gain a solid understanding of Python’s user input mechanisms and become capable of creating practical programs!

2. Basic Usage of Python’s input() Function (Beginner Friendly)

In Python, the most basic function for receiving input from the user is input(). By using this function, you can obtain data entered by the user during program execution and store it in a variable. In this section, we will explain the basic behavior of the input() function and how to handle strings and numbers.

2.1 Basic Usage of the input() Function

Using the input() function, you can display a message to the user on the console (terminal) and receive input. Below is the simplest example of using input().
name = input("Please enter your name: ")
print(f"Hello, {name}!")

Example Output

Please enter your name: Taro
Hello, Taro!

How It Works

  1. When input("Please enter your name: ") is executed, the program pauses until the user provides input.
  2. After the user enters input and presses the Enter key, that value is stored in the variable name as a string (str type).
  3. You can display the entered content on the screen using the print() function.

2.2 How to Receive Numbers with input() (Type Conversion)

Data obtained with the input() function is always a string (str type). For example, even if you enter a number, it is treated as a string.

Example: Enter a Number Directly

age = input("Please enter your age: ")
print(type(age))  # becomes a str (string) type

Output

Please enter your age: 25
<class 'str'>
In the above example, the age obtained via input() is “25” (a string of type str), not a number. If you want to treat it as a number, you need to perform type conversion.

Conversion to Integer (int type)

When receiving input as an integer, use the int() function.
age = int(input("Please enter your age: "))
print(f"You are {age} years old.")

Output

Please enter your age: 25
You are 25 years old.
By using int(), the user’s input value is treated as an integer type (int).

Conversion to Float (float type)

When entering a decimal number, use the float() function.
height = float(input("Please enter your height (cm): "))
print(f"Your height is {height} cm.")

Output

Please enter your height (cm): 170.5
Your height is 170.5 cm.
Using float() allows you to properly handle numbers that include a decimal point.

2.3 Caveats of input() and Error Occurrence

When using int() or float() for type conversion, an error occurs if the user enters data that is not a number.

Example of an Error

age = int(input("Please enter your age: "))
Please enter your age: abc
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'
A ValueError occurs, causing the program to crash. To prevent this issue, you need to implement error handling (exception handling). Error handling will be explained in detail in a later section.

2.4 Summary

  • input() function is the basic function for obtaining input from the user.
  • Data obtained with input() is always treated as a string (str type).
  • When you want the user to input numbers, perform type conversion using int() or float().
  • When using int() or float(), be mindful of incorrect input and it is advisable to implement error handling.

3. How to Receive Multiple Inputs in Python (Using split/Loops)

In Python, you can receive multiple values with a single input. In particular, there are convenient ways to obtain data as a list or to handle repeated inputs. This section explains the method using split() and the method for multi-line input using loops.

3.1 Using split() to Input Multiple Values in One Line

Normally, when you receive input from the user with input(), it is treated as a single string. However, by using split(), you can obtain multiple values separated by spaces and process them as a list.

Basic Example

values = input("Please enter multiple values separated by spaces: ").split()
print("Entered values:", values)

Example Output

Please enter multiple values separated by spaces: 10 20 30 40
Entered values: ['10', '20', '30', '40']

How It Works

  1. Obtain the string entered by the user via input().
  2. Use .split() to split by spaces (default) and convert to a list.
  3. As a result, the values are stored as a list.
Using this method, you can receive variable-length data from the user.

3.2 Combining split() with Type Conversion

In the method described above, the entered values are all strings (str type). If you want to process them as numbers, you need to convert each element in the list to the appropriate type.

Example: Process as Numbers

numbers = list(map(int, input("Please enter integers separated by spaces: ").split()))
print("Sum of integers:", sum(numbers))

Example Output

Please enter integers separated by spaces: 5 10 15 20
Sum of integers: 50

Explanation

  • After converting to a list with input().split(), use map(int, ...) to convert each element to an integer (int type).
  • Wrap the result of map with list() to create a list.
  • Use the sum() function to calculate the total.
This method is very useful when processing multiple numbers at once.

3.3 Receiving Multiple Lines of Input Using a while Loop

The split() method processes only a single line of input. However, if you want the user to enter data over multiple lines, using a while loop provides flexible handling.

Method for Receiving Multiple Lines of Input

lines = []
print("Please enter data (press Enter on an empty line to finish):")

while True:
    line = input()
    if line == "":  # Exit when an empty line is entered
        break
    lines.append(line)

print("Entered data:", lines)

Example Output

Please enter data (press Enter on an empty line to finish):
apple
banana
orange

Entered data: ['apple', 'banana', 'orange']

Explanation

  1. Create an infinite loop using while True.
  2. The user inputs a value with input().
  3. When an empty line ("") is entered, break ends the loop.
  4. All inputs are stored in the lines list.
Using this method, the user can input any number of data items.

3.4 Receiving Input a Fixed Number of Times Using a for Loop

When you need to receive input a specific number of times, using a for loop is convenient.

Example: Receive Input 3 Times

data = []
for i in range(3):
    value = input(f"{i+1}th input: ")
    data.append(value)

print("Entered data:", data)

Example Output

1st input: Python
2nd input: Java
3rd input: C++
Entered data: ['Python', 'Java', 'C++']

Key Points

  • Using a for loop lets you specify the number of inputs explicitly.
  • Displaying the input count, such as with f"{i+1}th input", makes it clear for the user.

3.5 Summary

MethodDescriptionBenefit
split() UsingConvert a single line of input into a listEasily receive multiple values
split() + Type ConversionConvert numeric input into a listSimplifies numeric processing
while LoopReceive multiple lines of inputInput count can be set freely
for LoopReceive input a fixed number of timesControl the number of repetitions precisely

4. Error Handling During Input [Using try-except]

When receiving input from users in Python, unexpected values can be entered. For example, if a string is entered when a number is expected, the program will raise an error and stop. To prevent this, implementing error handling using try-except is essential. This section explains the basic usage of try-except and practical error handling techniques.

4.1 Basic Usage of try-except

In Python, using try-except allows the program to handle errors (exceptions) appropriately when they occur.

Basic Example

try:
    num = int(input("Enter an integer: "))
    print(f"Entered integer: {num}")
except ValueError:
    print("Error: Please enter an integer!")

Example Output

Enter an integer:10
Entered integer: 10
Enter an integer: abc
Error: Please enter an integer!

How It Works

  1. try: block receives input with input() and converts it with int().
  2. If a numeric value is entered, processing continues normally.
  3. If a non-convertible value such as a string is entered, a ValueError occurs and the except ValueError: block is executed.
This ensures that even when an error occurs, the program does not crash and can display an appropriate message.

4.2 Using a while Loop to Continuously Prompt for Correct Input

The method above only displays an error message when an error occurs, but the approach of repeatedly prompting until a correct value is entered is also commonly used.

Example: Repeating Until the User Enters an Integer

while True:
    try:
        num = int(input("Enter an integer: "))
        break  # Exit the loop when input is correct
    except ValueError:
        print("Error: Please enter an integer!")

print(f"Entered integer: {num}")

Example Output

Enter an integer: abc
Error: Please enter an integer!
Enter an integer: 12
Entered integer: 12

Key Points

  • Using while True: creates an infinite loop.
  • Using try-except to prompt again if an error occurs.
  • Exit the loop with break when input is correct.
Using this method ensures the program continues running until the user provides input in the correct format.

4.3 Handling Multiple Inputs with try-except

When receiving multiple values, you can safely process them using tryexcept.

Example: Input Multiple Integers Separated by Spaces

while True:
    try:
        numbers = list(map(int, input("Enter integers separated by spaces: ").split()))
        break  # Exit the loop when input is correct
    except ValueError:
        print("Error: Please enter integers only!")

print(f"Entered integer list: {numbers}")

Example Output

Enter integers separated by spaces: 10 20 30
Entered integer list: [10, 20, 30]
Enter integers separated by spaces: 10 abc 30
Error: Please enter integers only!

Explanation

  • Use map(int, input().split()) to obtain multiple integers.
  • Use try-except to request re-entry if the input contains non-numeric values.

4.4 Using finally for Cleanup

try-except includes a finally block that runs at the end regardless of whether an error occurred.

Example: Resource Release

try:
    num = int(input("Enter an integer: "))
    print(f"Entered integer: {num}")
except ValueError:
    print("Error: Please enter an integer!")
finally:
    print("Finishing processing.")

Example Result

Enter an integer: abc
Error: Please enter an integer!
Finishing processing.
Using a finally: block allows you to execute code at the end regardless of exceptions, making it useful for cleanup tasks such as releasing resources.

4.5 Summary

MethodDescriptionWhen to Use
try-exceptCatch exceptions and handle errorsSimple input validation
while + try-exceptRepeat until correct input is obtainedProcess that continues until the user provides valid input
try-except-finallyError handling plus cleanupManaging file or database resources

5. Advanced: Advanced Input Processing

In Python, you can receive user input not only with the standard input() function but also through various methods. In particular, input from files, retrieving command-line arguments, and hiding password input are useful when creating practical programs. In this section, we explain advanced input handling using sys.stdin.read(), argparse, and getpass.

5.1 Input from Files【sys.stdin.read()

In Python, instead of input(), you can read the contents of a file as standard input (stdin). This allows you to pass file contents to the program for processing.

How to Get Input from a File

import sys

data = sys.stdin.read()  # Read all of standard input
print("Input data:")
print(data)

Execution method (Linux/macOS terminal)

$ python script.py < sample.txt
By specifying < filename like this, the contents of sample.txt are read by sys.stdin.read().

Use cases

  • Programs that process large amounts of data (log analysis, data conversion)
  • Scripts that receive files via pipes

5.2 Receiving Command-Line Arguments【argparse

Using command-line arguments allows you to pass values from outside when the script runs. This is handy when you want to flexibly change the script’s behavior.

Basic example using argparse

import argparse

parser = argparse.ArgumentParser(description="Script to get the user's name")
parser.add_argument("name", help="Please enter your name")
args = parser.parse_args()

print(f"Hello, {args.name}!")

Execution method

$ python script.py Taro
Hello, Taro!

Receiving multiple arguments

parser.add_argument("age", type=int, help="Please enter your age")
args = parser.parse_args()

print(f"{args.name} is {args.age} years old.")

Execution method

$ python script.py Taro 25
Taro is 25 years old.

Use cases

  • Creating command-line tools
  • Specifying script configuration values from outside

5.3 Hiding Password Input【getpass

Normally, when you input a password with input(), it is displayed directly in the terminal. To prevent this, use the getpass module.

Secure password input using getpass

import getpass

password = getpass.getpass("Please enter your password: ")
print("Password has been entered")

Result (password not visible during input)

Please enter your password:
Password has been entered

Use cases

  • Scripts that prioritize security
  • Programs that require authentication

5.4 Summary

MethodDescriptionMain Use Cases
sys.stdin.read()Read file contents as standard inputData processing, log analysis
argparseReceive command-line argumentsCommand-line tools
getpassHide password inputSecurity-focused input

6. Compatibility with Python 2 (Supplementary Information)

Python 3 uses the input() function to obtain user input, but Python 2 had two functions, input() and raw_input(). In environments that use Python 2, the input handling differs, so caution is required when dealing with legacy code. This section explains the differences in input() between Python 2 and Python 3.

6.1 Python 2’s input() and raw_input()

In Python 2, there were two distinct input functions: input() and raw_input().
FunctionBehavior in Python 2Python 3 equivalent
raw_input()Receives input as a stringIntegrated into input()
input()Evaluates the entered content as an expressionEquivalent to eval(input())
In Python 2, raw_input() is equivalent to input(), and in Python 3 the behavior of input() has been merged into raw_input().

6.2 The Dangers of Python 2’s input()

Python 2’s input() has a hazardous design that evaluates user input as Python code. For example, consider the following code.
# In Python 2
value = input("Please enter something: ")
print(value)
When this code runs, if the user enters 5 + 5, it is automatically evaluated and 10 is printed.
Please enter something: 5 + 5
10
This poses a security risk because it allows execution of arbitrary code. For instance, if a user enters a dangerous command like __import__('os').system('rm -rf /'), it could damage the system.

Safe Alternatives

When using Python 2, you can use raw_input() to treat user input as a string.
# Safe method in Python 2
value = raw_input("Please enter something: ")
print(value)
In Python 3, input() is safe by design, so this issue does not occur.

6.3 How to Run Python 2 Code in Python 3

To run code written for Python 2 on Python 3, you need to replace raw_input() with input(). However, if manual changes are difficult, you can use a tool called 2to3 for automatic conversion.

Converting Code Using 2to3

Python 3 provides a tool called 2to3 that can convert Python 2 code to Python 3.
$ 2to3 old_script.py -w
This automatically replaces raw_input() with input().

6.4 Summary

VersionSafe Input Method
Python 2raw_input() is used (input() is unsafe)
Python 3input() is used (safe behavior)
  • Avoid using Python 2’s input() because it is dangerous.
  • raw_input() has been merged into input() in Python 3.
  • Use the 2to3 tool to convert legacy Python 2 code.

7. Summary

In this article, we explained in detail how to receive user input in Python, covering everything from basics to advanced techniques. We covered a wide range of topics, from beginner-friendly usage of the input() function to error handling and advanced input processing.

7.1 Summary of Article Points

SectionContent
1. IntroductionExplain the importance of using input() to receive user input
2. Basics of input()Explain how to input strings and numbers (int() / float())
3. Receiving Multiple InputsHow to use split() to receive inputs as a list and how to handle multi-line input with a while loop
4. Error HandlingHow to use try-except to handle errors appropriately
5. Advanced Input ProcessingInput from files with sys.stdin.read(), command-line arguments with argparse, and password input with getpass
6. Differences with Python 2The differences between raw_input() and input(), and safe input methods in Python 2

7.2 Best Practices for Python User Input Handling

  1. Use the basic input()
  • Using input() makes it easy to input strings.
  • When receiving numbers, convert the type with int() or float().
  1. Apply error handling
  • Use try-except to prevent program crashes caused by user input mistakes.
  • Handle int() and float() appropriately when processing numeric input.
  1. Process multiple inputs
  • Use split() to obtain multiple values as a list at once.
  • Use a while loop to accept an arbitrary number of input lines.
  1. Leverage advanced input methods
  • File input: Read files with sys.stdin.read().
  • Command-line arguments: Use argparse to pass variables from the outside.
  • Password input: Use getpass to ensure security.
  1. Consider compatibility with Python 2
  • In Python 2, use raw_input() and avoid input().
  • When migrating to Python 3, use 2to3 to convert the code.

7.3 Next Steps

By leveraging Python’s input(), you can create more interactive programs. Apply what this article covered and try incorporating it into your own programs. If you want to learn more advanced input processing, the following topics are also recommended.
  • GUI-based input handling (e.g., tkinter or PyQt)
  • Database input handling (e.g., integration with sqlite3 or MySQL)
  • Data input from web forms (e.g., Flask or Django forms)
Being able to handle Python user input freely enables you to apply it to more advanced program development, such as web applications and data processing tools. Use this article as a reference to master input handling in Python smoothly! 🚀