razvan
razvan

Reputation: 7

Function not working in python calculator

I managed to build a calculator, but when I want to add functions, it doesn't work properly. You can see the function in the code, in the comments. If I enable the function, res will be all the time 0 and will add the last number. Without the function, you can do how many operations you want and it works properly. I've tried to put the function inside the while loop, but it's the same result. How can I solve this problem?

class Calc:
    num = float(input("Enter nr: "))
    operator = str(input("Enter operator"))
    res = 0

    # def add(num, res):
    #     res += num
    #     print(res)

    while operator != "=" : 

        if operator == '+' :
            res += num
            print(res)

            #add(num,res)
            #returns all the time 0+num,doesn`t add to res

        elif operator == '-' :
            res -= num
            print(res)

        elif operator == '*' :
            res *= num
            print(res)

        elif operator == '/' :
            res /= num
            print(res)

        else:
            print("Wrong operator!")

        operator = str(input("Enter operator"))
        num = float(input("Enter nr: "))

Upvotes: 0

Views: 771

Answers (3)

Bhavye Mathur
Bhavye Mathur

Reputation: 1077

The problem is that though you are changing the value of 'res' inside the function. It doesn't affect the value of the variable outside...

What I mean, is that when you pass the variable res to the function, you are passing a copy of the variable, not the variable itself. And when you add num to res inside the function, it changes that copy of the variable that exists only inside the function and not outside.

To solve your problem:

num = float(input("Enter nr: "))
operator = str(input("Enter operator"))
res = 0

def add(res, num):

    res += num
    return res

while operator != "=" : 

    if operator == '+' :
        res = add(res, num)
        print(res)

Here, I have 'returned' value of res inside the function and assigned the variable outside the function to it, and then printed out that value.

Upvotes: 0

Swapnil Nakade
Swapnil Nakade

Reputation: 860

if your purpose is to create a calculator then there is not need to do that much hustle, you can use eval function for the same, following is the implementation of that. eval function just takes the string as argument and calculate result for you.

def calc():
    cal = input("start calculating :")
    res = eval(cal)
    print(res)

calc()

Talking about you want to learn about python classes then as @chepner said in the comment classes are meant to be wrapper of behaviours and properties of physical or logical world's objects. They are used to encapsulate data. Now considering that python is very dynamic language you can write methods and variables outside classes.

But this is not the case in pure object oriented languages. everything should be inside class. So if you want to learn about classes then you should consider learning how classes work. Implementation of the same is just looking for syntax in particular language you are looking for. I will recommend you to look for actual behaviour of classes

here is tutorial for java classes I found these easy to understand

Understand this tutorial first, then think about how you can implement this concept in python.

Hope this helps!

Upvotes: 0

Giordano
Giordano

Reputation: 5570

Here a quick example to how integrate functions in your class.
This is just an example, to help you to understand better how to use Python classes.

class Calc:

    def __init__(self):
        self.first_num = float(input("Enter first nr: "))
        self.operator = str(input("Enter operator"))
        self.second_num = float(input("Enter second nr: "))

    def add(self):
        res=self.first_num + self.second_num
        print(res)

    # def minus(self):
    #   res=self.first_num - self.second_num
    #   print(res)

    def start(self):
        while(self.operator != "="):

            if self.operator == '+' :
                self.add()

            elif self.operator == '-' :
                res -= num
                print(res)
                # self.minus()

            elif self.operator == '*' :
                res *= num
                print(res)

            elif self.operator == '/' :
                res /= num
                print(res)

            else:
                print("Wrong operator!")

            self.first_num = float(input("Enter first nr: "))
            self.operator = str(input("Enter operator"))
            self.second_num = float(input("Enter second nr: "))

# instantiate Calc class and start it
calc_obj = Calc()
calc_obj.start()

I suggest you to read the Python documentation about classes.

Upvotes: 1

Related Questions