Unit 3 Python
Unit 3 Python
FUNCTIONS,
LIST
TUPLE,
DICTIONARIES
Functions in PYTHON
A function is a group of related statements that
performs a specific task.
Functions are the most important aspect of an
application.
A function can be defined as the organized block
of reusable code, which can be called whenever
required
Pass data, known as parameters, into a function.
A function can return data as a result.
Functions in PYTHON
Creating a Function
In Python a function is defined using the
def keyword:
Syntax:
def my_function(parameters):
function_block
return expression
Functions in PYTHON
Example
Function definition
def hello_world():
print("hello world")
function calling
hello_world()
Functions in PYTHON
The return statement
return [expression_list]
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
Operations on Dictionaries
Method II:
>>> for key,value in dict1.items():
print(key,':',value)
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
Dictionary Methods
clear()
Dictionary clear() method deletes all the
key:value pairs from the dictionary.
fromkeys()
Dictionary fromkeys() method creates a
new dictionary from the keys of given
dictionary and an optional default value
for the key-value pairs.
Dictionary Methods
Ex:
d = {"a": 4, "b": 5, "c": 6}
d1 = dict.fromkeys(d, 2)
print(d1)
get()
Dictionary get() method returns the value
for the specified key. The key is specified
by passing as argument to get() method.
Dictionary Methods
items()
Dictionary items() method returns an
iterator of type dict_items.
We can iterate over each of the key, value
in the dictionary.
Also, the dict_items type support dynamic
update to the dictionary.
Dictionary Methods
d = {"a": 4, "b": 5, "c": 6}
for key, value in dictionary.items():
print(key, '-', value)
popitem()
Dictionary popitem() method removes the
last inserted key-value pair of specified
key, and returns this key-value pair.
dictionary = {"a": 4, "b": 5, "c": 6}
x = dictionary.popitem()
print(x)
print(dictionary)
setdefault()
Dictionary setdefault() method returns the
value of the specified key if the key is
present.
If the key is not present, setdefault() method
inserts a key-value pair with the default
value and returns the default value.
d = {"a": 4, "b": 5, "c": 6}
x = d.setdefault("b")
print(x)
y = d.setdefault("m", 0)
print(y) print(dictionary)
update()
Dictionary update() method updates the
key-value pairs of this dictionary with the
key-value pairs from the dictionary passed
as argument to update() method.
Values for the keys that are present are
updated, and the for the keys that are not
present, those key-value pairs are inserted.
dictionary = {"a": 4, "b": 5, "c": 6}
dictionary_1 = {"a": 8, "m": 2, "v": 7}
dictionary.update(dictionary_1)
print(dictionary)