Cohort 4Register

PART 1 · PYTHON FROM ZERO · LESSON 6

Input and output

FreeLesson 8 of 78

print() sends text out. input() takes text in. Between the two you can already build small interactive tools.

PRINT IN DETAILPYTHON 3.12
print("a", "b", "c")                 # spaces between items
print("a", "b", "c", sep=" | ")      # choose the separator
print("loading", end="... ")         # stay on the same line
print("done")
print()                              # an empty line
print("Line 1\nLine 2")             # \n is a new line

Output

a b c
a | b | c
loading... done

Line 1
Line 2
ASKING THE USERPYTHON 3.12
name = input("Your name: ")
qty = int(input("How many items? "))    # input is always text
price = float(input("Price per item: "))

total = qty * price
print()
print(f"Hi {name}, your total is {total:,.2f}")

Output

Your name: How many items? Price per item:
Hi Meera, your total is 747.00
PROTECTING AGAINST BAD INPUTPYTHON 3.12
raw = "abc"                  # what if the user types letters?
try:
    qty = int(raw)
except ValueError:
    print("Please type a whole number, not", repr(raw))

Output

Please type a whole number, not 'abc'

int("abc") raises a ValueError and would stop the program. try/except catches it so you can ask again or skip the row. Lesson 17 and page 32 go further.

PRINTING A NEAT RECEIPTPYTHON 3.12
items = [("Wireless Mouse", 1, 799), ("Gel Pens", 3, 149),
         ("Water Bottle", 1, 399)]

print(f"{'item':<16}{'qty':>4}{'amount':>10}")
print("-" * 30)
total = 0
for name, qty, price in items:
    line = qty * price
    total += line
    print(f"{name:<16}{qty:>4}{line:>10,.2f}")
print("-" * 30)
print(f"{'total':<16}{'':>4}{total:>10,.2f}")

Output

item             qty    amount
------------------------------
Wireless Mouse     1    799.00
Gel Pens           3    447.00
Water Bottle       1    399.00
------------------------------
total                 1,645.00

Widths like :<16 (left, 16 wide) and :>10 (right, 10 wide) line up columns. This is how small reports and log lines are made readable.

Try it yourself before moving on

  1. Ask for two numbers and print their sum.
  2. Print a receipt for three items with the prices lined up on the right.
  3. What happens if the user types 3.5 when your code calls int()? Try it.