0

Function variable

message = "a" def greet(name): message ="b" greet("khan" ) print(message) #what will be out # a | b

27th Jan 2024, 7:06 AM
Muhammad
Muhammad - avatar
6 Answers
+ 3
Maybe the question should be a | b | khan. You could try the snipet in Sololearns playground and see what happend, did you?
27th Jan 2024, 7:52 AM
JaScript
JaScript - avatar
+ 3
It is important for programming to know what local and global variables are and how they are influenced.
27th Jan 2024, 7:57 AM
JaScript
JaScript - avatar
+ 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
27th Jan 2024, 12:00 PM
Solo
Solo - avatar
+ 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
27th Jan 2024, 12:48 PM
Per Bratthammar
Per Bratthammar - avatar
+ 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.
27th Jan 2024, 11:38 AM
Jacob Morgunov
Jacob Morgunov - avatar
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.
27th Jan 2024, 2:07 PM
Bob_Li
Bob_Li - avatar