0

I'm working on a project and now i'm stuck. I've tried to search but I didn't find anything, maybe because I don't know what I have to search exactly.

the part that I can't figure out is the same at this one

bum = 0

def tryit():
    for bum in range(5):
        print("Hey")
        bum += 1
    print(bum)

tryit()
tryit()
tryit()

I want the output to be

hey
hey
hey
hey
hey
5
hey
hey
hey
hey
hey
10  
hey
hey
hey
hey
hey
15

instead, the output is

hey
hey
hey
hey
hey
5
hey
hey
hey
hey
hey
5  
hey
hey
hey
hey
hey
5

how can i keep increment the variable bum ?

i know that maybe is stupid and sorry but i really can't figure out

DavidG
  • 24,279
  • 14
  • 89
  • 82
fobu36
  • 49
  • 1
  • 5

3 Answers3

2

Change bum to a global variable so your function can access it. Also, I would recommend changing your for loop variable to reduce any confusion.

Code:

bum = 0
def tryit():
    global bum
    for i in range(5):
        print("Hey")
        bum += 1
    print(bum)

Output:

enter image description here

This was for demonstration purposes only. While a global variable was used for this example it is typically not recommended as it can have negative side effects in a real world scenario. Read more here.

Jonathan Porter
  • 1,365
  • 7
  • 34
  • 62
0

In for loop, you should use different variable name rather than bum in for statement.

Second, maybe you need global keyword in tryit() for bum

Han Song
  • 54
  • 4
0

You're shadowing a global name but using the one in the for loop scope. Instead, use two different names for the bum outside of the function, and the bum inside the for loop.

Oyster773
  • 375
  • 1
  • 10