Python Functions
You use functions in programming to bundle a set of
instructions that you want to use repeatedly or that,
because of their complexity, are better self-contained
in a sub-program and called when needed. That
means that a function is a piece of code written to
carry out a specified task. To carry out that specific
task, the function might or might not need multiple
inputs. When the task is carried out, the function can
or can not return one or more values.
A function is a block of code which only
runs when it is called.
You can pass data, known as parameters,
into a function.
A function can return data as a result.
Example:
def function():
print(“Happy birthday to you”)
print(“Happy birthday to you”)
print(“Happy birthday to you”)
function()
f-string
Python offers a powerful feature called f-
strings (formatted string literals) to simplify string
formatting and interpolation. f-strings is introduced in
Python 3.6 it provides a concise and intuitive way to
embed expressions and variables directly into strings.
The idea behind f-strings is to make string interpolation
simpler.
Example:
def Name(name, age):
print(f"hello {name}")
print(f"{age} years old")
Practice:
Create a function about your autobiography
Output:
My name is
I’m years old
I live in My contact
Number is:
Example:
To add
def add1(num1, num2):
Print(num1 + num2)
To Subtract
def sub1(num1, num2):
print(num1 – num2)
exercise
Sum All Numbers in a List
Write a Python function to sum all the numbers in a list.
Sample List : (8, 2, 3, 0, 7)
Expected Output : 20
Python Lambda
A lambda function is a small anonymous
function.
A lambda function can take any number of
arguments, but can only have one
expression.
Lambda sample:
Sample_name = lambda a : a + 10
print(Sample_name(5))
Output: 15
TwoV = lambda a, b: a+b
print(TwoV(5,8))
Output: 13
Python Arrays
Arrays are used to store multiple values in one single
variable:
An array is a data structure that lets us hold multiple
values of the same data type. Think of it as a container
that holds a fixed number of the same kind of object.
Python makes coding easier for programmers.
An array is used to store more than one value at a time. It
can hold multiple values in a single variable, and also
helps you reduce the overall size of the code. Arrays save
time.
Creating an Array in Python
EXAMPLE:
Code:
Foods = [“Salad”, “Fried Chicken”, “Cake”]
Input:
Foods[0]
Output:
‘Salad’