1.4 Expressions and Operators
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.
python
print(21 // 4) # 5The modulo operator % returns the remainder after integer division.
python
print(22 % 3) # 1
print(4 % 7) # 4Loading concept check...
Reversing a three-digit integer
Floor division and modulo are often used together to split an integer into digits.
python
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:
text
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.
Loading concept check...
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.
python
s = "Hello" + "World"
s += "!"
print(s)Output:
text
HelloWorld!Loading concept check...
Loading practice...