If the result should be an integer, you should use operator.floordiv, i.e. a // b, not a / b 1:
from operator import add, sub, mul, floordiv, mod
op = {'+': add, '-': sub, '*': mul, '/': floordiv, '%': mod}
for i in range(int(input())):
znak, *nums = input().split()
print(op[znak](*map(int, nums)))
By the way, the code above does exactly the same as yours, but it's around two times shorter!
How?
- why check if
znak is equal to something with tons of if/else statements, if you could put all the math operators in a dictionary op, and get the operator you need with op[znak]?
- you're on Python 3, so you can use that nice
a, *b = iterable syntax which extracts the first item of iterable into a and puts other items into a list b, which looks super nice
- each
op[znak] is a function that accepts two arguments, so you convert nums to integers with map(int, nums) and then pass them as separate arguments with the asterisk: *map(int, nums)
- last, but not least, why use this C-style
while loop index incrementing if there's the Pythonic way to do it - with range(start, stop, [step])?
- finally, you don't really need the variable
n, so you can plug it into range right away
Pssst, dude, feeling in need of some craziness? Take a look at how you can squeeze all this into two lines:
from operator import*
sum(0for _ in map(print,((lambda znak,*nums:{'+':add,'-':sub,'*':mul,'/':floordiv,'%':mod}[znak](*map(int,nums)))(*input().split())for _ in range(int(input())))))
Or only one line:
sum(0for _ in map(print,((lambda znak,*nums:{'+':lambda a,b:a+b,'-':lambda a,b:a-b,'*':lambda a,b:a*b,'/':lambda a,b:a//b,'%':lambda a,b:a%b}[znak](*map(int,nums)))(*input().split())for _ in range(int(input())))))
These work exactly as the first version. Now, this is just for fun, to show how powerful Python is and how messy it can be. Don't try this at home :D
1 True division vs Floor division: 1 / 10 == 0.1, but 1 // 10 == 0.
sys.exit, the program exits automatically.int32(which doesn't exist)?/ 1 0will definitely throw an exception