0% found this document useful (0 votes)
42 views39 pages

Unit 3

Uploaded by

Omnious
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views39 pages

Unit 3

Uploaded by

Omnious
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

FUNCTIONS

Function
•It is a group of related statements that perform a specific task.
•Function helps to break our program into smaller and modular
chunks.
•As our program grows larger and larger, functions make it more
organized and manageable.
•It avoids repetition and makes code reusable.
•In Python a function is defined using the def keyword

#Function definition #Function definition with


without parameters parameters

def function_name( ): def function_name(parameters):


Body of function Body of function
FUNCTIONS
Ex 1: Function without parameters

def sum(): #func definition


print(“Hello, I am sum function”)

sum() #func calling

Ex 2: Function with parameters

def sum(a,b): #func definition


z=a+b
print(“The result is “,z)
sum(2,5) #func calling
FUNCTIONS
Types of Function:
•Built-in function:
Functions that are built into Python. Like: range(), pow(),
print(),input() etc…
•User-defined function:
Functions defined by the users themselves.

Ex: User defined function

def sum(a,b): #func definition


z=a+b
print(“The result is “,z)
sum(2,5) #func calling
FUNCTIONS
Parameters and Arguments:
•Parameters are passed during the definition of function.
•Arguments are passed during the function call.

def add(a,b): #here a & b are parameters


return a+b

result=add(12,13) # here 12 & 13 are arguments


print(result)

Output: 25
FUNCTIONS
Types of function arguments:
There are three types of Python function arguments using which we can call a
function.
• Default Arguments
• Keyword Arguments
• Variable-length Arguments
Default Arguments :
Function arguments can have default values in Python. We can provide a default
value to an argument by using the assignment operator (=)

def Wish(wish="Good Morning"):


print("Hello Everyone: "+wish)
Wish("Good Afternoon")
Wish()
FUNCTIONS
Keyword Arguments :
• Python allows functions to be called using keyword arguments.
When we call functions in this way, the order (position) of the
arguments can be changed.
• If you have some functions with many parameters and you want
to specify only some of them, then you can give values for such
parameters by naming them - this is called keyword arguments

Ex:
def items(item1,item2,item3):
print("It is " + item1)

items(item1="Mango", item2="Orange", item3="Grapes")


FUNCTIONS
Variable length Arguments :
When we need to process a function for more arguments than you
specified while defining the function. These arguments are
called variable-length arguments and are not named in the
function definition, unlike required and default arguments.
Ex:
def items(*item):
for x in range(len(item)):
print("This is "+item[x])

items("Mango", "Oranges", "Grapes")


FUNCTIONS
Variable length keyword Arguments :
If you do not know how many keyword arguments that will be
passed into your function, add two asterisk: ** before the
parameter name in the function definition.
This way the function will receive a dictionary of arguments, and
can access the items accordingly:
Ex:
def items(**item):
for x in item:
print("This is "+item[x])

items(item1="Mango",item2="Oranges",item3="Grapes")
LOCAL and GLOBAL scope
Local and Global scope:

Local Scope: A variable which is defined inside a function is local to


that function. It is accessible from the point at which it is defined
until the end of the function, and exists for as long as the function
is executing

Global Scope: A variable which is defined in the main body of a file is


called a global variable. It will be visible throughout the file, and
also inside any file which imports that file.

Note: The variable defined inside a function can also be made


global by using the global statement.
Python Strings
String Literals
String literals in python are surrounded by either single
quotation marks, or double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
Example
print("Hello")
print('Hello')

Assign String to a Variable


Assigning a string to a variable is done with the variable
name followed by an equal sign and the string:
Example
a = "Hello"
print(a)
Python Strings
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
a = """Hello First line
Second Line"""
print(a)

Or three single quotes:


Example
a = ''' Hello First line
Second Line '''
print(a)

Note: in the result, the line breaks are inserted at the same position as
in the code.
Python Strings
Strings are Arrays
Like many other popular programming languages, strings in
Python are arrays of bytes representing unicode characters.

However, Python does not have a character data type, a single


character is simply a string with a length of 1. Square brackets
can be used to access elements of the string.

Example

Get the character at position 1 (remember that the first


character has the position 0):
a = "Hello, World!"
print(a[1])
Python Strings
Substring.
Get the characters from position 2 to position 5 (not
included):
b = "Hello, World!"
print(b[2:5])
The strip() method removes any whitespace from the
beginning or the end:
a=" Hello, World! "
print(a.strip()) # returns "Hello, World!"
The len() method returns the length of a string:
a = "Hello, World!"
print(len(a))
Python Strings
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())

The upper() method returns the string in upper case:


a = "Hello, World!"
print(a.upper())

The replace() method replaces a string with another string:


a = "Hello, World!"
print(a.replace("H", "J"))

The split() method splits the string into substrings if it finds


instances of the separator:
a = "Hello World!"
print(a.split()) # returns ['Hello', ' World!']
Python Strings
String Format
As we learned till now, we cannot combine strings and numbers like this:
Ex
age = 36
txt = "My name is John, I am " + age
print(txt)
The above statement will show an error:
TypeError: can only concatenate str (not "int") to str
But we can combine strings and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and places them in
the string where the placeholders {} are:

Ex
Use the format() method to insert numbers into strings:
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

OUTPUT: My age is 36

The format() method takes unlimited number of arguments, and are placed into the
respective placeholders:
Python Strings
The format() method takes unlimited number of arguments, and are
placed into the respective placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

You can use index numbers {0} to be sure the arguments are placed in
the correct placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of
item {1}."
print(myorder.format(quantity, itemno, price))
Python Strings (Slicing)
Index:
An index is a position of an individual character or element in a list,
tuple, or string. The index value always starts at zero and ends at one
less than the number of items.

0 1 2 3 4 5 6 7 8 9 10
+ve indexing
H e l l o w o r l d
-ve indexing -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11

Negative indexes enable users to index a list, tuple, or other


indexable containers from the end of the container, rather than the
start.
Python Strings (Slicing)
Slicing is the extraction of a part of a string, list, or tuple. It
enables users to access the specific range of elements by
mentioning their indices.

Syntax: Object [start:stop:step]


•“Start” specifies the starting index of a slice
•“Stop” specifies the ending element of a slice
•“Step” You can use one of these if you want to skip certain
items

Note: The search will start at index Two (included) and ends at index seven(not
included).
Python Strings (Slicing)
Slicing all before index: Slicing between indices:
Ex: Ex:
a="Hello world“ a="Hello world“
x=a[:7] x=a[2:7]
print(x) print(x)

Slicing all after index: Slicing negative with index:


Ex: Ex:
a="Hello world“ a="Hello world“
x=a[2:] x=a[-1]
print(x) print(x)
Python Strings (Slicing)
Slicing all before –ve index: Slicing between indices:
Ex: Ex:
a="Hello world“ a="Hello world“
x=a[:-1] x=a[-9:-2]
print(x) print(x)

Slicing all after –ve index:


Ex:
a="Hello world“
x=a[-7:]
print(x)
Python Data Structures
List: In Python, lists are used to store multiple and mixed data at
once. A list can have any number of items and they may be of
different types (integer, float, string, etc.). Lists are created using
square brackets:
Syntax:
list1=[] #empty list
list1=[1,5,9] #list with similar data type
list1=[1, “hello”, 2.5] #list with different data types

List items are ordered, changeable, and allow duplicate values.


List items are indexed, the first item has index [0], the second item
has index [1] etc.
Python Data Structures
1. List Length
To determine how many items a list has, use the len() function:
list1=[1,5,9]
print(len(list1))

2. Accessing list items:

list1=[1,5,9]
print(list1[2])

3. Access using –ve index


list1=[1,5,9]
print(list1[-2])
Python Data Structures
4. Check item in list or not:
list1=[1,5,9]
if 5 in list1:
print("Yes")
5. Change item value in list:
list1=[1,5,9]
list1[1]=7
print(list1)
6. Insert item value in list:
list1=[1,5,9]
list1.insert(1,10)
print(list1)
Python Data Structures
7. Append item in list:
list1=[1,5,9]
list1.append(10)
print(list1)
8. Extend items in list:
list1=[1,5,9]
list2=['a','b','c']
list1.extend(list2)
print(list1)

9. Remove item from list:


list1=[1,5,9]
list1.remove(5)
print(list1)
Python Data Structures
10. Pop item from list:
list1=[1,5,9]
list1.pop(0)
print(list1)
11. Clear list items:
list1=[1,5,9]
list1.clear()
print(list1)

12. Delete list:


list1=[1,5,9]
del list1
print(list1)
Python Data Structures
Tuple: Tuples are used to store multiple items in a single variable. A
tuple is a collection which is ordered and unchangeable. Tuples are
written with round brackets. :
Syntax:
t1=() #empty tuple
t1=(1,5,9) #tuple with similar data type
t1=(1, “hello”, 2.5) #tuple with different data types

Tuple items are ordered, unchangeable, and allow duplicate


values.
Tuple items are indexed, the first item has index [0], the second
item has index [1] etc.
Python Data Structures
1. Tuple Length
To determine how many items a Tuple has, use the len() function:
t1=(1,5,9) One Item tuple
print(len(t1)) t1=(1,)
print(type(t1))
print(t1)
2. Accessing tuple items:

t1=(1,5,9)
print(t1[2])

3. Access using –ve index


t1=(1,5,9)
print(t1[-2])
Python Data Structures
4. Check item in tuple or not:
t1=(1,5,9)
if 5 in t1:
print("Yes")

5. Change item value in tuple: Once a tuple is created, you cannot change its
values. Tuples are unchangeable, or immutable as it also is called.
t1=(1,5,9)
l1=list(t1)
l1[1]=7
t1=tuple(l1)
print(t1)

6. Insert item value in tuple:


t1=(1,5,9)
l1=list(t1)
l1.insert(1,10)
t1=tuple(l1)
print(t1)
Python Data Structures
7. Unpack tuple:
When we create a tuple, we normally assign values to it. This is
called "packing" a tuple But, in Python, we are also allowed to
extract the values back into variables. This is called "unpacking“.

t1=(1,'a',9.5) t1=(1,'a',9.5,10, ‘abc’ ) t1=(1,'a',9.5,10, ‘abc’ )


(x,y,z)=t1 (x,y,*z)=t1 (x,*y,z)=t1
print("x=",x) print("x=",x) print("x=",x)
print("y=",y) print("y=",y) print("y=",y)
print("z=",z) print("z=",z) print("z=",z)

Note: The number of variables must match the number of values in the
tuple, if not, you must use an asterisk to collect the remaining values as a
list.
List Comprehension

• List comprehension offers a shorter syntax when you want to create a new
list based on the values of an existing list.

Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
if "a" in x:
newlist.append(x)

print(newlist)

• With list comprehension you can do all that with only one line of code

Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)
Dictionaries

A dictionary is a collection which is unordered, changeable and


indexed. In Python dictionaries are written with curly brackets,
and they have keys and values pair.

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionaries Functions

• Accessing Items
You can access the items of a dictionary by referring to its key name, inside
square brackets:

Get the value of the "model" key:


x = thisdict["model"]

There is also a method called get() that will give you the same result:
x = thisdict.get("model")

• Changing Values
THISDICT = {
"BRAND": "FORD",
"MODEL": "MUSTANG",
"YEAR": 1964
}
THISDICT["YEAR"] = 2018
Dictionaries Functions contd…

• Add Items

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)

• Remove Items

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Dictionaries Functions contd…

• Clear() Method

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)

• Copy() Method

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
Sets

• A Python set is the collection of the unordered items. Each


element in the set must be unique, immutable, and the sets
remove the duplicate elements. Sets are mutable which
means we can modify it after its creation.
• Unlike other collections in Python, there is no index attached
to the elements of the set, i.e., we cannot directly access any
element of the set by the index. However, we can print them
all together, or we can get the list of elements by looping
through the set.

Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday",


"Saturday", "Sunday"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
Sets Functions

• Set() Method
Example
Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)

• Add() Method
Example
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nAdding other months to the set...");
Months.add("July");
Months.add ("August");
print("\nPrinting the modified set...");
print(Months)
print("\nlooping through the set elements ... ")
for i in Months:
print(i)
Sets Functions contd…

• Update() Method
Example
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nupdating the original set ... ")
Months.update(["July","August","September","October"])
print("\nprinting the modified set ... ")
print(Months)

• Discard() Method
Example
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.discard("January");
months.discard("May");
print("\nPrinting the modified set...");
print(months)
print("\nlooping through the set elements ... ")
for i in months:
print(i)
Sets Functions contd…

• Delete() Method
Example
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.remove("January");
months.remove("May");
print("\nPrinting the modified set...");
print(months)
Lambda Expression

• Python Lambda Functions are anonymous function means that the function is without a
name. As we already know that the def keyword is used to define a normal function in
Python. Similarly, the lambda keyword is used to define an anonymous function in Python.

• Syntax: lambda arguments: expression

Example 1
# declare a lambda function
greet = lambda : print('Hello World')

# call lambda function


greet()

# Output: Hello World

Example 2
# lambda that accepts one argument
greet_user = lambda name : print('Hey there,', name)

# lambda call
greet_user('Delilah')

# Output: Hey there, Delilah

You might also like