0
I don't know why the functions is not using the if when the code works outside the function
word = input() #"3 is crowd" nonum = "" def change(a): print(a) if str(a) in word: nonum = word.replace(str(a),"three") change(3) print(nonum) # this returns 3 #----------------------------------------- word = input() #"3 is crowd" nonum = "" if str(3) in word: nonum = word.replace(str(3),"three") print(nonum) #this prints "three is crowd" which is the desired outcome #the only difference is if the if is inside the change() function #why is the if function not working when called inside change()?
1 ответ
+ 1
There's no problem with the function, and the `if` conditional.
The problem is, the <nonum> inside the function is local, it's not the same with the <nonum> defined outside the function - at global space.
If you want to change a global variable in a function you need to specify that explicitly by adding
global nonum
One line above the replacement of 3 -> "three" statement, inside the `if` block