Working with incremented variable in a funciton not working

Viewed 32

I'm new to python and trying to solve some problems with it. I'm trying to increment a variable and then using that incremented variable in a function but it looks like it's not using the incremented variable.

So this is my code:

var = 0
line_num = 0 + var

def incerement_problem(line_number):
    if line_number == 1:
        print("true")
    else:
        global var
        var += 1

incerement_problem(line_num)
incerement_problem(line_num)

So after the second function call the code should give me back the "true" message, but instead of that it just increments the variable and looks like it's using the original value which is 0.

What I see is that the var variable is incrementing properly. But line_num variable stays 0.

I don't understand what is the problem hope somebody can explain it to me.

1 Answers

you need to increment line_num not var

line_num = 0

def incerement_problem(line_number):
    if line_number == 1:
        print("true")
    else:
        global line_num
        line_num+=1

incerement_problem(line_num)
incerement_problem(line_num)

Output:

true

Update:

line_num = 0
var = 0

def incerement_problem(line_number):
    if line_number == 1:
        print("true")
    else:
        global line_num
        global var
        var = 1
        line_num+=var

incerement_problem(line_num)
incerement_problem(line_num)
Related