input()
The built-in input()
function captures the user input from the keyboard. It displays a prompt message to the user and waits for the user to type their response followed by pressing the Enter key:
>>> name = input("What is your name? ")
What is your name? John
>>> name
'John'
input()
Signatures
input()
input(prompt)
Arguments
Argument | Description |
---|---|
prompt |
A string to display as a prompt to the user before waiting for input. |
Return Value
- Returns the user input as a string, regardless of the input type.
input()
Examples
With a string prompt to ask for the user’s job:
>>> job = input("What is your current job? ")
What is your name? Python Dev
>>> job
'Python Dev'
With a string prompt to ask for the user’s age:
>>> age = input("How old are you? ")
How old are you? 30
>>> age
'30'
input()
Common Use Cases
The most common use cases for the input()
function include:
- Gathering user input for interactive programs or scripts.
- Prompting the user for configuration settings or parameters.
- Creating simple command-line interfaces.
input()
Real-World Example
Say that you want to write a number-guessing game where the user enters a number to guess a secret random number between 1
and 10
. To get the user input, you can use input()
as shown below:
guess.py
from random import randint
LOW, HIGH = 1, 10
secret_number = randint(LOW, HIGH)
clue = ""
while True:
guess = input(f"Guess a number between {LOW} and {HIGH} {clue} ")
number = int(guess)
if number > secret_number:
clue = f"(less than {number})"
elif number < secret_number:
clue = f"(greater than {number})"
else:
break
print(f"You guessed it! The secret number is {number}")
This example uses input()
to collect the user’s input. When the user guesses the secret number, the else
clause runs, breaking the loop. The final line of code prints the successful guess message.
Related Resources
Tutorial
How to Read User Input From the Keyboard in Python
Reading user input from the keyboard is a valuable skill for a Python programmer, and you can create interactive and advanced programs that run on the terminal. In this tutorial, you'll learn how to create robust user input programs, integrating error handling and multiple entries.
For additional information on related topics, take a look at the following resources:
- Python's Built-in Functions: A Complete Exploration (Tutorial)
- Numbers in Python (Tutorial)
- Python "while" Loops (Indefinite Iteration) (Tutorial)
- How Can You Emulate Do-While Loops in Python? (Tutorial)
- Python's Built-in Functions: A Complete Exploration (Quiz)
- Mastering While Loops (Course)
- Python "while" Loops (Quiz)