Python input() Function: How to Accept User Input from the Keyboard

When creating command-line tools or interactive scripts, there are times when you want to receive input from the user while the program is running. In Python, you can easily get standard input from the keyboard using the built-in input() function.

This article explains the basic usage of the input() function, how to handle inputs as numbers, and how to implement interactive processing combined with while loops.


目次

Basics of the input() Function

When the input() function is called, the program execution pauses and waits for the user to type characters from the keyboard and press the Enter key. Once Enter is pressed, the input content is returned to the program as a string (str).

Syntax:

variable = input("Message to prompt input (Prompt)")

If you pass a string as an argument, that message is displayed before the program waits for input.

Specific Example: User Registration

Here is a program that asks the user for their name and location.

print("--- User Registration ---")

# Ask for name (Display prompt)
user_name = input("Please enter your name: ")

# Ask for location
location = input("Please enter your location: ")

print("--------------------")
print(f"Registration Complete: {user_name} ({location})")

Output Example:

--- User Registration ---
Please enter your name: Tanaka
Please enter your location: Tokyo
--------------------
Registration Complete: Tanaka (Tokyo)

Important Note: Return Value is Always a “String”

Data obtained with the input() function is treated as string type (str), even if you input numbers. Therefore, if you want to perform calculations using the input numbers, you need to convert the type using int() or float().

# Inputting a number
price_str = input("Please enter the product price: ")

# Cannot calculate as a string, so convert to integer
try:
    price = int(price_str)
    tax_included = int(price * 1.1)
    print(f"Price with tax: {tax_included} yen")
except ValueError:
    print("Error: Please enter an integer.")

Output Example:

Please enter the product price: 1000
Price with tax: 1100 yen

If you try to calculate price_str * 1.1 without converting with int(), a TypeError will occur.


Receiving Repeated Input (while loop)

By placing the input() function inside a while loop, you can continue interactive processing until a specific exit command is entered.

General Implementation Pattern

print("Please enter a command. (Type 'exit' to quit)")

while True:
    # Receive input
    command = input(">> ")
    
    # Check for exit condition
    if command == "exit":
        print("Exiting program.")
        break
    
    # Process based on input content
    if command == "date":
        print("2025-11-27")
    elif command == "hello":
        print("Hello!")
    else:
        print(f"Unknown command: {command}")

Output Example:

Please enter a command. (Type 'exit' to quit)
>> hello
Hello!
>> date
2025-11-27
>> test
Unknown command: test
>> exit
Exiting program.

Short Notation Using Assignment Expression (Walrus Operator)

In Python 3.8 and later, you can use the Assignment Expression := (Walrus Operator) to write the input reception and termination check in a single line.

print("Please enter a message. (Type 'quit' to finish)")

# Assign input result to 'msg' and simultaneously check if it is not 'quit'
while (msg := input("Input: ")) != "quit":
    print(f"Received message: {msg}")

print("Finished.")

Writing it this way avoids code duplication (writing input once before the loop and again inside the loop), making the code concise.


Summary

  • Use input("Message") to get keyboard input from the user.
  • The return value is always a string. Conversion using int() etc., is required to handle it as a number.
  • Combine with while loops to create interactive tools that repeat processing until an exit command is entered.
  • Using the assignment expression := allows you to perform input and judgment simultaneously within the loop condition.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次