0

How can you go out of a function in python??

Look at this program

For example:

import pygame, sys
from pygame.locals import *

pygame.init()

level = 0
x = 0

def eg_func():
    global x
    x = 10

def eg_func2():
    global x
    x = 2

while True:
    if level == 0:       
        eg_func()

    if playing == True:
        eg_func2()   

    print(x)

pygame.quit()
quit

So, how can I do that eg_func() stops but level keeps being 0 and not changing global -> because in my program I can't change it?

Thanks for everything, probably it's a simple thing.

  • Check [Python Scopes and Namespaces](https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces). – Olvin Roght May 26 '23 at 20:48
  • Do any of these answer your question? [Cannot break out of while loop in python](https://stackoverflow.com/questions/42318622/cannot-break-out-of-while-loop-in-python) | [Can't break out of Python loop](https://stackoverflow.com/questions/25922925/cant-break-out-of-python-loop) | [How to break out of while loop in Python?](https://stackoverflow.com/questions/14594522/how-to-break-out-of-while-loop-in-python) – Robert Bradley May 26 '23 at 21:20
  • Or these? [I am unable to break out of python (while) loop, and unsure why?](https://stackoverflow.com/questions/75537809/i-am-unable-to-break-out-of-python-while-loop-and-unsure-why) | [breaking out of python loop without using break](https://stackoverflow.com/questions/19773965/breaking-out-of-python-loop-without-using-break) | [How to break out of a while loop in Python 3.3](https://stackoverflow.com/questions/12995405/how-to-break-out-of-a-while-loop-in-python-3-3) – Robert Bradley May 26 '23 at 21:20

1 Answers1

1

You have to use global x to tell Python to change the value of the global x value, instead of defining a local x variable inside the function.

import pygame, sys
from pygame.locals import *

pygame.init()

level = 0
x = 0

def eg_func():
    global x
    x = 10

def eg_func2():
    x = 2

while True:
    if level == 0:       
        eg_func()

    if playing == True:
        eg_func2()   

    print(x)

pygame.quit()
quit
TheOneMusic
  • 1,776
  • 3
  • 15
  • 39