print() FunctionThe most fundamental function in Python is print(). It displays text or values on the screen. To print a message, place it inside quotation marks within the parentheses:
print("Hello world")
print('Learning Python is fun!')
You can use either single quotes '...' or double quotes "..." — both work the same way.
print()Beginners often make small errors. Can you spot what is wrong in each of the following lines?
print(hello world)Missing quotation marks around the text. The correct version is:
print("hello world")
(print"how tall are you?")The parentheses are in the wrong place, and there is no opening parenthesis for print. The correct version is:
print("how tall are you?")
('Game Over')The print function name is missing entirely. The correct version is:
print('Game Over')
print('Game Over")Mismatched quotes — starts with a single quote but ends with a double quote. The correct version is:
print('Game Over')
pprint('Bob's car has 4 wheels')Two errors: pprint should be print, and the apostrophe in Bob's closes the string early. The correct version is:
print("Bob's car has 4 wheels")
Python can perform arithmetic directly. The basic operators are:
| Operator | Operation | Example | Result |
|---|---|---|---|
+ | Addition | 2 + 3 | 5 |
- | Subtraction | 10 - 4 | 6 |
* | Multiplication | 3 * 5 | 15 |
/ | Division | 10 / 4 | 2.5 |
You can use print() to display the result of calculations:
print(2 + 3)
print(10 * 10)
print(45 / 3)
5, 10, 1231.1, 0.5, 2.99When you divide two integers, Python always returns a float:
>>> 10 / 2
5.0
>>> 10 / 3
3.3333333333333335
What are the results of the following expressions?
12 * 12144
2 + 5.67.6
15 / (1.5 * 3)3.3333333333333335