Remember
divmod(a, b) returns a pair containing the floor quotient and remainder. The divisor must be nonzero.
divmod(a, b) returns a pair containing the floor quotient and remainder. The divisor must be nonzero.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
number = 7
print(divmod(number, 2))Top-level scope
7divmod(a, b) returns a pair containing the floor quotient and remainder. The divisor must be nonzero.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
number = 7
print(divmod(number, 2))
|
v
DISPLAYED RESULT
(3, 1)
FINAL BINDINGS
number --> object 1 (int)
object 1: 7Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
number = 7
print(divmod(number, 2))Top-level scope
7The example has finished. Compare the final output with the values and references above.
(3, 1)
What do you expect this program to print?
number = 7
print(divmod(number, 2))divmod() FunctionThe divmod() function in Python returns a tuple containing the quotient and the remainder when dividing two numbers. It's a quick way to get both results in one line.
divmod(a, b)
a – The dividend (numerator)b – The divisor (denominator); must not be 0(quotient, remainder)result = divmod(10, 3)
print(result)
(3, 1)
Why? Because 10 ÷ 3 = 3 with a remainder of 1.
q, r = divmod(22, 5)
print("Quotient:", q)
print("Remainder:", r)
Quotient: 4
Remainder: 2
print(divmod(7.5, 2.5))
(3.0, 0.0)
ZeroDivisionErrorIn coding interviews, divmod() can simplify logic in problems involving floor division and modulo operations.
divmod(a, b) returns (a // b, a % b)Write a program that reads two integers from the user and prints their quotient and remainder using divmod().
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
q, r = divmod(a, b)
print("Quotient:", q)
print("Remainder:", r)
Connect what you noticed in the example with the idea below.
divmod(a, b) returns a pair containing the floor quotient and remainder. The divisor must be nonzero.
divmod() returns only the true-division result.
This is the misconception to avoid.Reference checks are optional and do not count toward course progress.