Salutations, Python apprentice! Last we met, we delved into controlling the flow of your Pythonic spells.
Now, we venture into an equally exciting territory: Functions! Yes, you heard it right, the magical formulae that make our coding lives a million times easier!
Defining a Function
Functions in Python are like your magic spells. They do a specific task and can be called upon whenever needed. Here's how you define a function:
def cast_spell():
print("Expecto Patronum!")
To call this function, we simply write:
cast_spell()
Function Arguments and Return Values
Sometimes, our spells (functions) need ingredients (arguments) to work. We provide these ingredients when we call the spell:
def cast_spell(incantation):
print(incantation)
cast_spell("Expecto Patronum!")
A function can also return a value using the return
statement. This is like the result of your spell:
def add_numbers(num1, num2):
return num1 + num2
sum = add_numbers(7, 3)
print(sum) # prints 10
Variable Scope (Global vs. Local)
In the magical world of Python, variables have a scope
which refers to the visibility of variables.
- Local Variables: These are the variables defined inside a function. These can only be used inside that function.
def magic_function():
spell = "Accio" # Local Variable
print(spell)
- Global Variables: These are the variables defined outside of all functions. These can be used anywhere in the file.
spell = "Accio" # Global Variable
def magic_function():
print(spell)
Anonymous Functions (lambda)
In Python, we have some one-line, anonymous spells which we call lambda
functions. They are super handy when we want to write small, quick functions.
double = lambda x: x * 2
print(double(5)) # prints 10
Modules and Packages
Sometimes, other Python wizards have written useful spells and put them into modules
and packages
that we can use in our own code. This is one of the key advantages of Python - an incredibly rich ecosystem of pre-made magic!
import math
print(math.sqrt(16)) # prints 4.0
There you go! You now have a new set of spells to add to your Pythonic grimoire. Use them wisely and remember, coding is like magic, the only limit is your imagination.
Happy coding, Python sorcerer!