Unit 3
Unit 3
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
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 (=)
Ex:
def items(item1,item2,item3):
print("It is " + item1)
items(item1="Mango",item2="Oranges",item3="Grapes")
LOCAL and GLOBAL scope
Local and Global scope:
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.
Example
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
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)
list1=[1,5,9]
print(list1[2])
t1=(1,5,9)
print(t1[2])
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)
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"]
print(newlist)
Dictionaries
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:
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
• 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.
Example 1
# declare a lambda function
greet = lambda : print('Hello World')
Example 2
# lambda that accepts one argument
greet_user = lambda name : print('Hey there,', name)
# lambda call
greet_user('Delilah')