7B: Math
Source: https://cscircles.cemc.uwaterloo.ca/7b-math/ Parent: https://cscircles.cemc.uwaterloo.ca/
Lesson 7 has three parts A, B, C which can be completed in any order.
So far, we have performed math calculations using Python's operators +, -, *, / and the functions max and min. In this lesson we will see some more operators and functions and learn how to perform more complex calculations.
Math Operators
We have already seen how to use operators for addition (a + b), subtraction (a - b), multiplication (a * b) and division (a / b). We will now learn about three additional operators.
- The power operator
a ** bcomputesab(amultiplied by itselfbtimes). For example,2 ** 3produces8(which is 2×2×2). - The integer division operator
a // bcomputes the "quotient" ofadivided byband ignores the remainder. For example,14 // 3produces4. - The modulus operator
a % bcomputes the remainder whenais divided byb. For example,14 % 3produces2.
Example
The power, integer division, and modulus operators
print(2 ** 3) print(14 // 3) print(14 % 3)
Coding Exercise: Eggsactly
Egg cartons each hold exactly 12 eggs. Write a program which reads an integer number of eggs from input(), then prints out two numbers: how many cartons can be filled by these eggs, and how many eggs will be left over. For example, the output corresponding to 27 eggs is
2\
3
since 27 eggs fill 2 cartons, leaving 3 eggs left over. Hint
You need to create an account and log in to ask a question.
delete this comment and enter your code here
You may enter input for the program in the box below.
More actions... History Help
The modulus operator is used for a variety of tasks. It can be used to answer questions like these ones:
- If the time now is 10 o'clock, what will be the time 100 hours from now? (requires modulus by 12)
- Will the year 2032 be a leap year? (requires modulus by 4, 100, and 400)
Checking leap years is an example of divisibility testing; in the next exercise we ask you to write a program that performs divisibility testing in general.
Coding Exercise: Divisibility
Write a program that reads two positive integers a and b on separate lines. If a is divisible by b, print the message "divisible". Otherwise, print the message "not divisible". For example, when the input is
14\
3
the program should print "not divisible". Hint
You need to create an account and log in to ask a question.
delete this comment and enter your code here
You may enter input for the program in the box below.
More actions... History Help