Brief Overview of Python
Operators and expressions
Evaluate an expression step by step.
An operator performs an operation on values called operands: in 10 + num, 10 and num are operands and + is the operator.
Arithmetic operators: + (add), - (subtract), * (multiply), / (divide, giving the quotient as a float: 5 / 2 is 2.5), % (modulus, the remainder: 13 % 5 is 3), // (floor division, dropping the decimal part: 5 // 2 is 2, 2 // 5 is 0), and the power operator, written as two asterisks (3 to the power 4 is 81).
- With strings, + joins them ('Hello' + 'India' gives 'HelloIndia') and * repeats a string a whole number of times ('India' * 2 gives 'IndiaIndia'). These work similarly for lists and tuples.
Relational operators compare and give True or False: == (equal), != (not equal), >, <, >=, <=. Strings are compared character by character using the characters' ASCII values, so 'Good' > 'Afternoon' is True (G comes after A).
Assignment operators: = assigns the right side to the left; += adds and assigns (x += y means x = x + y), -= subtracts and assigns, and there are similar shortcuts for multiply, divide, modulus, floor division and power (*=, /=, %=, //= and the two-asterisk version).
Logical operators (always lower case): and (True only if both sides are True), or (True if either side is True), not (reverses True and False).
Membership operators: in is True if a value is found in a sequence; not in is True if it is not. With numSeq = [1, 2, 3], 2 in numSeq is True, but '1' in numSeq is False, because '1' is a string and the list holds the number 1.
Expressions combine constants, variables and operators and always give a value; a lone value or variable is also an expression, but a lone operator is not.
Precedence (which operator goes first): brackets first, then the power operator, then multiply, divide, modulus and floor division, then add and subtract. Operators of equal precedence go left to right. So 20 + 30 * 40 is 1220, but (20 + 30) * 40 is 2000; and 15.0 / 4.0 + (8 + 3.0) is 3.75 + 11.0 = 14.75.
Example (new): 17 // 5 + 17 % 5 * 2 works out as 3 + 2 * 2 = 3 + 4 = 7: floor division and modulus first, then the multiplication, then the addition.
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.