Search code examples
functionvariables

How do assign a variable an input as the value in a function and allow it to be accessed?


I know that this is probably a simple fix, but I'm pretty new at programing.

def main2():
    x = int(input("What is the length of your rectangle?:  "))
    y = int(input("What is the width of your rectangle?:  "))
    z = int(input("What is the height of your rectangle?:  "))
    print(area2())

def area2():
    return(x * y)

if __name__ == "__main__":
    main2()

My problem is that I am getting a "'variable' not accessed." Because of this, my program is not using the variables later in the code.

I've tried pretty stupid stuff that I expected to not work because I don't know very much code.


Solution

  • You need to pass the variable to the function. Inside main2() change the line with print() to this:

    print(area2(x, y))
    

    You should also change your function to accept two variables.

    def area2(x, y):
        return(x * y)
    

    Otherwise, make x,y as global:

    global x,y
    

    Then you don't need to pass the variables.