Getting Started with Python
Operators
Predict the result of each kind of operator.
Operators carry out operations on values.
Arithmetic operators, with a = 17 and b = 5:
- + adds (a + b is 22); it also joins strings: 'Good' + 'Day' is 'GoodDay'.
- - subtracts (a - b is 12).
- * multiplies (a * b is 85); it also repeats a string: 'Hi' * 3 is 'HiHiHi'.
- / divides, and always gives a float: 9 / 3 is 3.0.
- % gives the remainder: 17 % 5 is 2.
- // is floor division, dropping the fraction: 17 // 5 is 3.
The power (exponent) operator is written with two stars: 2 ** 5 means 2 to the power 5, which is 32.
Relational operators compare values and give True or False: == (equal), != (not equal), >, <, >= and <=. For example, 10 < 100 is True. Strings are compared character by character, using their character codes, so 'Mango' > 'Apple' is True (M comes after A).
Assignment operators: = gives a value; the shortcuts +=, -=, *=, /=, %= and //= combine an operation with assignment: x += 3 means x = x + 3.
Logical operators: and, or, not (always in small letters). In a condition, every value counts as True, except None, False, 0 and empty collections ('', (), [], {}). So not 0 is True.
Identity operators, is and is not, check whether two names refer to the same object: type(a) is int is True when a holds a whole number. Membership operators, in and not in, check whether a value is inside a collection: 6 in [5, 6, 7] is True, but '5' in [5, 6, 7] is False, because the string '5' is not the number 5.
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.