Python Programming (Unit-3)
Python Programming (Unit-3)
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.
Syntax:
string_variable = 'Hello, world!'
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)
st = "KCNIT_BANDA"
st2= “ ”.join((reversed(st))
print(st2)
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)
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])
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.
Create a Tuple
By Assigning Method:
By Dynamic typing:
By Assigning Method:
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:
In python tuple slicing is similar to the list or string slicing. You can read above.
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)
Num=(11,12,13,14,15)
Sum=sum(Num)
print(“Summation is ”,sum)
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.
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
Accessing Items
1.
thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
2.
for x in thisdict:
print(thisdict[x])
thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
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