Python / Getting started

Your first program: print and comments

Print text, numbers and calculation results, tell text from numbers, and leave comments with #. Baccalaureate

In Python you print with print, putting the text in quotes inside brackets. Try it:

Python
print("Hello")
print("Good morning")
Console
Hello
Good morning

To print the result of a calculation, write it without quotes; anything inside quotes is printed exactly as written:

Python
print("5+2")
print(5+2)
print(7*6)
print(48/6)
Console
5+2
7
42
8.0
OperationSymbolExampleResult
Add+278+422700
Subtract-3000-8502150
Multiply*7*642
Divide/48/68.0
Division / in Python always gives a decimal: 48/6 = 8.0.

Joining text and numbers

You join texts with +, but you cannot join text and a number directly. Turn the number into text first with str():

Python
print("2 crepes " + 350 * 2)
Console
TypeError: can only concatenate str (not "int") to str
Python
print("2 crepes " + str(350 * 2) + " pounds")
Console
2 crepes 700 pounds

Comments

A line that starts with # is a comment the computer ignores; use it for notes or to switch a line off.

Python
# Groceries
print("Bread")
# print("Grapes")
print("Yogurt")
Console
Bread
Yogurt

Practice

1Write the programCurriculum practice

Print Good night.

Python Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Console
Press Run to see the result.
2Edit the programCurriculum practice

Fix the program so it prints Let's do our best.

HintUse double quotes " because the text contains '.
Python Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
print(Let's do our best)
Console
Press Run to see the result.
3Write the programCurriculum practice

Make the computer calculate 1200 + 2800 and print the result.

Python Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Console
Press Run to see the result.
4Fill in the blankCurriculum practice

Fill in the blank to print 3 crepes 1050 pounds (350 × 3).

Python Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
print("3 crepes " + ___ + " pounds")
Console
Press Run to see the result.
5Edit the programCurriculum practice

Turn the line that prints Fish into a comment.

Python Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
print("Mercury")
print("Fish")
print("Venus")
Console
Press Run to see the result.
6Write the programExtra practice

A plate of koshary costs 45 pounds. Print Total: 135 for three plates, and let the computer calculate 45 × 3.

Python Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Console
Press Run to see the result.

Key points

  • print("text") prints text; print(5+2) prints the result.
  • Operators: + - * /; division gives a decimal.
  • str() turns a number into text before joining with +; # starts a comment.