Getting Started with Python
Expressions, statements, input and output
Evaluate an expression step by step.
An expression is a combination of values, variables and operators that always evaluates to a single value. A value or a variable on its own is also an expression (5, or total).
When an expression has several operators, Python follows an order of precedence:
- the power operator first;
- then unary minus and plus (as in -5);
- then *, /, % and //;
- then + and -;
- then the comparisons;
- then not, then and, then or.
Operators of equal precedence are worked out from left to right. Brackets override everything: what is inside them is done first.
- 5 + 4 * 3 = 5 + 12 = 17 (multiplication first).
- (5 + 4) * 3 = 9 * 3 = 27 (brackets first).
- 10 - 4 + 2 = 6 + 2 = 8 (left to right).
A statement is a unit of code that the interpreter can execute, such as x = 7 or print(x).
Input: input([prompt]) shows the prompt, waits for the user to type something, and returns it as a string, even if the user types digits. So type(input()) is always str. To use the input as a number, convert it: age = int(input('Enter age: ')).
Output: print(value, ..., sep=' ', end='\n') prints the values, separated by sep (a space by default), and finishes with end (a new line by default). For example, print('a', 'b', sep=':') prints a:b. Joining strings with + puts no space between them; separating them with a comma in print adds a space.
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.