Lesson 6 +10 XP

Output with print

print() is Python's way of showing things on the screen. You'll use it constantly.

Print text

Code

python
print("Hello, World!")

Print numbers

Code

python
print(42)
print(3.14)

Print several things at once

Separate values with commas. Python adds a space between them.

Code

python
print("Hello", "world", "again")

### Hello world again

Combine strings with +

You can glue strings together with +:

Code

python
print("Hello " + "world")

### Hello world

But you can't mix a string and a number with +:

Code

python
print("The answer is " + 42)

TypeError!

Fix it with str() or a comma:

Code

python
print("The answer is " + str(42))
print("The answer is", 42)

The end parameter

By default print ends with a newline. You can change it:

Code

python
print("Hello", end=" ")
print("World")

### Hello World

The sep parameter

Change the separator between values:

Code

python
print("a", "b", "c", sep="-")

### a-b-c

TL;DR

  • print(value) shows a value.
  • Commas add spaces; + glues strings.
  • Use str() to turn numbers into strings.
  • end and sep fine-tune the output.