0

What i want to do is have a function which checks some conditions and assigns a value according to which condition is true. But the variable assignment in the function does not affect the value outside. (Scopes)

While the following code won't work, is there any way to not have to write the if-elif block again and again?

def calc():
    if o==1:
        z=x+y
    elif o==2:
        z=x-y

calc()
print(z)
Green05
  • 319
  • 1
  • 8
  • Should read up more on [scopes](https://www.w3schools.com/python/python_scope.asp) and such. I'd **strongly** suggest you go back to wherever you're learning Python from, and ask the teacher or read the material to better understand how to create variables, scopes and functions. – Torxed May 28 '20 at 17:58
  • @Torxed That clarifies why it didn't work, thanks! I'm learning it myself, just begun, guess I tried something out of my depth. Any idea how I can achieve my goal? – Green05 May 28 '20 at 18:01
  • I'm self taught, I just had a very clear goal of what I needed to make and I broke the project down to pieces. For instance, book keeping. I knew i needed storage, googled "python store data" and sqlite came up, and then I needed a UI, so I googled "python builtin ui" and found some examples that weren't to far off what I needed (basic input and showing results). And then I just started looking and analyzing stuff. These days you have IDE's that can debug and step through code (pycharm) which I didn't have at the time, so `print()` was my friend. Just see what others have done, start small! – Torxed May 28 '20 at 18:17

1 Answers1

0

this is referred to as scope in the computer science world ... and your assignment is out of scope of the main program space

instead you should just return the value

def calc():
    if o==1:
        z=x+y
    elif o==2:
        z=x-y
    return z

y = calc()
print(y)
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179