The print() Function#

How Do I See What My Code Is Doing?#

When you run code, Python does calculations silently. If you don’t print anything, you have no idea what’s happening. Did the velocity calculation work? Is the loop running? What value does x have right now?

print() is your window into what your code is doing. You’ll use it constantly for:

  • Checking if your calculations are correct

  • Debugging when something goes wrong

  • Displaying results to the user


Basic Printing#



Combining Multiple Variables#

g = 9.8
m = 68.1
c = 12.5
t = 10

v = (g * m / c) * (1 - 2.71828**(-c/m * t))

# All on one line
print(f"At t = {t} s, velocity = {v:.2f} m/s")

Output: At t = 10 s, velocity = 44.87 m/s


Printing in Loops#

Very useful for seeing what happens at each step.

v = 0
g, c, m, dt = 9.8, 12.5, 68.1, 2

for t in range(0, 14, 2):
    print(f"t = {t:2d} s, v = {v:5.2f} m/s")
    #        ^^^^         ^^^^^
    #        |            5 characters wide, 2 decimal places
    #        2 characters wide (pads with space)
    v = v + (g - c/m * v) * dt

Output:

t =  0 s, v =  0.00 m/s
t =  2 s, v = 19.60 m/s
t =  4 s, v = 32.00 m/s
t =  6 s, v = 39.85 m/s
t =  8 s, v = 44.82 m/s
t = 10 s, v = 47.97 m/s
t = 12 s, v = 49.96 m/s

Older Styles (You’ll See These)#

You don’t need to use these, but you’ll encounter them in older code.

%-formatting (C-style)#

V = 0.0245
print("Volume: %.4f m3" % V)

Output: Volume: 0.0245 m3

.format() method#

V = 0.0245
print("Volume: {:.4f} m3".format(V))

Output: Volume: 0.0245 m3

Tip

Use f-strings for new code. They’re easier to read and less error-prone.


Common Mistakes#

Forgetting the f#

T = 300
print("Temperature is {T}")   # WRONG: prints literally "{T}"
print(f"Temperature is {T}")  # CORRECT: prints "Temperature is 300"

Using wrong quotes#

# If your string contains quotes, use the other type
print(f"It's {T} Kelvin")     # Single quote inside double quotes: OK
print(f'Temperature: {T} K')  # No quotes inside: OK

Quick Reference#

Format

Syntax

Example

Output

Basic f-string

f"{var}"

f"T = {T}"

T = 298.15

Decimal places

{var:.Nf}

f"{3.14159:.2f}"

3.14

Scientific

{var:.Ne}

f"{6.022e23:.2e}"

6.02e+23

Integer

{var:d}

f"{42:d}"

42

Width (right-align)

{var:>N}

f"{42:>5}"

   42

Width (left-align)

{var:<N}

f"{42:<5}"

42  

Zero-pad

{var:0N}

f"{42:05}"

00042

Combined

{var:N.Mf}

f"{3.14159:8.2f}"

    3.14

Next Steps#

Continue to Control Flow to learn about conditionals and loops.