def myfunc():
x = "fantastic"
myfunc()
print("Python is " + x)
Output: Python is awesome
Why is the output "Python is awesome"?
• The variable x = "awesome" is declared outside the function, making it a global variable.
• Inside the function myfunc(), a new variable is created:
x = "fantastic"
This is a local variable, which exists only within the function.
Since the function neither returns nor prints the local variable, and the global variable is never changed, the statement: print("Python is " + x)
still uses the global variable:
x = "awesome"
Therefore, the output is: Python is awesome
If You Want the Output to Be "Python is fantastic"
You can use the global keyword: x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Output: Python is fantastic
A Better Practice
Instead of using global, it is generally better to return a value from the function: x = "awesome"
def myfunc():
return "fantastic"
x = myfunc()
print("Python is " + x)
Output: Python is fantastic This approach is considered cleaner, easier to understand, and follows modern Python programming practices.
Errors in the Image
The image contains a few mistakes:
❌ Incorrect: myfunc
✅ Correct: myfunc() -> ❌ Incorrect: dwesome
✅ Correct: awesome
❌ Inconsistent capitalization: python is
✅ More common style: Python is
Key Concepts Learned
This example introduces three important Python concepts:
• Global Variables – Variables declared outside a function and accessible throughout the program.
• Local Variables – Variables declared inside a function and accessible only within that function.
• Variable Scope – The area of a program where a variable can be accessed.
Understanding these concepts is essential for anyone beginning to learn Python programming.
Baca versi Indonesia: Klik Di sini

No comments:
Post a Comment