Python Input/Output Examples
Short, runnable programs that show python input and output in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Input and Output lesson.
1Adding two numbers typed by the user
Each input() reads one line from the Input box. Converting both with int() makes real arithmetic possible, and the f-string shows the working.
a = int(input("First number: "))
b = int(input("Second number: "))
print(f"{a} + {b} = {a + b}")
print(f"{a} / {b} = {a / b:.3f}")Expected outputFirst number: 8
Second number: 5
8 + 5 = 13
8 / 5 = 1.600
2Reading several values from one line
When the user types several values on one line, split() breaks the text at the spaces. Each part is still a string, so convert before adding.
sides = input("Enter three sides: ").split()
a, b, c = sides
perimeter = int(a) + int(b) + int(c)
print("Sides:", a, b, c)
print("Perimeter:", perimeter)Expected outputEnter three sides: 3 4 5
Sides: 3 4 5
Perimeter: 12
3Printing a neat receipt with alignment
:<10 pads text to 10 characters on the left side, and :>8.2f right-aligns a number with two decimals in 8 characters, so the columns line up.
print(f"{'Item':<10}{'Price':>8}")
print(f"{'Coffee':<10}{3.5:>8.2f}")
print(f"{'Bagel':<10}{2.25:>8.2f}")
print("-" * 18)
print(f"{'Total':<10}{3.5 + 2.25:>8.2f}")Expected outputItem Price
Coffee 3.50
Bagel 2.25
------------------
Total 5.75
4Cleaning up a typed answer
People type answers in all sorts of ways. Chaining strip() and lower() straight onto input() turns YES, Yes or yes into the same clean value.
answer = input("Continue? (yes/no) ").strip().lower()
print("You typed:", answer)
print("Going ahead:", answer == "yes")Expected outputContinue? (yes/no) YES
You typed: yes
Going ahead: True
Practise next
Python Input and Output exercises → Back to the lesson
Python Exceptions: try, except, else and finally examplesPython File Handling examplesPython Calculator Project examples