0
y = 0
x = 10

print("TRUE" if y>x else theloop())

def theloop():
 while y < 11:
    print(f"Number is {y}!")
    y = y + 1

I want y to keep on getting bigger by 1 until it becomes bigger than x and print "TRUE", but each time it keeps saying the function isn't defined.

I tried this right here and it seems to work for some reason. But whenever I want y to increase by 1, it completely stops working.

y=0
x=10

def theloop():
    while y < x:
       print(y+1)

print("true" if y>x else theloop())
marc77
  • 1
  • 1
    "But whenever I want y to increase by 1, it completely stops working." - https://stackoverflow.com/questions/370357/unboundlocalerror-trying-to-use-a-variable-supposed-to-be-global-that-is-rea – user2357112 May 13 '23 at 02:06
  • You need to be more specific about what "completely stops working" means. – Mark Ransom May 13 '23 at 02:10
  • 1
    When you do `y = y + 1` you're shadowing the global variable `y` with a new local variable `y`. You can "fix" this by saying `global y` at the start of the function to say that you want local assignments to affect the global variable -- but once you learn about objects, you should put this state into an object and make `theloop` a method of that object instead of having global functions that modify global state. – Samwise May 13 '23 at 02:17
  • You're calling `theloop()` before it's defined. – John Gordon May 13 '23 at 02:19

1 Answers1

1

First thing:

In the global scope, you want to define a function before you call it. This explains why your first code doesn't work. Python hasn't defined the function yet and you're calling it before it has a chance to access it.

print("TRUE" if y>x else theloop())

# Python hasn't seen this when you call the function
def theloop():
    while y < x:
       print(y+1)

Second thing:

The code you wrote that runs only prints (y+1)... it does not actually increase y by 1.

Also, y is not accessible within the function so:

Define it locally before the while loop like this:

x = 10

def the_loop():
    # define y locally
    y = 0
    while y < x:
        # increases y by 1
        y += 1
        print(y)

print("true" if y > x else the_loop())

Pass it in as an argument if y might change:

x = 10
y = 0

# pass y in as an argument 
def the_loop(y):
    while y < x:
        # increases y by 1
        y += 1
        print(y)

print("true" if y > x else the_loop(y))

Use the global keyword (see this post)

y = 0
x = 10

def theloop():
    global y
    while y < x:
       y += 1
       print(y)

print("true" if y > x else the_loop())

Using global keyword actually changes the original variable and now y = 10 is accessible outside of the function. More on globals here

futium
  • 90
  • 1
  • 9