Python course menu
Your First Python Program: print(), Strings and Running Code
Write and run your first Python program. Learn how print() works, how to show text and numbers, print several values, use sep and end, special characters like \n, and read your first error message.
On this page
Every programmer's journey starts with a program that displays a message. In Python, that takes a single line. In this lesson you will write it, understand exactly what each part does, and learn how to read the error Python shows you when something goes wrong.
Hello, world!#
Create a file called hello.py and type:
print("Hello, world!")Run it with python hello.py:
Hello, world!That's a complete program. Let's break it down:
Several lines#
Python runs your file from top to bottom, one line at a time:
print("Welcome to Laviyx Learn")
print("Let's learn Python")
print(2 + 3)Welcome to Laviyx Learn
Let's learn Python
5Notice the last line: 2 + 3 is not in quotes, so Python calculates it and prints the result. "2 + 3" in quotes would print the text exactly as written.
Printing several values#
Separate values with commas. print puts a space between them:
print("Name:", "Asha", "| Age:", 21)Name: Asha | Age: 21You can mix text and numbers this way without converting anything.
sep and end#
print has two useful options:
sepsets what goes between values (default: a space).endsets what goes after the last value (default: a new line).
print("a", "b", "c", sep="-")
print("Loading", end="...")
print("done")a-b-c
Loading...doneBecause the second print ended with "..." instead of a new line, the third print continued on the same line.
Quotes and special characters#
Strings can use single or double quotes. Use one kind outside when the text contains the other:
print('He said "hi"')
print("It's fine")
print("Line one\nLine two")
print("Tab\tseparated")He said "hi"
It's fine
Line one
Line two
Tab separated\n means new line and \t means tab. These backslash combinations are called escape sequences.
An empty print() prints a blank line, which is handy for spacing out output.
Your first error#
Mistakes are normal; reading error messages is a core programming skill. Leave out the closing parenthesis:
print("Hello" File "hello.py", line 1
print("Hello"
^
SyntaxError: '(' was never closedPython tells you:
- Where: the file and line number.
- What: a
SyntaxError, meaning the code breaks Python's grammar rules. - Why: the
(was never closed. The^points at the problem.
Read error messages from the bottom up: the last line is the most important one.
Common mistakes#
Practice#
Practice exercise
Write a program that prints this exactly, using three print calls and the sep option at least once:
=== Receipt ===
Notebook-3-180
Thank you!Show hint
print("Notebook", 3, 180, sep="-") prints the middle line.
Show solution
print("=== Receipt ===")
print("Notebook", 3, 180, sep="-")
print("Thank you!")=== Receipt ===
Notebook-3-180
Thank you!Key takeaway#
Finished this lesson?