Skill - functions in python
Skills Required
- Setup Python Development environment
- Commenting in python
- Basic printing in python
- Managing Variables in python
Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision
Functions can be used to encapsulate logic so that we can get an output for a given input based on the function’s logic
The pictorial representation can be as shown below
Structure of a function in python
Function example in python
# define a function that adds 2 numbers
def add(x,y):
return x+y
# use the function by passing the required parameter
sum = add(5, 6)
print(sum)
# this prints 11
Function with optional and named parameters
# define a function that adds 2 numbers
def multiply(x,y=1):
return x*y
# since we didn't give second input, it is considered
# as the default value, i.e., 1
a = multiply(15)
print(a)
# this prints 15
# here we are giving both the inputs
b = multiply(15, 2)
print(b)
# this prints 30
# we can also give inputs through input variable names
c = multiply(x=12, y=4)
print(c)
# this prints 48
Video
Video for this post can be found here
Online Interpreter
Although we recommend to practice the above examples in Visual Studio Code, you can run these examples online at https://pynative.com/online-python-code-editor-to-execute-python-code/
Comments
Post a Comment