Lesson 4 of 12
Do maths with + - * / and %, join text with +, and use handy functions like round, upper and length. Every example runs in your browser.
About 6 minutes · 3 parts, each with a program to try
Part 1 of 3
+ adds, - takes away, * multiplies and / divides. % gives the remainder after dividing.
floor(x) rounds down to a whole number, handy for sharing things out.
sweets = 17friends = 5"Each gets " + floor(sweets / friends)"Left over: " + sweets % friendsEach gets 3Left over: 2import math
def remainder_of(a, b): # Like % in B4Coder: the remainder has the sign of a, so -7 % 3 is -1 (Python's % gives 2). r = abs(a) % abs(b) return -r if a < 0 else r
sweets = 17friends = 5print("Each gets " + str(math.floor(sweets / friends)))print("Left over: " + str(remainder_of(sweets, friends)))Part 2 of 3
Once there are words at the start, every + joins text. "Sum: " + 4 + 5 shows Sum: 45.
Put the maths in brackets to do it first: "Sum: " + (4 + 5) shows Sum: 9.
ab"The sum is " + (a + b)45It showsThe sum is 9a = int(input("First number? "))b = int(input("Second number? "))print("The sum is " + str(a + b))Part 3 of 3
A function does a job and gives back the answer. upper(word) gives the word in capitals, length(word) counts its letters, round(3.7) gives 4.
See them all on Symbols and functions.
word = "banana"upper(word)length(word)round(3.7)BANANA64import math
def round_half_up(x, digits=0): # Like round() in B4Coder: a half goes up, so 2.5 is 3 (Python's round() gives 2). scale = 10 ** digits whole = math.floor(x * scale) if x * scale - whole >= 0.5: whole += 1 return whole if digits == 0 else whole / scale
word = "banana"print(word.upper())print(len(word))print(round_half_up(3.7))Quick check