Input and output operations let your programs interact with users. Python makes this straightforward with input() and print().
Getting input from the user
Use input() to read text from the keyboard. It always returns a string.
name = input("Enter your name: ")
print(name)
Add a prompt inside input():
age = input("How old are you? ")
The program waits for the user to type something and press Enter.
Converting input types
Since input() returns a string, convert it when needed.
age = int(input("How old are you? "))
print(age + 1) # Adds 1 to the number
Common conversions:
-
int()for whole numbers -
float()for decimals -
str()to convert back to text
Without conversion:
number = input("Enter a number: ") # "10"
result = number + "5" # "105" (concatenation, not addition)
Basic output with print
Use print() to display values.
print("Hello, world!")
print(42)
print(True)
Print multiple items:
name = "Alex"
score = 95
print("Name:", name, "Score:", score)
Use f-strings for cleaner output:
print(f"{name} scored {score} points.")
Control formatting:
pi = 3.14159
print(f"Pi rounded: {pi:.2f}") # Pi rounded: 3.14
Simple program example
A basic calculator addition:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
sum_result = num1 + num2
print(f"The sum is: {sum_result}")
Common mistake: forgetting type conversion
This causes errors when doing math:
age = input("Age: ") # "25"
next_year = age + 1 # TypeError
Fix:
next_year = int(age) + 1
Quick summary
-
input()reads user text (always as string). - Convert with
int(),float(), etc. for calculations. -
print()displays output; use f-strings for formatting. - Combine them to make interactive programs.
Practice building small interactive scripts. Input and output are key for creating useful Python programs.
Top comments (0)