WEEK- II PP
1) Write a program to define a function with multiple
return values
Return values using comma
CODE:
def name():
return
"Richard","Kewin"
# print the tuple with the returned values
print(name())
# get the individual items
name_1, name_2 = name()
print(name_1, name_2)
OUTPUT:-
OUTPUT: ----------------------------- Try on your own👏-----------------------------
Using a dictionary
CODE:
def name():
n1 = "Richard"
n2 = "Kelwin"
return {1:n1, 2:n2}
names = name()
print(names)
OUTPUT:-
OUTPUT: ----------------------------- Try on your own👏-----------------------------
2) Write a program to define a function using default arguments
Python Function Arguments:
CODE:
def add_numbers(a, b):
sum = a + b
print('Sum:', sum)
add_numbers(2, 3)
OUTPUT:-
OUTPUT: ----------------------------- Try on your own👏-----------------------------
Function Argument
with Default Values:
CODE:
def add_numbers( a =
7, b = 8):
sum = a + b
print('Sum:', sum)
# function call with two arguments
add_numbers(2, 3)
# function call with one argument
add_numbers(a = 2)
# function call with no arguments
add_numbers()
OUTPUT:-
OUTPUT: ----------------------------- Try on your own👏-----------------------------
Exp: Here, we have provided default values 7 and 8 for
parameters a and b respectively. Here's how this program works
1. add_numbers(2, 3)
Both values are passed during the function call.
Hence, these values are used instead of the default values.
2. add_numbers(2)
Only one value is passed during the function call. So,
according to the positional argument 2 is assigned to argument a, and the
default value is used for parameter b.
3. add_numbers()
No value is passed during the function call. Hence,
default value is used for both parameters a and b.
Python Keyword
Argument:
CODE:
def display_info(first_name, last_name):
print('First Name:',
first_name)
print('Last Name:',
last_name)
display_info(last_name = 'leo', first_name =
'joy')
OUTPUT:-
OUTPUT: ----------------------------- Try on your own👏-----------------------------
Exp: Hence, first_name in the function call is
assigned to first_name in the function definition. Similarly, last_name in the
function call is assigned to last_name in the function definition.
In such scenarios,
the position of arguments doesn't matter.
3) Write a program to find
the length of a string without using the library function in python
CODE:
my_string = "Hi students"
print("The string is :")
print(my_string)
my_count=0
for i in my_string:
my_count=my_count+1
print("The length of the string is ")
print(my_count)
OUTPUT:-
OUTPUT: ----------------------------- Try on your own👏-----------------------------
4) Write a program to check if
the substring is present in a given string or not
Check Python Substring in String using the If-Else
CODE:
# Take input from users
my_string = "I am a good student and i will
execute all the programs in python"
if "I am A " in my_string:
print("Yes! it is
present in the string")
else:
print("No! it is not
present")
OUTPUT:-
OUTPUT: ----------------------------- Try on your own👏-----------------------------
Check Python Substring in String using Find() method
CODE:
def check(string, sub_str):
if (string.find(sub_str)
== -1):
print("NO")
else:
print("YES")
# driver code
string = "Be a good student"
sub_str = "of"
check(string, sub_str)
OUTPUT:-
OUTPUT: ----------------------------- Try on your own👏-----------------------------
a)
Addition : Using the "+" Operator
CODE:
a = 15
b = 12
# Adding two numbers
res = a + b
print(res)
OUTPUT:-
OUTPUT: ----------------------------- Try on your own👏-----------------------------
Using
user input
CODE:
# taking user input
a = input("First number: ")
b = input("Second number: ")
# converting input to float and adding
res = float(a) + float(b)
print(res)
OUTPUT:-
OUTPUT: ----------------------------- Try on your own👏-----------------------------
Using
Function
CODE:
# creating a list
fruit = ["banana","cherry","mango","grape"]
fruit.insert(1,"kiwi")
print(fruit)
OUTPUT:-
OUTPUT: ----------------------------- Try on your own👏-----------------------------
# function to add two numbers
def add(a, b):
return a + b
# initializing numbers
a = 10
b = 5
# calling function
res = add(a,b)
print(res)
OUTPUT:-
OUTPUT: ----------------------------- Try on your own👏-----------------------------
b) Insertion:
Python List insert() method inserts an item at a specific index in a list.
CODE:
list1 = [ 1, 2, 3, 4, 5, 6, 7 ]
# insert 10 at 4th index
list1.insert(4, 10)
print(list1)
OUTPUT:-
OUTPUT: ----------------------------- Try on your own👏-----------------------------
Insertion in a List Before any Element:
CODE:
# Python3 program for Insertion in a
list
# before any element using insert() method
list1 = [ 1, 2, 3, 4, 5, 6 ]
# Element to be inserted
element = 13
# Element to be inserted before 3
beforeElement = 3
# Find index
index = list1.index(beforeElement)
# Insert element at beforeElement
list1.insert(index, element)
print(list1)
OUTPUT:-
OUTPUT: ----------------------------- Try on your own👏-----------------------------
c) Slicing: Retrieve All Characters
CODE:
s = "Hello, Students hope all are fine"
# Get the entire string
s2 = s[:]
s3 = s[::]
s4 = s [:]
print(s2)
print(s3)
print(s4)
OUTPUT:-
OUTPUT: ----------------------------- Try on your own👏-----------------------------
Get All Characters Before or After a Specific Position:
CODE:
s = "Hello, Students hope all are fine"
# Characters from index 7 to the end
print(s[6:])
# Characters from the start up to index 5
(exclusive)
print(s[:5])
OUTPUT:-
OUTPUT: ----------------------------- Try on your own👏-----------------------------
Demonstrating 5 simple built-in functions:
CODE:
# 1. len() - returns the length of an object
my_list = [10, 20, 30, 40, 50]
print("Length of the list:",
len(my_list))
# 2. sum() - sums the items of an iterable
print("Sum of the list elements:",
sum(my_list))
# 3. max() - returns the largest item in an
iterable
print("Maximum element in the list:",
max(my_list))
# 4. min() - returns the smallest item in an
iterable
print("Minimum element in the list:",
min(my_list))
# 5. abs() - returns the absolute value of a
number
negative_number = -100
print("Absolute value of -100:",
abs(negative_number))
OUTPUT:-
OUTPUT: ----------------------------- Try on your own👏-----------------------------
Demonstrating 5 more built-in
functions:
# 1. enumerate() - adds a counter to an iterable
my_list = ['apple', 'banana', 'cherry']
print("Using enumerate():")
for index, value in enumerate(my_list):
print(f"Index:
{index}, Value: {value}")
# 2. zip() - combines multiple iterables
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
print("\nUsing zip():")
for item1, item2 in zip(list1, list2):
print(item1, item2)
# 3. map() - applies a function to all items in an
input list
def square(x):
return x * x
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(square, numbers))
print("\nUsing map():", squared_numbers)
# 4. filter() - constructs an iterator from
elements of an iterable for which a function returns true
def is_even(x):
return x % 2 == 0
even_numbers = list(filter(is_even, numbers))
print("Using filter():", even_numbers)
# 5. reduce() - applies a function of two
arguments cumulatively to the items of a sequence (requires import)
from functools import reduce
def add(x, y):
return x + y
sum_of_numbers = reduce(add, numbers)
print("Using reduce():", sum_of_numbers)
OUTPUT:-
OUTPUT: ----------------------------- Try on your own👏-----------------------------