+ 1
how to divide 8/4/2 if we got this as input ?
I Want to perform the mathamatical operations on input according to the user input. input can be anything as shown below : -------------------..................... - - - - - - - -- Example : Input : 1+2+3+4+5 output : 15 input : 2-4-5-6 output : - 13 input : 3*2*4*3 output : 72 input : 8/2/2 output : 2.0 My attempt : https://code.sololearn.com/cGDCZeJsOn3U/?ref=app Edit : I know the eval() function but I want to do it without using eval()
7 Réponses
+ 1
One way could be the following:
1) in case of /, set total to lst[0] before entering the loop
2) in case of /, skip the first iteration of lst
Another thing:
Mind catching zero division error if there is a 0 in the lst
+ 2
if you want to do it in a very easy, flexible (and unsafe) way - you can simply write:
calc =input("Enter :")
print(eval(calc))
+ 2
Martin Ed sorry to tell later but I know the eval() method
but I want to do without it..
+ 2
Here is one possible solution, but it still lacks error handling (as Lisa mentioned already earlier):
https://code.sololearn.com/cpRlo02MPlCu/?ref=app
+ 1
Lisa I did it Thank you so much for the hints :
any bugs?? :
https://code.sololearn.com/cJAIucJ331b3/?ref=app
+ 1
Lisa OK I will edit it Thanks again! 😊
0
On zero division error:
Maybe you could
- actually raise an error or
- print a message so the user notices what he/she did wrong or
- print a None result
instead of just "passing" the division error.
Consider we input 4/0/2.
Your code outputs 2.0 which mathematically doesn't make sense as division through 0 is not defined, right?