An expression combines values, variables, and operators. Programs use expressions to calculate, join, compare, and update data.
Arithmetic operators
Python supports common arithmetic operations, plus a few operators that are especially useful in programming.
The floor-division operator // returns the integer part of a division result.
print(21 // 4) # 5The modulo operator % returns the remainder after integer division.
print(22 % 3) # 1
print(4 % 7) # 4KNOWLEDGE QUIZ
Reversing a three-digit integer
Floor division and modulo are often used together to split an integer into digits.
num = int(input("Enter a 3-digit integer: "))
a = num // 100
b = num // 10 % 10
c = num % 10
print("Reversed:", c * 100 + b * 10 + a)One possible run:
Enter a 3-digit integer: 520
Reversed: 25The result is displayed as 25 because the reversed number is 025, and leading zeros are not shown when printing an integer.
KNOWLEDGE QUIZ
Compound operators
Compound operators make variable updates shorter.
a += bmeansa = a + ba -= bmeansa = a - ba *= bmeansa = a * ba /= bmeansa = a / ba %= bmeansa = a % b
String concatenation
+ is not only for numbers. It can also join strings.
s = "Hello" + "World"
s += "!"
print(s)Output:
HelloWorld!KNOWLEDGE QUIZ
Split total seconds into hours, minutes, and seconds
Break a total number of seconds into hours, minutes, and leftover seconds. It is a good way to reinforce // and % together.
- Read an integer named total_seconds.
- Use floor division and modulo to compute hours, minutes, and seconds.
- Print the result in a format such as “3661 seconds = 1 hour 1 minute 1 second”.