0% found this document useful (0 votes)
7 views

UNIT - 3_Python

Uploaded by

papakhanna78
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

UNIT - 3_Python

Uploaded by

papakhanna78
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 96

UNIT - 3

Python Complex data types

18-11-2024 Ankita Sharma Unit 3 1


Using string data type and string operations
• String is a sequence which is made up of one or more UNICODE
characters. Here the character can be a letter, digit, whitespace
or any other symbol.
• A string can be created by enclosing one or more characters in
single, double or triple quote.
Example : str1 = 'Hello World!‘
str2 = "Hello World!“
str3 = """Hello World!""“
str4 = '''Hello World!''
18-11-2024 Ankita Sharma Unit 3 2
string "Hello, World" is basically a sequence ['H', 'e', 'l', 'l', 'o', ',', ' ',
'W', 'o', 'r', 'l', 'd'] and its length can be calculated by counting number
of characters inside the sequence, which is 12.

Note: Yes, space, comma everything inside those quotes will be a


character if the length is 1.

18-11-2024 Ankita Sharma Unit 3 3


• In Python, there is no character data type. Instead characters are just
treated as a string of length 1.

Declaration of Strings
mystring = "This is not my first String"
print (mystring)
Output : This is not my first String

Accessing Characters in a String

• Can access each individual character of a string too , by using index


numbers for this purpose.
• To access first character of mystring, we can do following:
print
18-11-2024
(mystring[0]) Ankita Sharma Unit 3 4
• To gives 6th character of str1
>>> str1[2+4] **can also write like this**

• #gives error as index must be an integer


>>> str1[1.5]
TypeError: string indices must be integers

• Python allows an index value to be negative also. Negative indices are


used when we want to access the characters of the string from right
to left.
• Starting from right hand side, the first character has the index as -1
and the last character has the index –n where n is the length of the
string.
18-11-2024 Ankita Sharma Unit 3 5
18-11-2024 Ankita Sharma Unit 3 6
An inbuilt function len() in Python returns the length of the string that is passed
as parameter. For example, the length of string str1 = 'Hello World!' is 12.
#gives the length of the string str1
>>> len(str1)
12
#length of the string is assigned to n
>>> n = len(str1)
>>> print(n)
12
#gives the last character of the string
>>> str1[n-1]
'!'
#gives the first character of the string
>>> str1[-n]
18-11-2024
'H' Ankita Sharma Unit 3 7
• Refer string pdf shared in cse group for operations
available …

18-11-2024 Ankita Sharma Unit 3 8


Program for logic building :
1. Printing all letters except some using Python while loop
2. Converting numbers from decimal to binary using while loop
3. Finding the multiples of a number using while loop
4. Reversing a number using while loop in Python

18-11-2024 Ankita Sharma Unit 3 9


1.
i=0
word = "Hello"

#print all letters except e and o

while i < len(word):


if word[i] == "e" or word[i] =="o":
i += 1
continue

print("Returned letter",word[i])
i += 1
18-11-2024 Ankita Sharma Unit 3 10
3.
n = int(input("Enter an integer: "))

i=1
while i <= 10:
mul = i*n
i += 1
print(mul)

18-11-2024 Ankita Sharma Unit 3 11


4.
n = int(input("Enter a number: "))
rev = 0

while n!=0:
r = n%10
rev = rev * 10 + r
n = n//10

print("Reversed number:",rev)

18-11-2024 Ankita Sharma Unit 3 12


Reassigning Strings
A string can only be replaced with new string since its content
cannot be partially replaced. Strings are immutable in Python.

Example 1:

str = "HELLO"
str[0] = "h"
print(str)

18-11-2024 Ankita Sharma Unit 3 13


However, in example 1, the string str can be assigned completely
to a new content as specified in the following example.

Example 2 :

str = "HELLO"
print(str)
str = "hello"
print(str)

18-11-2024 Ankita Sharma Unit 3 14


Deleting the String
As we know that strings are immutable. We cannot delete or remove the
characters from the string. But we can delete the entire string using
the del keyword.

Example :
str1 = "JAVATPOINT"
del str1
print(str1)

Output : NameError: name 'str1' is not defined

18-11-2024 Ankita Sharma Unit 3 15


String Operators

Assume a as Hello.

18-11-2024 Ankita Sharma Unit 3 16


18-11-2024 Ankita Sharma Unit 3 17
18-11-2024 Ankita Sharma Unit 3 18
String Concatenation
Concatenation is the process of combining strings. In Python, we use
the + operator to concatenate strings.

x = "Good"
y = "Work"
print(x + y) # Output: GoodWork
To add a space between words, we can include a space in one of the
strings or add a space string:

print(x + " " + y) # Output: Good Work

18-11-2024 Ankita Sharma Unit 3 19


In Python, we can't directly combine strings and integers using the +
operator. We need to convert integers to strings first

age = 25
message = "I am " + str(age) + " years old."
18-11-2024 Ankita Sharma Unit 3 20
print(message) # Output: I am 25 years old.
String Repetition
• It allow you to repeat a string by certain number
• We can repeat a string multiple times using the * operator:

string = "hello "


result = string * 3
print(result)

# Output: hello hello hello

18-11-2024 Ankita Sharma Unit 3 21


18-11-2024 Ankita Sharma Unit 3 22
Python List Slicing
• This is incredibly useful when dealing with large datasets,
manipulating specific ranges of data, or simply extracting the
information you need.

• To perform slicing, you use square brackets [] along with a special


syntax.
• The basic syntax for slicing a list is:

18-11-2024 Ankita Sharma Unit 3 23


• start: The index at which the slice begins (inclusive). If omitted,
the slice starts from the beginning of the list.
• stop: The index at which the slice ends (exclusive). If omitted,
the slice goes up to the end of the list.
• step: The interval between elements in the slice. If omitted, the
default step is 1

18-11-2024 Ankita Sharma Unit 3 24


Basic Slicing :

Let’s look at a simple example of list slicing. Imagine you have a


list of letters named L:

18-11-2024 Ankita Sharma Unit 3 25


Slicing with Negative Indices :

18-11-2024 Ankita Sharma Unit 3 26


Slicing with Positive and Negative Indices
Python allows you to mix positive and negative indices within the
same slice.

18-11-2024 Ankita Sharma Unit 3 27


Let’s take our familiar list of letters as an example. If you want to get
every other element starting from index 2 (the letter ‘c’) and going up
to, but not including, index 7, you can use a step value of 2:

18-11-2024 Ankita Sharma Unit 3 28


Negative Step
A negative step reverses the order of elements. In the example
below, the slice starts at index 6 and ends before index 1, taking
every second element in reverse order.

18-11-2024 Ankita Sharma Unit 3 29


Slice at the Beginning and to the End
When you omit the start index, the slice begins at the start of the
list. So, L[:stop] is equivalent to L[0:stop].

For example, to get the first three items of a list named L, you
would use L[:3].

18-11-2024 Ankita Sharma Unit 3 30


On the other hand, when you omit the stop index, the slice goes up
to the end of the list. So, L[start:] is equivalent to L[start:len(L)].

For example, to obtain the last three items, you’d use L[6:].

18-11-2024 Ankita Sharma Unit 3 31


Reversing a List
Omitting both the start and stop indices while specifying a negative
step value of -1 reverses the order of elements in the slice.

18-11-2024 Ankita Sharma Unit 3 32


Replacing a Slice
Slicing can also be used to modify lists. You can replace elements
within a list by assigning a new list to a slice of the original list.

For example, if you want to replace the elements from index 1 to 3


(inclusive) with the values 1, 2, and 3, you can do:

18-11-2024 Ankita Sharma Unit 3 33


We can replace a single element with multiple elements using this
technique.

18-11-2024 Ankita Sharma Unit 3 34


Inserting Elements

To insert elements at the beginning of a list, you can use a slice


starting from the beginning (L[:0]) and assign the new elements
to it.

18-11-2024 Ankita Sharma Unit 3 35


If you want to insert elements at the end, you can use a slice that
starts at the current length of the list (L[len(L):]) and assign the new
elements there.

18-11-2024 Ankita Sharma Unit 3 36


Removing a Slice
You can remove multiple elements from the middle of a list
using slicing techniques. One way to do this is by assigning an
empty list to the desired slice.

18-11-2024 Ankita Sharma Unit 3 37


Alternatively, you can use the del statement to achieve the same
result.

18-11-2024 Ankita Sharma Unit 3 38


Copying the Entire List
In Python, when you assign one list to another (e.g., new_list =
old_list), you’re not creating a true copy.

Instead, you’re creating a new reference that points to the same


underlying list object.

Any changes made to either new_list or old_list will affect both, as


they share the same data.

18-11-2024 Ankita Sharma Unit 3 39


To create an actual copy of the list, you can use the slicing
operator. By omitting both the start and stop indices (L1[:]), you
create a copy of the entire list L1.

L1 = ['a', 'b', 'c', 'd', 'e']

# Create a shallow copy of L1


L2 = L1[:]
print(L2)

# Output: ['a', 'b', 'c', 'd', 'e']

18-11-2024 Ankita Sharma Unit 3 40


Note :- ‘is ‘ keyword
is keyword in Python is used to check if two variables refer to the
same object. The is operator returns True if the two objects are the
same and False if they are not.

Example 1
x = ["apple", "banana", "cherry"] and y = x.
In this example, x is y will return True because x and y are the same
object.

The is operator is also known as the identity operator. It's different


from the == operator, which checks if the values of two objects are
equal.
18-11-2024 Ankita Sharma Unit 3 41
This example shows working of ‘is’ keyword also .

18-11-2024 Ankita Sharma Unit 3 42


Out of Range Indices

When you use indices that go beyond the boundaries of a list,


Python adjusts the indices to the nearest valid values instead of
causing an error. For example:

The slice includes all elements from index 3 to the end.


18-11-2024 Ankita Sharma Unit 3 43
18-11-2024 Ankita Sharma Unit 3 44
Note :

18-11-2024 Ankita Sharma Unit 3 45


Python Tuple (With Examples)

• You may want to construct a list of objects that cannot be altered


while the application is running. Python Tuples are utilized to
meet this requirement.
• They are frequently utilized internally in many of the systems on
which we rely, such as databases.
• In Python, tuples are a fundamental data structure. Tuples store
data in the sequence in which we input it.

18-11-2024 Ankita Sharma Unit 3 46


Python Tuple
Python Tuple is an immutable (unchangeable) collection of various
data type elements.

Creating a Tuple
A tuple is formed by enclosing all of the items (elements)
in parentheses () rather than square brackets [], and each element is
separated by commas.Tuple can also be created without parantheses.

18-11-2024 Ankita Sharma Unit 3 47


A tuple can contain any number of objects of various sorts (integer,
float, list, string, etc.)

You can also specify nested tuples, which have one or more entries
that are lists, tuples, or dictionaries.

18-11-2024 Ankita Sharma Unit 3 48


Question : give output of the following

18-11-2024 Ankita Sharma Unit 3 49


Output :

18-11-2024 Ankita Sharma Unit 3 50


Access Tuple Elements

Indexes are integers that range from 0 to n-1, where n is the


number of entries. The elements of a tuple can be accessed in a
variety of ways.

18-11-2024 Ankita Sharma Unit 3 51


Output :

18-11-2024 Ankita Sharma Unit 3 52


ERROR :

18-11-2024 Ankita Sharma Unit 3 53


EXAMPLE :

18-11-2024 Ankita Sharma Unit 3 54


18-11-2024 Ankita Sharma Unit 3 55
18-11-2024 Ankita Sharma Unit 3 56
f-strings are a way to create concatenated strings from
variables and values. They start with the letter “f” followed
by a pair of square brackets “[” and end with a pair of
square brackets “]”. So, inside these square brackets, we
can specify the values ​we want to concatenate.

For example, suppose we want to concatenate a string


with a name and an address. Using the f-string, we can
write the f-string using the values ​of the variable “name”
and “address” to form the concatenated string. Look:

18-11-2024 Ankita Sharma Unit 3 57


name = "João"
address = "Road A, 123"

print(f"Hello, {name}! You live at {address}.")


The code output will be:

Hello, João! You live at Road A, 123.


Another advantage of f-strings is that you can use string formats to insert numeric
or boolean values ​directly into the concatenated string. For example:

your_idade = 25
if_you_are_working = True

print(f"You are {your_age} years old and currently working.")


The code output will be:

You are 25 years old and currently


18-11-2024
working. ,….Thus, f-strings make string
Ankita Sharma Unit 3 58
concatenation even simpler and more readable in Python.
Tuple Immutable

Immutable Nature : Tuples cannot be changed once created . Any


attempt to modify a tuple will result in an error.
Tuple Immutability : tuple1=(1,2,3,4)
#tuple1[1]=5 #TypeError

18-11-2024 Ankita Sharma Unit 3 59


18-11-2024 Ankita Sharma Unit 3 60
Tuple Methods :

18-11-2024 Ankita Sharma Unit 3 61


count() Method

The count() method counts the number of occurrences of a specified


element in a tuple functions in python.

It takes a single argument, which is the element to be counted.

18-11-2024 Ankita Sharma Unit 3 62


Updating Tuples

Since tuple methods in python are immutable, you cannot


update their elements directly. However, you can update
tuples indirectly by converting them into lists, modifying the
list, and then converting it back into a tuple. Here’s an
example:

18-11-2024 Ankita Sharma Unit 3 63


18-11-2024 Ankita Sharma Unit 3 64
Deleting Tuples
Tuples, being immutable, cannot be deleted directly. However, we
can use the ‘del’ keyword to delete the entire tuple. Here’s an
example:

18-11-2024 Ankita Sharma Unit 3 65


index() Method
The index() method finds the index of the first occurrence of a
specified element in a tuple.

It takes a single argument, which is the element to be searched.


Here’s an example:

18-11-2024 Ankita Sharma Unit 3 66


len() Method

The len() method is used to find the number of elements in a tuple.

It takes no arguments and returns an integer value representing the


length of the tuple. Here’s an example:

18-11-2024 Ankita Sharma Unit 3 67


sorted() Method

The sorted() method sorts the elements of a tuple in ascending


order. It takes no arguments and returns a new tuple with the
sorted elements. Here’s an example:

18-11-2024 Ankita Sharma Unit 3 68


min() and max() Methods
The min() and max() methods find the smallest and largest
elements in a tuple, respectively. They take no arguments and
return the smallest and largest elements, respectively. Here’s
an example:

18-11-2024 Ankita Sharma Unit 3 69


tuple() Function

The tuple() function converts an iterable object, such as a list or a


string, into a tuple. It takes a single argument, which is the iterable
object to be converted. Here’s an example:

18-11-2024 Ankita Sharma Unit 3 70


STRING MANIPULATION

Python has several built-in functions in the standard library to help


programmers manipulate strings in different ways.

Let's learn more about these functions:-

• Concatenation of Strings Concatenation means to join two or more


strings into a single string. + operator is used to concatenate strings.
For example,
word1 = 'Coding'
word2 = ' lines'
print(word1 + word2)
18-11-2024 Ankita Sharma Unit 3 71
• Replace Part of a String

The replace() method is used to replace a part of the string with


another string. As an example, let's replace 'ing' in Coding with
'ers,' making it Coders.

string = 'Coding'
string = string.replace('ing', 'ers')
print(string)

Output: Coders

18-11-2024 Ankita Sharma Unit 3 72


• Count characters

count() method is used to count a particular character in the string.

18-11-2024 Ankita Sharma Unit 3 73


• Split a String

It is a very common practice to split a string into smaller strings.


In Python, we use the split() function to do this. It splits the string
from the identified separator and returns all the pieces in a list.

string.split(separator, maxsplit)

separator: the string splits at this separator.


maxsplit (optional): tells how many splits to do

18-11-2024 Ankita Sharma Unit 3 74


Example:
String = ‘welcome to coding line’

#splitting across the whitespace .

myList = string.split(“ “)
Print(myList)

Output:
[‘welcome’,’to’,coding’,’line’]

18-11-2024 Ankita Sharma Unit 3 75


• find( ) function
The find() function looks for the first occurrence of the provided
value. If the value is not found in that string, it returns -1. The
value can be any character or a substring.

string = 'Welcome to Coding lines'


index = string.find('t')

print(index)

Output : 8

18-11-2024 Ankita Sharma Unit 3 76


• join() Function

This method is used to join a sequence of strings with some


operator. The join() operator will create a new string by joining
every character of the sequence with a specified character,
including whitespaces.

Note: The join() method only accepts strings. If any element in


the iteration is of a different type, an error will be thrown.

18-11-2024 Ankita Sharma Unit 3 77


String =‘welcome to coding line’

String=“ ,”.join(string)

Print(string)

Output :
W,e,l,c,o,m,e, ,t,o, ,c,o,d,i,n,g, ,l,i,n,e,s

18-11-2024 Ankita Sharma Unit 3 78


Some More Important String Functions

18-11-2024 Ankita Sharma Unit 3 79


18-11-2024 Ankita Sharma Unit 3 80
List Manipulation

18-11-2024 Ankita Sharma Unit 3 81


append():

copy():

18-11-2024 Ankita Sharma Unit 3 82


clear():

extend(): In the code below, we will extend the list by adding


elements from another list.

18-11-2024 Ankita Sharma Unit 3 83


insert(): In the code below, we will insert an element at a
specific position in the list.

pop(): In the code below, we will remove the last element


from the list

18-11-2024 Ankita Sharma Unit 3 84


remove(): In the code below, we will remove the first occurrence of
a specified element from the list

**Example of all remaining functions we have already


discussed many times **

18-11-2024 Ankita Sharma Unit 3 85


FUNCTIONS In Python :
Block of statements that perform a specific task.
(note ,.. Can observe loop , as we know loop will execute as much
range is mentioned but function can be used again n again ).

Suppose we have to sum two digit so we write code in our code


editor. Like;

18-11-2024 Ankita Sharma Unit 3 86


Suppose in same code we again have to sum and then after few
lines of , again repeatedly sum have to be calculated in code.

So this is repetation of same code .. This is also called redundant .


Redundant code is sign of bad programming , because of this we
make function .

So to write function we have to use keyword ‘def’ .

So , Function we can say is a line of code which takes some input


and parameter as input and return output.

18-11-2024 Ankita Sharma Unit 3 87


18-11-2024 Ankita Sharma Unit 3 88
def function_name(parameter1, parameter2) // Whatever it takes as input , it is parameter

Let’s take an example of finding sum of two numbers :

18-11-2024 Ankita Sharma Unit 3 89


return Keyword :

A return statement is used to end the execution of the function call


and “returns” the result (value of the expression following the
return keyword) to the caller.

The statements after the return statements are not executed. If the
return statement is without any expression, then the special value
None is returned.

Note: Return statement can not be used outside the function

18-11-2024 Ankita Sharma Unit 3 90


Example :
Program for average of
three number :

18-11-2024 Ankita Sharma Unit 3 91


Examples :

18-11-2024 Ankita Sharma Unit 3 92


Functions in Python can be :
- build-in
- User defined

18-11-2024 Ankita Sharma Unit 3 93


Practise Questions :

1. Program to Compute LCM using function


2. Program to print the length of a list.(list is the parameter)

Questions Provided in class from previous year paper …

18-11-2024 Ankita Sharma Unit 3 94


1
def compute_lcm(x, y):

# choose the greater number


if x > y:
greater = x
else:
greater = y

while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1

return lcm

num1 = 54
num2 = 24

print("The L.C.M. is", compute_lcm(num1, num2)).

18-11-2024 Ankita Sharma Unit 3 95


Discused Function Programs in class

Links : https://www.programiz.com/python-
programming/examples

Link for Dictionary Manipulation :


https://cleverzone.medium.com/dictionaries-manipulation-
method-in-python-f69c3cf740b8

18-11-2024 Ankita Sharma Unit 3 96

You might also like