Arithmetic operators

Two operators divide, and they give different answers

7 / 23.5true division: always a float7 // 23floor division: rounds down7 % 21modulo: the remainder-7 // 2-4down means towards minus infinity2 ** 38power: 2 × 2 × 27.0 // 23.0one float in, a float outTwo operators divide, and they give different answers.A single slash keeps the fraction and always gives a float, even for 6 / 2. A double slashthrows the fraction away by rounding down, which for a negative number means further from zero.

/ gives a float. // rounds down. % is the remainder.

Arithmetic operators · Going deeper

Result types, and strings

ExpressionGivesRule3 + 4, 3 * 47, 12int with int gives int3 + 4.07.0A float anywhere makes the result a float6 / 23.0Except /, which gives a float every time-7 % 2, 7 % -21, -1A remainder takes the sign of the right side'ab' + 'cd''abcd'+ joins two strings'ab' * 3'ababab'* repeats a string'ab' + 1TypeErrorA string and a number do not addThe same symbol does different jobs for different types.+ adds numbers and joins strings. * multiplies numbers and repeats strings.

A float spreads. + joins strings, * repeats them.

Precedence

Power first, then multiply and divide, then add

2 + 3 * 4 ** 2the expression2 + 3 * 16** first: 4 ** 2 is 162 + 48then *: 3 * 16 is 4850then +Power first, then multiply and divide, then add and subtract.Python does not work left to right. It works by rank, and only then left to right amongoperators of the same rank. Brackets override everything: (2 + 3) * 4 is 20.

**, then * / // %, then + -.

Precedence · Going deeper · 1 of 2

The full ranking

RankOperatorsSame rank bindsExample1( )(2 + 3) * 4 is 202**right to left2 ** 3 ** 2 is 2 ** 9, 5123+x -x (unary)-2 ** 2 is -(2 ** 2), -44* / // %left to right8 / 4 / 2 is 1.05+ -left to right10 - 4 - 3 is 36== != < <= > >=1 + 2 == 3 is True7notnot True or True is True8andleft to right9orleft to rightTrue or False and False is TrueA unary operator has one operand: -x. A binary operator has two: x - y.Only ** binds right to left. That, and -2 ** 2, are the two rank questions the exam likes.

** binds right to left. not, and, or come last.

Precedence · Going deeper · 2 of 2

Augmented assignment

Statement, from x = 10Meansx becomesx += 3x = x + 313x -= 3x = x - 37x *= 3x = x * 330x /= 4x = x / 42.5x //= 4x = x // 42x %= 4x = x % 42x **= 2x = x ** 2100An augmented assignment is a shorter way to write "x = x, operator, value".x /= 4 makes x a float, because / always does. There is no x++ in Python.

x += 3 means x = x + 3.

Check yourself

x = 2 + 3 * 2 ** 2print(x)

What does this print?

Comparison and Boolean operators

A comparison gives True or False. and, or, not combine.

age = 20has_id = Falseage >= 18 and has_idand: bothTrue and FalseFalseage >= 18 or has_idor: one is enoughTrue or FalseTrueA comparison gives True or False. and, or and not combine them.and is True only when both sides are. or is True when at least one is. not turns Trueinto False. Comparisons are worked out before not, not before and, and and before or.

and: both. or: at least one. not: the opposite.

Comparison and Boolean operators · Going deeper

Comparisons and the truth table

OperatorAsksExample==equal?3 == 3.0 is True; '3' == 3 is False!=not equal?3 != 4 is True> >=greater? greater or equal?5 >= 5 is True< <=less? less or equal?'a' < 'b' is True: strings compare by letteraba and ba or bnot aTrueTrueTrueTrueFalseTrueFalseFalseTrueFalseFalseTrueFalseTrueTrueFalseFalseFalseFalseTrue= assigns and == compares. A string never equals a number.

== compares. A str never equals a number.

Console input

input() always returns a string

The user types 20age = input('Age: ')print(age + 1)age is '20', a strTypeError: text and a number do not addThe user types 20age = int(input('Age: '))print(age + 1)age is 20, an intprints 21input() always returns a string.It shows the prompt, waits for the user to press Enter, and gives back what was typed astext, digits included. Convert it before you do arithmetic: int() for whole numbers,float() for the rest.

input() gives a str. Wrap it in int().

Console input · Going deeper

What print() prints

CodeOutputprint('a', 'b', 3)a b 3print('a' + 'b')abprint('a', 'b', sep='-')a-bprint('a', end='!') print('b')a!bprint()(an empty line)print('7' * 2)77print() puts a space between its arguments and a new line at the end.sep= changes what goes between the arguments. end= changes what goes after the last one.Both are covered again with functions in lesson 10.

A space between, a new line after.

Check yourself

x = input()print(x * 2)

The user types 5. What is printed?

Type conversion

int() cuts. It does not round.

int(4.9)4cuts off the fraction; does not roundint('42')42text of a whole numberint('4.2')ValueErrortext with a point is not an intfloat('4')4.0text or an int, to a floatstr(4) + '2''42'a number to text, then joinedint() cuts. It does not round.int(4.9) is 4 and int(-4.9) is -4: the fraction is dropped. int() reads text only when thetext is a whole number. For '4.2' go through float first: int(float('4.2')) is 4.

int(), float(), str(). Bad text: ValueError.

Type conversion · Going deeper

What converts to what

Fromint( )float( )str( )'42'4242.0'42''4.2'ValueError4.2'4.2''abc'ValueErrorValueError'abc'4.944.9'4.9'True11.0'True'A conversion that cannot be done raises a ValueError when the line runs.So a program that reads a number with int(input()) stops if the user types a word.Lesson 11 shows how to catch that.

What cannot convert raises ValueError.

Check yourself

a = int('7')b = float(a)print(a / 2, b // 2)

What does this print?

Lesson complete

You finished “Operators, input and output”

Answer the questions along the way to see your score here.

Open in a new tab