0
Function variable
message = "a" def greet(name): message ="b" greet("khan" ) print(message) #what will be out # a | b
6 odpowiedzi
+ 3
Maybe the question should be a | b | khan.
You could try the snipet in Sololearns playground and see what happend, did you?
+ 3
It is important for programming to know what local and global variables are and how they are influenced.
+ 3
In order to use a global variable in a function, it must be marked:
def greet(name):
global message
message = name
So the output is: a
+ 3
Hi, Muhammad !
In your code there exist two variables with the same name (message). One global and one local. The local one exists as long as you run the function, because it is created inside the function 'greet' and refere to a inmutuable object (a string).
You can of course use the keyword 'global' to get a variable inside a function store a variable as global variable.
But threre is actually ways to preserve the state between function calls, for example like this shows:
https://sololearn.com/compiler-playground/c13gPsnuaP5A/?ref=app
+ 2
The greet function defines a local variable message within its scope, but it doesn't return or print anything. Therefore, the global variable message remains unchanged, and when you print it outside the function, it will still be "a". The global variable message is not affected by the local variable with the same name inside the function.
0
maybe this
message = "a"
def greet(name=""):
return name or message
print(message)
print(greet())
print(greet("khan" ))
even without the global keyword, a function can still access global variables.