0% found this document useful (0 votes)
6 views18 pages

Unit 2

This document provides a comprehensive overview of functions and strings in Python, detailing how to create, call, and manage functions with various types of arguments, including default and arbitrary arguments. It also covers string manipulation techniques such as slicing, modifying, and formatting strings, along with examples. Additionally, it introduces lists, explaining their properties, methods for accessing and modifying list items, and operations such as sorting and copying.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views18 pages

Unit 2

This document provides a comprehensive overview of functions and strings in Python, detailing how to create, call, and manage functions with various types of arguments, including default and arbitrary arguments. It also covers string manipulation techniques such as slicing, modifying, and formatting strings, along with examples. Additionally, it introduces lists, explaining their properties, methods for accessing and modifying list items, and operations such as sorting and copying.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

UNIT-II

Functions
A function is a block of code which only runs when it is called.

Creating a Function
In Python a function is defined using the def keyword:
def my_function():
print("Hello from a function")

Calling a Function
To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello from a function")

my_function()
OUTPUT: Hello from a function

Arguments
Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")
OUTPUT: Emil Refsnes
Tobias Refsnes
Linus RefsnesTry it Yourself »

Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information
that are passed into a function.
Number of Arguments
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the function
with 2 arguments, not more, and not less.

Example
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + " " + lname)

my_function("Emil", "Refsnes")

OUTPUT: Emil Refsnes

Arbitrary Arguments, *args


If you do not know how many arguments that will be passed into your function,
add a * before the parameter name in the function definition.

Example
If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

OUTPUT: The youngest child is Linus

Keyword Arguments
You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

OUTPUT: The youngest child is Linus


Arbitrary Keyword Arguments,
**kwargs
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.

Example
If the number of keyword arguments is unknown, add a double ** before the
parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")

OUTPUT: His last name is Refsnes

Default Parameter Value


The following example shows how to use a default parameter value.

If we call the function without argument, it uses the default value:

Example
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
OUTPUT: I am from Sweden
I am from India
I am from Norway
I am from Brazil

Passing a List as an Argument


You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the function.
Example
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)
OUTPUT: apple
banana
cherry

Return Values
To let a function return a value, use the return statement:

Example
def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))
OUTPUT: 15
25
45

The pass Statement


function definitions cannot be empty, but if you for some reason have
a function definition with no content, put in the pass statement to avoid
getting an error.

Example
def myfunction():
pass
OUTPUT:NO ERROR
1. Write a program to define a function with multiple return values.
def name():
return "John","Armin"

# print the tuple with the returned values


print(name())

# get the individual items


name_1, name_2 = name()
print(name_1, name_2)

output: ('John', 'Armin')


John Armin

2. Write a program to define a function using default arguments.


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: Sum: 5
Sum: 10
Sum: 15

Strings
Arrays
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])
output:e

Looping Through a String


Since strings are arrays, we can loop through the characters in a string, with
a for loop.
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
output: b
a
n
a
n
a

String Length
To get the length of a string, use the len() function.

Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
output:13

Check String
character is present in a string, we can use the keyword in.

Example
Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)
output; True

Use it in an if statement:

Example
Print only if "free" is present:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
output: Yes, 'free' is present.

Slicing Strings
You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon

Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
output: llo

Example
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])
output: Hello

Example
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
output: llo, World!

Negative Indexing
Use negative indexes to start the slice from the end of the string:

Example
Get the characters:

From: "o" in "World!" (position -5)

To, but not included: "d" in "World!" (position -2):


b = "Hello, World!"
print(b[-5:-2])
output: orl

Modify Strings
Upper Case
Example
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
output: HELLO, WORLD!

Lower Case
Example
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
output: hello, world!

Remove Whitespace
Example
The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
output: Hello, World!

Replace String
Example
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
output: Jello, World!

Split String
Example
The split() method splits the string into substrings if it finds instances of the
separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
output: ['Hello', ' World!']

String Concatenation
To concatenate, or combine, two strings you can use the + operator.

Example
Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c = a + b
print(c)
output: HelloWorld

Example
To add a space between them, add a " ":
a = "Hello"
b = "World"
c = a + " " + b
print(c)
output: Hello World

tring Format
As we learned in the Python Variables chapter, we cannot combine strings and
numbers like this:

Example
age = 36
txt = "My name is John, I am " + age
print(txt)
output: txt = "My name is John, I am " + age
TypeError: must be str, not int
But we can combine strings and numbers by using f-strings or
the format() method!

Example
Create an f-string:
age = 36
txt = f"My name is John, I am {age}"
print(txt)
output: My name is John, I am 36
Placeholders and Modifiers
A placeholder can contain variables, operations, functions, and modifiers to
format the value.

Example
Add a placeholder for the price variable:
price = 59
txt = f"The price is {price} dollars"
print(txt)
output: The price is 59 dollars
1. Write a program to find the length of the string without using any library
functions.
string=input("Enter string:")
count=0
for i in string:
count=count+1
print("Length of the string is:")
print(count)
output: Enter string:lalunaik
Length of the string is:
8
2. Write a program to check if the substring is present in a given string or
not.
tring=input("Enter string:")
sub_str=input("Enter word:")
if(string.find(sub_str)==1):
print("Substring not found in string!")
else:
print("Substring in string!")
output: Enter string:lalu
Enter word:lalu
Substring in string!

Lists
List
Lists are used to store multiple items in a single variable.

ExampleGet your own Python Server


Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
output: ['apple', 'banana', 'cherry']

List Items
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.

Example
Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
output: ['apple', 'banana', 'cherry', 'apple', 'cherry']

List Length
To determine how many items a list has, use the len() function:

Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
output: 3

List Items - Data Types


List items can be of any data type:

Example
String,int and boolean data types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
output: ['apple', 'banana', 'cherry']
[1, 5, 7, 9, 3]
[True, False, False]

A list can contain different data types:


Example
A list with strings, integers and boolean values:
list1 = ["abc", 34, True, 40, "male"]
print(list1)
['abc', 34, True, 40, 'male']

Access Items
List items are indexed and you can access them by referring to the index
number:

ExampleGet your own Python Server


Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
output: banana

Negative Indexing
Negative indexing means start from the end

-1 refers to the last item, -2 refers to the second last item etc.

Example
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
output: cherry

Range of Indexes
You can specify a range of indexes by specifying where to start and where to
end the range.

Example
Return the third, fourth, and fifth item:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
output: ['cherry', 'orange', 'kiwi']
Example
This example returns the items from the beginning to, but NOT including, "kiwi":
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
output: ['apple', 'banana', 'cherry', 'orange']

Example
This example returns the items from "cherry" to the end:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
output: ['cherry', 'orange', 'kiwi', 'melon', 'mango']

Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of the list:

Example
This example returns the items from "orange" (-4) to, but NOT including
"mango" (-1):
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
output: ['orange', 'kiwi', 'melon']

Change Item Value


To change the value of a specific item, refer to the index number:

ExampleGet your own Python Server


Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
output: ['apple', 'blackcurrant', 'cherry']

Append Items
To add an item to the end of the list, use the append() method:
ExampleGet your own Python Server
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
output: ['apple', 'banana', 'cherry', 'orange']

Insert Items
To insert a list item at a specified index, use the insert() method.

Example
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
output: ['apple', 'orange', 'banana', 'cherry']

Remove Specified Item


The remove() method removes the specified item.

ExampleGet
Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
output: ['apple', 'cherry']

Loop Through a List


You can loop through the list items by using a for loop:

ExampleGet
Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
output: apple
banana
cherry
Loop Through the Index Numbers
You can also loop through the list items by referring to their index number.

Use the range() and len() functions to create a suitable iterable.

Example
Print all items by referring to their index number:
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
output: apple
banana
cherry

Example
Print all items, using a while loop to go through all the index numbers
thislist = ["apple", "banana", "cherry"]
i = 0
while i < len(thislist):
print(thislist[i])
i = i + 1
output: apple
banana
cherry

Sort List Alphanumerically


List objects have a sort() method that will sort the list alphanumerically,
ascending, by default:

xampleGet your own Python Server


Sort the list alphabetically:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
output: ['banana', 'kiwi', 'mango', 'orange', 'pineapple']

Example
Make a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
output: ['apple', 'banana', 'cherry']

Example
Join two list:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)
output: ['a', 'b', 'c', 1, 2, 3]

1. Write a program to perform the given operations on a list:


i. addition ii. Insertion iii. slicing
# i).Python program to find sum of elements in list

total = 0
# creating a list
list1 = [11, 5, 17, 18, 23]
# Iterate each element in list
# and add them in variable total
for ele in range(0, len(list1)):
total = total + list1[ele]
# printing total value
print("Sum of all elements in given list: ", total)
output: Sum of all elements in given list: 74
ii. Insertion
# creating a list
#inserts an item at a specific index in a list.
fruit = ["banana","cherry","grape"]
fruit.insert(1,"apple")
print(fruit)

iii. slicing
my_list = [1, 2, 3, 4, 5]

print(my_list[:])

output: [1, 2, 3, 4, 5]

my_list = [1, 2, 3, 4, 5]
print(my_list[2:])

output: [3, 4, 5]

my_list = [1, 2, 3, 4, 5]

print(my_list[:2])

output: [1, 2]

my_list = [1, 2, 3, 4, 5]

print(my_list[2:4])

output: [3, 4]

Write a program to perform any 5 built-in functions by taking any list.

List Methods
Python has a set of built-in methods that you can use on lists.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

You might also like