Beginner âĸ Python
Operators
â Arithmetic Operators
Arithmetic operators allow Python to perform mathematical calculations. The main operators are + for addition, - for subtraction, * for multiplication, and / for division.
print(10 + 5)
print(10 - 5)
print(10 * 5)
print(10 / 5)15 5 50 2.0
đ Everything in Operators
Learn how Python performs calculations and comparisons. Here is every step in this topic in one place, so you can review what you learned or jump straight to a step.
â Arithmetic Operators
Arithmetic operators allow Python to perform mathematical calculations. The main operators are + for addition, - for subtraction, * for multiplication, and / for division.
print(10 + 5) print(10 - 5) print(10 * 5) print(10 / 5)âī¸ Comparison Operators
Comparison operators compare values and return True or False. Common comparison operators include >, <, ==, >=, <=, and !=.
print(10 > 5) print(10 < 5) print(10 == 10) print(10 != 5)đ§Ž Using Operators with Variables
Operators can also be used with variables. This allows programs to perform calculations using values stored in variables.
apples = 5 oranges = 3 total = apples + oranges print(total)đ° Remainder with %
The % operator gives us the remainder after division. For example, 10 divided by 3 has a remainder of 1. The remainder operator is useful for problems such as checking whether a number is even or odd.
print(10 % 3) print(8 % 2) print(7 % 2)⥠Assignment Shortcuts
Programs often need to change a variable by adding or taking away a number, such as when a player scores points. Python has handy shortcuts for this. score += 5 means the same as score = score + 5, and score -= 3 means the same as score = score - 3.
score = 10 score += 5 print(score) score -= 3 print(score)đ Powers and Floor Division
The ** operator raises a number to a power. For example, 2 ** 3 means 2 * 2 * 2. The // operator is called floor division. It divides two numbers and gives a whole number answer by throwing away anything after the decimal point.
print(2 ** 3) print(5 ** 2) print(7 // 2) print(10 // 3)đ§ Order of Operations
When a calculation has more than one operator, Python follows the same rules as in maths class. Multiplication and division happen before addition and subtraction. If we want Python to do a part of the calculation first, we can put it inside brackets ().
print(2 + 3 * 4) print((2 + 3) * 4) print(10 - 4 / 2)đ Logical Operators: and, or, not
Logical operators let us combine True and False values. and gives True only when both sides are True. or gives True when at least one side is True. not flips a value, so True becomes False and False becomes True.
age = 12 has_ticket = True print(age >= 10 and has_ticket) print(age < 5 or has_ticket) print(not has_ticket)
