Python divmod() Built in Function
The divmod() function in Python is used to find the quotient and remainder of dividing two numbers. The divmod() function takes two numbers as arguments and returns a tuple containing the quotient and remainder as (quotient, remainder). The numbers can be integers or floats, but they must be non-complex. Here are some examples of using divmod() in Python:
Divide two numbers and get the quotient and remainder:
>>> divmod(10, 3)
(3, 1)
In this example, divmod(10, 3) divides 10 by 3, and returns a tuple containing the quotient 3 and the remainder 1.
Calculate the number of hours and minutes in a given number of minutes:
>>> total_minutes = 135
>>> hours, minutes = divmod(total_minutes, 60)
>>> print(hours, "hours", minutes, "minutes")
2 hours 15 minutes
In this example, we start with a total number of minutes (135) and use divmod(total_minutes, 60) to calculate the number of hours and minutes. The divmod() function returns a tuple containing the quotient (2) and the remainder (15), which we then assign to the variables hours and minutes, respectively. Finally, we print the result in a human-readable format.
Use divmod() to calculate the number of pages and the remaining lines on the last page when printing a book with a given number of lines:
>>> num_lines = 1001
>>> lines_per_page = 25
>>> num_pages, remaining_lines = divmod(num_lines, lines_per_page)
>>> print(num_pages, "pages with", remaining_lines, "lines")
40 pages with 1 lines
In this example, we start with a total number of lines (1001) and a specified number of lines per page (25). We use divmod(num_lines, lines_per_page) to calculate the number of pages and the remaining lines. The divmod() function returns a tuple containing the quotient (40) and the remainder (1), which we then assign to the variables num_pages and remaining_lines, respectively. Finally, we print the result in a human-readable format.
Some more examples:
# Divide two integers
x = 10
y = 3
result = divmod(x, y)
print(result) # Output: (3, 1)
# Divide two floats
x = 7.5
y = 2.5
result = divmod(x, y)
print(result) # Output: (3.0, 0.0)
# Divide a float by an integer
x = 8.0
y = 3
result = divmod(x, y)
print(result) # Output: (2.0, 2.0)
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment