Python input()
In this page:
Basic input() Usage
input() pauses your program and waits for the user to type something and press Enter; whatever they typed is returned as a string, regardless of whether it looked like a number. This is Python's standard way to make a script interactive from the command line.
Example: Basic input() Usage
# name = input("Enter your name: ")
name = "Alex" # simulated input for this sandbox
print("Hello,", name)
Converting Inputs to Integers
Since input() always hands back text, wrapping the call in int() — like age = int(input("Age: ")) — converts that text into a whole number so you can safely use it in arithmetic or numeric comparisons.
Example: Converting Inputs to Integers
# age = int(input("Age: "))
age = int("25")
print(age + 1)
Converting Inputs to Floats
For values with a decimal point, float() performs the same job as int() but produces a floating-point number instead, which matters for calculations like averages or measurements where a whole number would lose precision.
Example: Converting Inputs to Floats
# price = float(input("Price: "))
price = float("19.99")
print(price * 2)
Reading Multiple Inputs
Calling .split() on the string returned by input() breaks it into a list of separate pieces wherever whitespace occurs, which is the standard way to read several values a user typed on a single line, like x, y = input().split().
Example: Reading Multiple Inputs
# x, y = input().split()
x, y = "3 4".split()
print(x, y)
Handling Input Types
If a user types letters where int() or float() expects a number, Python raises a ValueError and the program crashes unless you catch it — validating or wrapping conversions in a try/except block is essential for any program that trusts real user input.
Example: Handling Input Types
text = "abc"
try:
number = int(text)
except ValueError:
print("That's not a valid number")
Chapter Quiz — Complete all 16 topics to unlock
0/16 topics done
Complete these topics first:
- Python print()
- Python input()
- Python Format Strings
- Python f-strings
- Python String Formatting
- Python Arithmetic Operators
- Python Relational Operators
- Python Logical Operators
- Python Bitwise Operators
- Python Assignment Operators
- Python Increment & Decrement
- Python Ternary Operator
- Python Operator Precedence
- Python Identity Operators
- Python Membership Operators
- Python Operators