-2

I have defined a variable on initialization, now if I`m trying to change the value it does not change.

File=""

def pathValue():
    if File:
        print("file path: " + File)
    else:
        File = "abc.txt"
        print("file path: " + File)

pathValue()

Above is my sample code. It should change the value of the 'File' variable to 'abc.txt' but it's not working. Instead, it shows like this,

file path:

if the variable is empty then how can it bypass the if-condition?

NewLomter
  • 95
  • 1
  • 7
Mayank Jain
  • 47
  • 1
  • 8
  • 1
    Hey, thanks for the question! It would be a big help if you told us a little about how you've already tried to fix the issue and why that didn't work. Regardless, the issue is that, within `pathValue`, Python is treating `File` as a local variable. To fix it, add `nonlocal File` as the first line to `pathValue`. – Quelklef Jul 04 '20 at 18:46
  • 1
    Does this answer your question? [Python nonlocal statement](https://stackoverflow.com/questions/1261875/python-nonlocal-statement) – Quelklef Jul 04 '20 at 18:46
  • @Quelklef I think `global` is more relevant here than `nonlocal` . – Vishal Singh Jul 04 '20 at 18:51
  • @VishalSingh Yeah, you're right. Looks like `nonlocal` can't reach into the global context (dunno why). I can't edit my original comment, though. – Quelklef Jul 04 '20 at 18:54
  • Does this answer your question? [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – mkrieger1 Jul 04 '20 at 18:56
  • I cannot reproduce this. I get an error message instead, as I expected. – Karl Knechtel Sep 13 '22 at 15:34

2 Answers2

3

You may add global File as the first line of your function so python would treat File as a global and not as a local variable.

pebox11
  • 3,377
  • 5
  • 32
  • 57
3

The variable File is out of scope for the function pathValue(), either declare it inside the function, :

def pathValue():
    File=""
    if File:
        print("file path: " + File)
    else:
        File = "abc.txt"
        print("file path: " + File)

pathValue()

or make it a global variable :

File=""

def pathValue():
    global File
    if File:
        print("file path: " + File)
    else:
        File = "abc.txt"
        print("file path: " + File)

pathValue()
Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40
  • 1
    Thanks, actually I've used global keyword but the this is 'File' is used by two other functions and I forgot to use global in all functions. Silly mistake, but thank you again – Mayank Jain Jul 05 '20 at 05:01