Задача: Напишите простой калькулятор, который считывает с пользовательского ввода три строки: первое число, второе число и операцию, после чего применяет операцию к введённым числам («первое число» «операция» «второе число») и выводит результат на экран.
Поддерживаемые операции: +, -, /, *, mod, pow, div, где
mod — это взятие остатка от деления,
pow — возведение в степень,
div — целочисленное деление.
Проблема: При операциях с нулем возвращает:
Traceback (most recent call last):
File «jailed_code», line 9, in
print(n1 % n2)
ZeroDivisionError: float modulo
Мой код:
n1 = float(input())
n2 = float(input()
o = str(input())
if o == 'mod':
if (n1 or n2) == 0.0:
print("Деление на 0!")
else:
print(n1%n2)
elif o == 'div':
if (n1 or n2) == 0.0:
print("Деление на 0!")
else:
print(n1//n2)
elif o == '/':
if (n1 or n2) == 0.0:
print("Деление на 0!")
else:
print(n1/n2)
elif o == '*':
print(n1 * n2)
elif o == '+':
print(n1 + n2)
elif o == '-':
print(n1 - n2)
elif o == 'pow':
print(n1 ** n2)
else:
print('Something was wrong')
The divmod() method in python takes two numbers and returns a pair of numbers consisting of their quotient and remainder.
Syntax :
divmod(x, y) x and y : x is numerator and y is denominator x and y must be non complex
Examples:
Input : x = 9, y = 3 Output :(3, 0) Input : x = 8, y = 3 Output :(2, 2)
Explanation: The divmod() method takes two parameters x and y, where x is treated as numerator and y is treated as the denominator. The method calculates both x // y and x % y and returns both the values.
- If x and y are integers, the return value is
(x // y, x % y)
- If x or y is a float, the result is
(q, x % y), where q is the whole part of the quotient.
Python3
print('(5, 4) = ', divmod(5, 4))
print('(10, 16) = ', divmod(10, 16))
print('(11, 11) = ', divmod(11, 11))
print('(15, 13) = ', divmod(15, 13))
print('(8.0, 3) = ', divmod(8.0, 3))
print('(3, 8.0) = ', divmod(3, 8.0))
print('(7.5, 2.5) = ', divmod(7.5, 2.5))
print('(2.6, 10.7) = ', divmod(2.6, 0.5))
Output:
(5, 4) = (1, 1) (10, 16) = (0, 10) (11, 11) = (1, 0) (15, 13) = (1, 2) (6.0, 5) = (2.0, 2.0) (3, 9.0) = (0.0, 3.0) (13.5, 6.2) = (3.0, 0.0) (1.6, 10.7) = (5.0, 0.10000000000000009)
Errors And Exceptions
- If either of the arguments (say x and y), is a float, the result is (q, x%y). Here, q is the whole part of the quotient.
- If the second argument is 0, it returns Zero Division Error
- If the first argument is 0, it returns (0, 0)
Practical Application: Check if a number is prime or not using divmod() function.
Examples:
Input : n = 7 Output :Prime Input : n = 15 Output :Not Prime
Algorithm
- Initialise a new variable, say x with the given integer and a variable counter to 0
- Run a loop till the given integer becomes 0 and keep decrementing it.
- Save the value returned by divmod(n, x) in two variables, say p and q
- Check if q is 0, this will imply that n is perfectly divisible by x, and hence increment the counter value
- Check if the counter value is greater than 2, if yes, the number is not prime, else it is prime
PYTHON3
n = 15
x = n
count = 0
while x != 0:
p, q = divmod(n, x)
x -= 1
if q == 0:
count += 1
if count > 2:
print('Not Prime')
else:
print('Prime')
Output:
Not Prime
More Applications:
Example 1:
Python3
num = 86
sums = 0
while num != 0:
use = divmod(num, 10)
dig = use[1]
sums = sums + dig
num = use[0]
print(sums)
Output:
14
Example 2:
Python3
num = 132
pal = 0
while num != 0:
use = divmod(num, 10)
dig = use[1]
pal = pal*10+dig
num = use[0]
print(pal)
Output:
231
Syntax
object.__divmod__(self, other)
The Python __divmod__() method implements the built-in divmod operation. So, when you call divmod(a, b), Python attempts to call x.__divmod__(y). If the method is not implemented, Python first attempts to call __rdivmod__ on the right operand and if this isn’t implemented either, it raises a TypeError.
We call this a “Dunder Method” for “Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.
Background Default divmod()
Python’s built-in divmod(a, b) function takes two integer or float numbers a and b as input arguments and returns a tuple (a // b, a % b). The first tuple value is the result of the integer division a//b. The second tuple is the result of the remainder, also called modulo operation a % b. In case of float inputs, divmod() still returns the division without remainder by rounding down to the next round number.
To understand this operation in detail, feel free to read over our tutorial or watch the following video:
Python divmod() — A Simple Guide
Example Custom divmod()
In the following example, you create a custom class Data and overwrite the __divmod__() method so that it returns a dummy string when trying to calculate the modulo of two numbers.
class Data:
def __divmod__(self, other):
return '... my result of divmod...'
a = Data()
b = Data()
c = divmod(a, b)
print(c)
# ... my result of divmod...
If you hadn’t defined the __divmod__() method, Python would’ve raised a TypeError.
How to Resolve TypeError: unsupported operand type(s) for divmod()
Consider the following code snippet where you try to divide two custom objects without defining the dunder method __truediv__():
class Data:
pass
a = Data()
b = Data()
c = divmod(a, b)
print(c)
Running this leads to the following error message on my computer:
Traceback (most recent call last):
File "C:UsersxcentDesktopcode.py", line 7, in <module>
c = divmod(a, b)
TypeError: unsupported operand type(s) for divmod(): 'Data' and 'Data'
The reason for this error is that the __divmod__() method has never been defined—and it is not defined for a custom object by default. So, to resolve the TypeError: unsupported operand type(s) for divmod(), you need to provide the __divmod__(self, other) method in your class definition as shown previously:
class Data:
def __divmod__(self, other):
return '... my result of divmod...'
Of course, you’d use another return value in practice as explained in the “Background divmod()” section.
Python __divmod__ vs __rdivmod__
Say, you want to calculate the divmod of two custom objects x and y:
print(divmod(x, y))
Python first tries to call the left object’s __divmod__() method x.__divmod__(y). But this may fail for two reasons:
- The method
x.__divmod__()is not implemented in the first place, or - The method
x.__divmod__()is implemented but returns aNotImplementedvalue indicating that the data types are incompatible.
If this fails, Python tries to fix it by calling the y.__rdivmod__() for reverse divmod on the right operand y.
If this method is implemented, Python knows that it doesn’t run into a potential problem of a non-commutative operation. If it would just execute y.__divmod__(x) instead of x.__divmod__(y), the result would be wrong because the divmod operation is non-commutative (neither the integer division, nor the modulo operation is commutative). That’s why y.__rdivmod__(x) is needed.
So, the difference between x.__divmod__(y) and x.__rdivmod__(y) is that the former calculates (x // y, x % y) whereas the latter calculates (y // x, y % x) — both calling the respective divmod method defined on object x.
You can see this in effect here where we attempt to call the divmod operation on the left operand x—but as it’s not implemented, Python simply calls the reverse divmod operation on the right operand y.
class Data_1:
pass
class Data_2:
def __rdivmod__(self, other):
return 'called divmod'
x = Data_1()
y = Data_2()
print(divmod(x, y))
# called divmod
References:
- https://docs.python.org/3/reference/datamodel.html
Explainer Video Modulo
You can also check out my explainer video where I’ll give you a deep dive on the built-in modulo operation and how to use them for various data types. Click to watch:
Python Modulo — A Simple Illustrated Guide
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
Join the free webinar now!

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.
|
krenddel 0 / 0 / 0 Регистрация: 25.04.2020 Сообщений: 14 |
||||
|
1 |
||||
|
26.04.2020, 12:21. Показов 11977. Ответов 2 Метки нет (Все метки)
В коде:
############################ Traceback (most recent call last): Хотя,там написано, что если b равно 0, то вывести «деление на ноль»
__________________
0 |
|
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
26.04.2020, 12:21 |
|
2 |
|
25 / 9 / 0 Регистрация: 26.11.2018 Сообщений: 82 |
|
|
26.04.2020, 12:31 |
2 |
|
На 26 строке вы ставите в условие строку, а надо число. И на 19 замените, где проводится операция деления
0 |
|
Viktorrus 1726 / 966 / 198 Регистрация: 22.02.2018 Сообщений: 2,694 Записей в блоге: 6 |
||||||||
|
26.04.2020, 12:38 |
3 |
|||||||
|
b==’0′ Вы число сравниваете со строкой. Если b будет равно нулю, у Вас условие все равно будет False, то есть у Вас не определяется, когда b равно нулю. Исправте в условии на
0 |
|
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
26.04.2020, 12:38 |
|
3 |
a = input() f = float(a.replace(',','.')) b = float(input()) c = input() if b == 0 and (c == 'div' or 'mod' or '/'): print('Деление на 0!') elif c == '+': print(f + b) elif c == '-': print(f - b) elif c == '*': print(f * b) elif c == '/': print(f / b) elif c == 'mod': print(f % b) elif c == 'div': print(f // b) elif c == 'pow': print(f ** b)
При вводных данных:
5
0
— или +
Выводит “Деление на 0!”
При
if b == 0 and (c == 'div' or 'mod' or '/') and not(c == '-' or '+')
Вот такая штука с mod
Test input: 5.0 0.0 mod Correct output: Деление на 0! Your code output: Error: Traceback (most recent call last): File "jailed_code", line 16, in <module> print(f % b) ZeroDivisionError: float modulo
И вот такая с div
Traceback (most recent call last): File "jailed_code", line 18, in <module> print(f // b) ZeroDivisionError: float divmod()
Само задание для написание калькулятора:
Напишите простой калькулятор, который считывает с пользовательского ввода три строки: первое число, второе число и операцию, после чего применяет операцию к введённым числам (“первое число” “операция” “второе число”) и выводит результат на экран.
Поддерживаемые операции: +, -, /, *, mod, pow, div, где
mod — это взятие остатка от деления,
pow — возведение в степень,
div — целочисленное деление.
Если выполняется деление и второе число равно 0, необходимо выводить строку “Деление на 0!”.
Обратите внимание, что на вход программе приходят вещественные числа.
