Let’s Do Some Calculations with Python
In this chapter, the theme is calculations.
Basic Arithmetic Operations
In Python, you can perform basic arithmetic operations as shown below.
From top to bottom: addition, subtraction, multiplication (*), and division (/).
# Simple calculations
print(1 + 2) # Result: 3
print(4 - 3) # Result: 1
print(5 * 6) # Result: 30
print(8 / 4) # Result: 2.0 (division results in a floating-point number)
Multiplication and division are executed before addition and subtraction.
You can use parentheses ( and ) to control the order of operations.
# Slightly more complex calculations
print(1 + 2 * 3) # Result: 7
print((1 + 2) * 3) # Result: 9
By writing * twice, you can calculate powers (exponentiation).
# Exponentiation
print(2 ** 2) # 2 squared = Result: 4
print(2 ** 3) # 2 cubed = Result: 8
print(2 ** 4) # 2 to the 4th power = Result: 16
About Comments
By writing # in your code, you can leave notes called comments.
In Python, everything after # on the same line is treated as a comment and is ignored when the program runs.
Comments are often used as reminders or explanations.
(When you look at the code later, you’ll be able to remember what it does!)
print("Hello, Python!!") # Command to display text
When you want to write comments across multiple lines, you can use triple quotes (""").
"""
The code below
displays a string.
This is a very important piece of code!!
"""
print("Hello, Python!!")
As you continue writing code, try to actively leave comments about what you notice or learn.
(Some people even write their thoughts or complaints in comments... 😄)
Coming Up Next...
Thank you very much for reading!
The next chapter is titled “Working with Strings”.
Stay tuned!
Top comments (0)