Can def calculate with variables?

a = 1
b = 1

def test():
a += b


so i tried to make def calculate with 2 variables, which is an easy task, but it seems like python doesn’t like variables in a def, please help

Of course Python can use variables inside functions.

What should we call you? “iam” or “doomguy” or something else? Whichever
you prefer, thank you for showing the code you used.

I don’t know what level of explanation to use, since I don’t know your
level of experience. Have you done any tutorials in Python? Have you any
experience with other programming languages? I’m going to guess No for
the first and “Not much” with the second.

In the future, could you please copy and paste the error messages you
see when you ask for help? (Don’t take a screen shot or photo!) That
way we don’t have to guess what error message you see.

In this case, I’m going to guess that you see something like this:

UnboundLocalError: local variable 'a' referenced before assignment

If you saw something else, I can’t guess what it might have been.

The error message tells you that Python does handle variables in
functions, and tells you precisely what the problem was: you have a
local variable ‘a’, but you tried to refer to it before it existed.

Do you understand the difference between global variables and local
variables? In your test function:

def test():
    a += b

‘a’ is a local variable and ‘b’ is a global variable. It’s not obvious
at first glance why, but the reason is that whenever you assign a value
to a variable, and that includes +=, Python treats it as a local
variable unless you tell it otherwise.

Here are two ways to fix the bug in your test function:

(1) The best way is to avoid global variables, and pass the variables
into the function, and return a result. It’s more work but better in the
long run when you have more complex functions.

a = 1
b = 1

def test(x, y):
    x += y
    return x

a = test(a, b)

(2) Tell Python to use a global variable. This is shorter and easier,
but in the long run, it will lead to more trouble, difficulty and bugs.
As a beginner it’s okay to do this just for experimenting but don’t get
into the habit of it.

a = 1
b = 1

def test():
    global a
    a += b


Play around with both; see if you can work out for yourself why option 1
is better in the long run than 2.

(Hint: what happens if you don’t want to increment ‘a’, but put the
result of ‘a+b’ into a new variable ‘c’? How would you do that with
option 2?)

Feel free to ask if you have any more questions.

thank you, it helped me a lot, python is my first programming language and i think i whould be pretty decent at it.
i can programm a lot with automated calculations, and also its logic behind.
i just sometimes don’t know what codes whould do what.
call me doomguy. lol