Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
32 views

Python Programming (Unit-3)

The document provides an overview of Python programming focusing on complex data types such as strings, lists, tuples, and dictionaries. It covers their definitions, creation, manipulation methods, and various built-in functions. Additionally, it includes examples and syntax for performing operations on these data types.

Uploaded by

shankarspshukla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Python Programming (Unit-3)

The document provides an overview of Python programming focusing on complex data types such as strings, lists, tuples, and dictionaries. It covers their definitions, creation, manipulation methods, and various built-in functions. Additionally, it includes examples and syntax for performing operations on these data types.

Uploaded by

shankarspshukla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

KALI CHARAN NIGAM INSTITUTE OF

TECHNOLOGY, BANDA

“PYTHON PROGRAMMING”
BCC-402

UNIT – III

Python Complex data types: Using string data type and string
operations, Defining list and list slicing, Use of Tuple data type. String,
List and Dictionary, Manipulations Building blocks of python
programs, string manipulation methods, List manipulation. Dictionary
manipulation, Programming using string, list and dictionary in-built
functions. Python Functions, organizing python codes using functions.

Compiled by
Abhishek Tiwari
(Assistant Professor)
Python String
A String is a data structure in Python Programming that represents a sequence of characters. It
is an immutable data type, meaning that once you have created a string, you cannot change it.
Python String are used widely in many different applications, such as storing and manipulating
text data, representing names, addresses, and other types of data that can be represented as text.

What is a String in Python?


Python Programming does not have a character data type, a single character is simply a string
with a length of 1.

Syntax:
string_variable = 'Hello, world!'

Create a String in Python


Strings in Python can be created using single quotes or double quotes or even triple
quotes. Let us see how we can define a string in Python or how to write string in Python.
Example:
In this example, we will demonstrate different ways to create a Python String. We will create
a string using single quotes (‘ ‘), double quotes (” “), and triple double quotes (“ ”” “” ”). The
triple quotes can be used to declare multiline strings in Python.

Accessing characters in Python String


In Python Programming tutorials, individual characters of a String can be accessed by using
the method of Indexing. Indexing allows negative address references to access characters
from the back of the String, e.g. -1 refers to the last character, -2 refers to the second last
character, and so on.
While accessing an index out of the range will cause an IndexError. Only Integers are
allowed to be passed as an index, float or other types that will cause a TypeError.

String Concatenation
String concatenation means add strings together.
Use the + character to add a variable to another variable:

Example
x = "Python is "
y = "awesome"
z= x+y
print(z)

String Replication
String replication means multiply strings with number of times.
Use the * character to repeat a variable with given number of time:
Example
x = "Python"
z = x *4
print(z)
String Slicing Python
In Python Programming tutorials, the String Slicing method is used to access a range of
characters in the String. Slicing in a String is done by using a Slicing operator, i.e., a colon
(:). One thing to keep in mind while using this method is that the string returned after slicing
includes the character at the start index but not the character at the last index.

# Creating a String
String1 = "KCNIT_BANDA_UP"
print("Initial String: ")
print(String1)

# Printing 3rd to 12th character


print("\nSlicing characters from 3-12: ")
print(String1[3:12])

# Printing characters between


# 3rd and 2nd last character
print("\nSlicing characters between " +
"3rd and 2nd last character: ")
print(String1[3:-2])

Python String Reversed


In Python Programming tutorials, By accessing characters from a string, we can also reverse
strings in Python Programming. We can Reverse a string by using String slicing method.

#Program to reverse a string


st = "KCNIT_BANDA"
print(st[::-1])

st = "KCNIT_BANDA"
st2= “ ”.join((reversed(st))
print(st2)

String Manipulation Function and Methods

Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of where
it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ASCII characters
isdigit() Returns True if all characters in the string are digits
islower() Returns True if all characters in the string are lower case
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Converts the elements of an iterable into a string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
upper() Converts a string into upper case

Examples:-

st = "KCNIT_BANDA"
print(lower(st))

st = "KCNIT_BANDA"
st2= st.capitalize()
print(st2)

st = "KCNIT_BANDA"
print(len(st))

st = "KCNIT_BANDA"
print(st.replace(“KCNIT”,”VNMPS”)

Python Lists

Python Lists are just like dynamically sized arrays, declared in other languages (vector in C++
and ArrayList in Java). In simple language, a Python list is a collection of things, enclosed in [
] and separated by commas.
The list is a sequence data type which is used to store the collection of
data. Tuples and String are other types of sequence data types.

Example
Var = ["KCNIT", "BANDA", "UP"]
print(Var)

Creating a List in Python


Lists in Python can be created by just placing the sequence inside the square brackets[].
# Python program to demonstrate
# Creation of List

# Creating a Blank List


List = []
print("Blank List: ")
print(List)
# Creating a List of numbers
List = [10, 20, 30]
print("\nList of numbers: ")
print(List)

# Creating a List of strings and accessing


# using index
List = ["KCNIT", "BANDA", "UP"]
print("\nList Items: ")
print(List[0])
print(List[2])

Accessing elements from the List


In order to access the list items, refer to the index number. Use the index operator [ ] to access
an item in a list. The index must be an integer. Nested lists are accessed using nested
indexing.
Example 1: Accessing elements from list

List = ["KCNIT", "BANDA", "UP"]


# accessing an element from the
# list using index number
print("Accessing an element from the list")
print(List[0])
print(List[2])

Example 2: Accessing elements from a multi-dimensional list

List = [['KCNIT', 'BANDA'], ['UP']]


# accessing an element from the
# Multi-Dimensional List using
# index number
print("Accessing a element from a Multi-Dimensional list")
print(List[0][1])
print(List[1][0])

Python List Slicing

In Python, list slicing is a common practice and it is the most used technique for programmers
to solve efficient problems. Consider a Python list, in order to access a range of elements in a
list, you need to slice a list. One way to do this is to use the simple slicing operator i.e. colon(:).
With this operator, one can specify where to start the slicing, where to end, and specify the
step. List slicing returns a new list from the existing list.

Syntax
Lst[ Start : Stop : Step ]
Example: -
# Initialize list
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Show original list
print("Original List:\n", List)
print("\nSliced Lists: ")
# Display sliced list
print(List[3:9:2])
# Display sliced list
print(List[::2])

# Display sliced list


print(List[::])

List Manipulation Function and Methods

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 first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
max() It will return the max value from the list
min() It will return the min value from the list
sum() It will return the summation of the list elements
list() It will convert the data into the form of list
del It is statement to delete the list permanently.

Examples:
1. Num1=[1,2,3]
Num1.append(4)
print(Num1)

2. Num1=[1,2,3,4,5,6]
Num2=Num1.copy()
print(Num2)

3. Num1=[1,2,3]
del Num1
print(Num1)

4. Num1=[3,4,5,1,2]
Num1.sort()
print(Num1)

5. Num1=[1,2,3,4,5]
Num1.reverse()
print(Num1)

Python Tuple

Python Tuple is a collection of objects separated by commas. In some ways, a tuple is similar
to a Python list in terms of indexing, nested objects, and repetition but the main difference
between both is Python tuple is immutable, unlike the Python list which is mutable.

 Tuples are used to store multiple items in a single variable.


 Tuple is one of 4 built-in data types in Python used to store collections of data, the
other 3 are List, Set, and Dictionary, all with different qualities and usage.
 A tuple is a collection which is ordered and unchangeable.
 Tuples are written with round brackets ( ).

Create a Tuple

We can create tuple by three methods-


 By Assigning method
 By Dynamic typing
 By another sequence

By Assigning Method:

thistuple = ("apple", "banana", "cherry")


print(thistuple)

By Dynamic typing:

thistuple = tuple(eval(input(“Enter any 5 element for tuple”)))


print(thistuple)

By Assigning Method:

thistuple = tuple( ["apple", "banana", "cherry"] )


print(thistuple)

Tuple Items
 Tuple items are ordered, unchangeable, and allow duplicate values.
 Tuple items are indexed, the first item has index [0], the second item has
index [1] etc.

Ordered
 When we say that tuples are ordered, it means that the items have a defined order, and
that order will not change.

Unchangeable
 Tuples are unchangeable, meaning that we cannot change, add or remove items after
the tuple has been created.

Allow Duplicates
 Since tuples are indexed, they can have items with the same value:

thistuple = ("apple", "banana", "cherry", "apple", "cherry")


print(thistuple)

Python Tuple Slicing

In python tuple slicing is similar to the list or string slicing. You can read above.

Tuple Function and Methods

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


index() Returns the index of the first element with the specified value from tuple
max() It will return the max value from the tuple
min() It will return the min value from the tuple
sum() It will return the summation of the tuple elements
tuple() it will convert the data into the form of tuple
del It is statement to delete the tuple permanently

Tuple Operations:
Concatenation
It is used to concatenate the multiple tuple into a one tuple.

Example:
T1=(1,2,3)
T2=(4,5,6)
print(T1+T2)
Replication
It is used to replicate or repeat the tuple into multiple times.

Example:
T1=(1,2,3)
print(T1*2)

how to find the summation of all elements of tuple?

Num=(11,12,13,14,15)
Sum=sum(Num)
print(“Summation is ”,sum)

how to count the elements in tuple?

Num=(11,12,11,14,15,11)
C=Num.count(11)
print(“Count = ”,C)

Dictionaries in Python
A Python dictionary is a data structure that stores the value in key:value pairs. This makes
it different from lists, tuples, and arrays as in a dictionary each key has an associated value.
This makes it different from lists, tuples, and arrays as in a dictionary each key has an
associated value.

Note: As of Python version 3.7, dictionaries are ordered and can not contain duplicate keys.

Example:
As you can see from the example, data is stored in key:value pairs in dictionaries, which
makes it easier to find values.

Dict = {1: 'Rahul', 2: 'Ramesh', 3: 'Kavita'}


print(Dict)

Python Dictionary Syntax


dict_var = {key1 : value1, key2 : value2, …..}
Dictionary Methods
Here is a list of in-built dictionary functions with their description. You can use these
functions to operate on a dictionary.

Method Description
dict.clear() Remove all the elements from the dictionary
dict.copy() Returns a copy of the dictionary
dict.get(key, default = “None”) Returns the value of specified key
Returns a list containing a tuple for each key value
dict.items()
pair
dict.keys() Returns a list containing dictionary’s keys

dict.update(dict2) Updates dictionary with specified key-value pairs

dict.values() Returns a list of all the values of dictionary


pop() Remove the element with specified key
popItem() Removes the last inserted key-value pair
set the key to the default value if the key is not
dict.setdefault(key,default= “None”)
specified in the dictionary
returns true if the dictionary contains the specified
dict.has_key(key)
key.

Accessing Items
1.
thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)

2.
for x in thisdict:
print(thisdict[x])

Change Dictionary Items

thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
print(thisdict)

Add Dictionary Items


thisdict= {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"]= "red"
print(thisdict)

Removing Items
Using pop
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)

Using popitem
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)

Using del
1.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
2.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict)
Using clear
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
Python Functions
 A function is a block of code which only runs when it is called.
 You can pass data, known as parameters, into a function.
 A function can return data as a result.

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:
Example:
def my_function():
print("Hello from a function")

my_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.
The following example has a function with one argument (fname). When the function is
called, we pass along a first name, which is used inside the function to print the full name:
def my_function(fname):
print(fname + " Refsnes")

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

Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are passed
into a function.
 From a function's perspective:
 A parameter is the variable listed inside the parentheses in the function definition.
 An argument is the value that is sent to the function when it is called.

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("KCNIT", "BANDA")

Types of parameters
In python there are three types of parameters-
 Positional or Required Parameter
 Named or Keyword Parameter
 Default parameter

How many types we can define the function in python?


We can define the user defined function in four ways-
 Return value with Parameter pass
 Return value without parameter pass
 No return value with Parameter pass
 No return value without Parameter pass
Return value with Parameter pass Example:-
# Function definition
def add(a, b):
return (a+b)
# Main Program
x=2
y=3
print(“Additin is : ”, add(x, y))

Return value without Parameter pass Example: -


# Function definition
def add( ):
x=2
y=3
return (x+y)
# Main Program
print(“Additin is : ”, add( ))

No Return value with Parameter pass Example: -


# Function definition
def add(a, b):
print (“Addition is: ”, a+b)
# Main Program
x=2
y=3
add(x, y)
No Return value without Parameter pass Example: -
# Function definition
def add( ):
x=2
y=3
print (“Addition is: ”, x+y)
# Main Program
add( )

You might also like