Python
/
Functions
- 1 Language 9
-
Hello World S
-
Variables S
-
Functions S
-
Conditional A S
-
Operators S
-
While S
-
Turtle S
-
Script Mode S
-
Debugging S
- 2 Strings 7
-
Slice S
-
Raw Strings S
-
Regex A S
-
Validation S
-
Config S
-
Security S
-
Encrypt A S
- 3 Collections 5
-
Lists S
-
Dictionaries S
-
Efficiency S
-
Tuples S
-
References S
- 4 Functions 5
-
Recursion S
-
Factorial S
-
Modulus S
-
Reassignment S
-
Approximate S
- 5 Storage 8
-
Files S
-
Databases S
-
Pipes S
-
With open S
-
Shelve A S
-
Zip S
-
Csv S
-
Json S
- 6 Class 4
-
Definition S
-
Attributes S
-
Functional S
-
Methods S
- 7 Goodies 5
-
Conditional Expression S
-
List Comprehension A S
-
Generator S
-
Named Tuple S
-
Modules S
- 8 Applications 5
-
Pythagora A S
-
Palindrome A S
-
Binary Search A S
-
Conway Game A S
-
Coin Flip A S
- 9 Scheduler 4
-
Time S
-
Multithreading A S
-
Subprocess S
-
Logging S
- 10 Packages 6
-
Clipboard A S
-
Ocr A S
-
Socket S
-
Image S
-
Virtualenv S
-
Jupyter S
S
R
Q
Python Functions Modulus
In Python integer division returns floor division Modulus always return a number with the same sign 25 % 7 == 4 # 25//7 = 3 reminder 4 3 % 7 == 3 # 3 -3 % 7 == 4 # 4
Positive
p103 In Python integer division always return floor division.
"""Modulus operation
Python always does floor division
dividend % divisor = reminder
"""
assert 0 % 7 == 0
assert 1 % 7 == 1
assert 3 % 7 == 3 # 3//7 = 0 reminder 3
assert 7 % 7 == 0
assert 8 % 7 == 1
assert 9 % 7 == 2
assert 25 % 7 == 4
assert 7 % 25 == 7 # 7//25 = 0 reminder 7
print('Tests passed')
Negative
Python modulus always return a number with the same sign as the denominator.
"""Modulus with negative numbers
In Python (%) returns same sign as the denominator
23 = 4*5 + 3 # reminder 3
23 = -5* 5 - 2 # reminder -2
-3 = -1*7 + 4 # remainder 4
Python applies distribute law of Modulo
(a + b) mod n = ((a mod n) + (b mod n)) mod n
(2 + 2) % 3 = (2%3 + 2%3) % 3 = 1
"""
assert (2 + 2) % 3 == 1 # distribute law of Modulo
assert (2 + 2) % 3 == (2%3 + 2%3) % 3 == 1
assert (2 + 2) % 3 != 2%3 + 2%3
assert 23 % 5 == 3 # reminder 3
assert 23 % -5 == -2 # same sign as denominator
assert -3 % 7 == 4
assert 23 // 5 == 4 # floor division
assert 23 // -5 == -5
assert -3 // 7 == -1
print('Tests passed')
➥ Questions
Last update: 117 days ago