Posted December 15, 2022 by up2146107
In Python, a functions is a block code that only runs when it is called and when its called also you can also pass data known as parameters into a function, and you return data as well in the form of a result. the way of creating a function in python is by using the Keywords "def" which is what defines it like the following:
def my_function():
print("Hello this is what a function is : )")
to call a function in python you would use a functions name followed by a parenthesis like the following:
Input:
def my_function():
print("THIS IS HOW YOU DO A FUNCTION!")
my_function()
Output: THIS IS HOW YOU DO A FUNCTION!
Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:
Example;
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Number of Arguments:
By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.
Example:
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.
Casting in python is therefore done using constructor functions:
x = 1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
Example:
print(type(x))
print(type(y))
print(type(z))