Function
A function is a block of code that performs a task. It can be called and reused multiple times.
1. no return function
2. return function
Syntax: Python Collection(Arrays)
There are four collection data types in the Python programming language:
• List
• Tuple
• Set
• Dictionary
List
List is a collection which is ordered and changeable. Allows duplicate members. Access the list items by
referring to the index number. Python has a set of built-in methods that you can use on lists.
Method Description
append(value) Adds an element at the end of the list
len() To determine how many items have in list
insert(position, value) Adds an element at the specified position
count(value) Returns the number of elements with the specified value
index(value) Returns the index of the first element with the specified value
remove(value) Removes the element with the specified value
pop(position) Removes the element at the specified position
reverse() Reverse the order of the list
sort() Sorts the list
Example (1)
lst=[10,20,30,40,50,10]
print(lst)
print("Length=",len(lst))
print("Count 10=",lst.count(10))
print("Index 10=",lst.index(10))
lst.append(100)
lst.insert(2,1000)
print("After Append ",lst)
Example (2)
lst2=list(range(1,11))
print(lst2)
print("Sum=",sum(lst2))
lst2.insert(1,200)
print("Now Lst2=",lst2)
Example (3)
extend() -This function adds the elements of one list to the end of another list. It returns the extended list.
lstOne=[1,2,3]
lstTwo=[100,200]
lstOne.extend(lstTwo)
print("lstOne=",lstOne)
lstOne.remove(3)
print("After Remove lstOne=",lstOne)
print("lstOne pop",lstOne.pop())
print("lstOne pop",lstOne.pop())
print("lstOne pop",lstOne.pop(0))
print("lstOne=",lstOne)
Example (4)
lst=[10,-2,40,100,12]
lst.reverse()
print("Reverse lst=",lst)
lst.sort()
print(lst)
lst.sort(reverse=True)
print(lst)
Example (5)
The id() function in Python is used to return a unique id for an object. The id() function returns an identity of an
object. The id() function is useful to determine the type of an object and also to compare two objects.
lst2=lst[:]
lst.append(10245)
print(lst2)
print("ID=",id(lst))
print("ID=",id(lst2))
Tuple
A tuple is a collection which is ordered and unchangeable. Cannot add items after create the tuple and
remove items in a tuple. So, assign the items in a tuple while the tuple creation. In Python tuples are written
with round brackets.
Method Description
len() To determine how many items have in tuple
Example (6)
print("Tuple")
myTuple="John",
print("type=",type(myTuple))
print(myTuple)
print(myTuple[0])
student=(("John",20),("Su",15))
print(student)
print(student[0])
Example (7)
myTuple="John",20
print(myTuple)
print("Name=",myTuple[0])
print("Age=",myTuple[1])
Example (8)
students=(("Rose",16),("Susan",15))
print(students)
print(students[0])
print(students[1])
Set
A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.Once a
set is created, cannot change its items, but can add and remove items. Note: Sets are unordered, so the items
will appear in a random order.
Method Description
add(value) To add one item to a set
del() Delete the set
remove(value) To remove an item in a set (Note : If the item to remove does not exist, will raise an
error)
Example (9)
centre={"psd","mng","tgz","hld1","hld2"}
print(centre)
print(sorted(centre),len(centre))
del(centre)
print(centre)
Example (10)
numbers = {21, 34, 54, 12}
print('Initial Set:',numbers)
numbers.add(32)
print('Updated Set:', numbers)
Example (11)
programming = {'PHP', 'Java', 'Python'}
print('Initial Set:', programming)
removedValue = programming.remove('Java')
print('Set after remove():', programming)
programming.update(['VB','C','Ruby'])
print('Set after update():', programming)
Dictionary
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. Adding an item to the dictionary is done by using a new
index key and assigning a value to it. Can access the items of a dictionary by referring to its key name.
Example (12)
mark1={"Myan":40,
"Eng":60,
"Math":72}
mark2={"Myan":80,
"Eng":70,
"Math":62}
print(mark1)
print(mark2)
Exercise(1)
Write a Python program to display the first and last colors from the following list.
#left to right -> start 0
#right to left -> start -1
def FunctionName(parameters):
Statements
Example(1)
def showMsg(): #function definition
print("Hello World")
print("Python Program")
print("test Function")
def sum(x,y): #function definition
print("Sum=",x+y)
print("do somthing")
showMsg() # function calling
sum(1,2) # function calling
single value return function
Example(2)
def sum(x,y):
return x+y
print("Sum
print("Total=",result)
print("Average=",result/2)
Example(3)
def max_Num(a,b):
if(a>b):
return a
else:
return b
a=int(input("Enter first num:"))
b=int(input("Enter first num:"))
print("Maximum Number=",max_Num(a,b))
Global Variable
A global variable in Python is a variable that is declared outside of any function or class and is accessible from
anywhere in the program. Global variables are usually used to store information that needs to be accessed by
multiple functions or classes.
Example(4)
x="orginal"
def changeOriginal():
y="inside function"
global x #global
x="Update Value"
print(y)
changeOriginal()
print(x)
Default Parameter
Example(5)
def show_Greeting(name="Susan"):
print("Have a nice day!",name)
show_Greeting("Michael")
show_Greeting()
Example(6)
def show_Greeting1(name="John",age=30,phone=9567543):
print("Name!",name)
print("Age!",age)
print("Phone
show_Greeting1()
Exercise
Write a Python program to calculate the difference between a given number and 17. If the number is
greater than 17, return twice the absolute difference.