+ 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()

3rd Jan 2021, 6:25 PM
Ratnapal Shende
Ratnapal Shende - avatar
7 Antworten
+ 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
3rd Jan 2021, 6:46 PM
Lisa
Lisa - avatar
+ 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))
3rd Jan 2021, 6:43 PM
Martin Ed
Martin Ed - avatar
+ 2
Martin Ed sorry to tell later but I know the eval() method but I want to do without it..
3rd Jan 2021, 6:47 PM
Ratnapal Shende
Ratnapal Shende - avatar
+ 2
Here is one possible solution, but it still lacks error handling (as Lisa mentioned already earlier): https://code.sololearn.com/cpRlo02MPlCu/?ref=app
3rd Jan 2021, 7:09 PM
Martin Ed
Martin Ed - avatar
+ 1
Lisa I did it Thank you so much for the hints : any bugs?? : https://code.sololearn.com/cJAIucJ331b3/?ref=app
3rd Jan 2021, 7:16 PM
Ratnapal Shende
Ratnapal Shende - avatar
+ 1
Lisa OK I will edit it Thanks again! 😊
3rd Jan 2021, 7:33 PM
Ratnapal Shende
Ratnapal Shende - avatar
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?
3rd Jan 2021, 7:26 PM
Lisa
Lisa - avatar