Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data Science)
Functions in python:
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.
Python Function Declaration
The syntax to declare a function is:
Types of Functions in Python
There are mainly two types of functions in Python.
Built-in library function: These are Standard functions in Python that are
available to use.
User-defined function: We can create our own functions based on our
requirements.
1
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data Science)
Example1: Function with no parameters and no return value
def add():
n1=10
n2=20
sum=n1+n2
print(sum) #o/p 30
add() # call a function
Example2: Function with parameters and no return value
def add(n1,n2):
sum=n1+n2
print(sum) #o/p 30
add(10,20) # call a function
Example3: Function with parameters and return value
def add(n1,n2):
sum=n1+n2
return(sum)
s=add(10,20) # call a function
print(s) #o/p 30
String
2
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data Science)
In Python, string is an immutable sequence data type. It is the
sequence of Unicode characters wrapped inside single, double, or
triple quotes.
Example:
str1='This is a string in Python'
print(str1)
str2="This is a string in Python"
print(str2)
Multi-line Strings
str1='''This is the first
Multi-line string '''
print(str1)
str2="""This is the second
Multi-line string."""
print(str2)
Get String Length
greet='Hello'
n = len(greet) #returns 5
String as Array
greet='hello'
print(greet[0])
print(greet[1])
print(greet[2])
print(greet[3])
print(greet[4])
print(greet[5]) #IndexError: string index out of range
Negative Index
greet='hello'
print(greet[-5])
3
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data Science)
print(greet[-4])
print(greet[-3])
print(greet[-2])
print(greet[-1])
print(greet[0])
The string is an immutable object. Hence, it is not possible to
modify it. The attempt to assign different characters at a certain
index results in errors.
greet='hello'
greet[0]='A' #TypeError:'str' object does not support item
assignment
String Operators
Obviously, arithmetic operators don't operate on strings. However, there
are special operators for string processing.
Operato
r Description Example
+ Appends the second string to the first a='hello'
b='world'
a+b
#output: 'helloworld'
* Concatenates multiple copies of the same string a='hello'
a*3
#output: 'hellohellohello'
[] Returns the character at the given index a = 'Python'
a[2]
#output: t
[:] Fetches the characters in the range specified by two a = 'Python'
index operands separated by the : symbol a[0:2]
#output: 'Py'
in Returns true if a character exists in the given string a = 'Python'
4
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data Science)
Operato
r Description Example
'x' in a #output: False
'y' in a #output: True
'p' in a #output: False
not in Returns true if a character does not exist in the given a = 'Python'
string 'x' not in a #output: True
'y' not in a #output: False
Python String Methods
Method Description and Example
capitalize() Converts the first character to upper case
Example:
s="good morning"
print(s.capitalize())
output: GOOD MORNING
casefold() Converts string into lower case
Example:
s="GOOD morning"
print(s.casefold())
output: good morning
count() Returns the number of times a specified value occurs in a string
Example:
s="good morning"
print(s.count("o"))
output:3
endswith() Returns true if the string ends with the specified value
Example:
s="good morning"
print(s.endswith("ing"))
output: True
s="googd morning"
print(s.endswith("ig"))
5
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data Science)
output: False
find() Searches the string for a specified value and returns the position
of where it was found
Example:
s="Hi good morning"
print(s.find("good"))
output:3
s="Hi good morning good"
print(s.find("god"))
output:-1
index() Searches the string for a specified value and returns the position
of where it was found
Example:
s="Hi good morning good"
print(s.index("good"))
output:3
s="Hi good morning good"
print(s.index("god"))
output:error
isalnum() Returns True if all characters in the string are alphanumeric
Example:
s="company123"
print(s.isalnum())
output: True
isalpha() Returns True if all characters in the string are in the alphabet
Example:
s="company"
print(s.isalpha())
output: True
isdecimal() Returns True if all characters in the string are decimals
Example:
s="23456"
print(s.isdecimal())
output: True
isdigit() Returns True if all characters in the string are digits
Example:
6
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data Science)
s="123abcd"
print(s.isdigit())
output:False
s="123"
print(s.isdigit())
output: True
islower() Returns True if all characters in the string are lower case
Example:
s="good morning"
print(s.islower())
output: True
isnumeric() Returns True if all characters in the string are numeric
Example:
s="12345.89"
print(s.isnumeric())
output:False
isspace() Returns True if all characters in the string are whitespaces
Example:
output:
istitle() Returns True if the string follows the rules of a title
Example:
s="Good Morning"
print(s.istitle())
output:True
isupper() Returns True if all characters in the string are upper case
Example:
s="GOOD MORNING"
print(s.isupper())
output: True
join() Converts the elements of an iterable into a string
Example:
s=["Hi", "Good moring", "How are you"]
print("#".join(s))
output: Hi#Good moring#How are you
7
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data Science)
ljust() Returns a left justified version of the string
Example:
txt = "mango"
x = txt.ljust(20)
print(x, "is my favorite fruit.")
output:
mango is my favorite fruit.
lower() Converts a string into lower case
Example:
s="GOOD MORNING"
print(s.lower())
output: good morning
replace() Returns a string where a specified value is replaced with a
specified value
Example:
s="I like bananas"
print(s.replace("bananas","mangos"))
output: I like mangos
rfind() Searches the string for a specified value and returns the last
position of where it was found
Example:
s="Hi, good morning Have a good Day"
print(s.rfind("good"))
output: 24
rindex() Searches the string for a specified value and returns the last
position of where it was found
s="Hi, good morning Have a good Day"
print(s.rindex("good"))
output: 24
rjust() Returns a right justified version of the string
Example:
txt = "banana"
x = txt.rjust(20)
print(x, "is my favorite fruit.")
output:
banana is my favorite fruit.
8
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data Science)
split() Splits the string at the specified separator, and returns a list
Example:
s = "welcome to the python class"
print(s.split())
output: ['welcome', 'to', 'the', 'python', 'class']
startswith() Returns true if the string starts with the specified value
Example:
txt = "Hello, welcome to my world."
print(txt.startswith("Hello"))
output: True
strip() Returns a trimmed version of the string
Example:
s=" Hello, welcome to my world."
print(s.strip())
output: Hello, welcome to my world
swapcase() Swaps cases, lower case becomes upper case and vice versa
Example:
s = "Hello, Welcome to my WORLD."
print(s.swapcase())
output: hELLO, wELCOME TO MY world.
title() Converts the first character of each word to upper case
Example:
s = "Hello,Welcome to my world."
print(s.title())
output: Hello,Welcome To My World.
upper() Converts a string into upper case
Example: s = "Hello,Welcome to my world."
print(s.upper())
output: HELLO,WELCOME TO MY WORLD.
Dictionary
Dictionaries are used to store data values in key:value pairs.
9
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data Science)
A dictionary is a collection which is ordered*, changeable and do not allow
duplicates.
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
Dictionaries are written with curly brackets, and have keys and values:
Example:
Employee = {"Name": "Johnny", "Age": 32, "salary":26000,"Company":"TCS"}
print("printing Employee data .... ")
print(Employee)
Output
printing Employee data ....
{'Name': 'Johnny', 'Age': 32, 'salary': 26000, 'Company': TCS}
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Hcl', 2: 'WIPRO', 3:'Facebook'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)
Output
Empty Dictionary:
{}
Create Dictionary by using dict():
{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}
10
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data Science)
Accessing the dictionary values
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}
print("printing Employee data .... ")
print("Name : " Employee["Name"])
print("Age : " Employee["Age"])
print("Salary : " Employee["salary"])
print("Company : " Employee["Company"])
Output:
printing Employee data ....
Name : Dev
Age : 20
Salary : 45000
Company : WIPRO
Adding Dictionary Values
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements to dictionary one at a time
Dict[0] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(Dict)
11
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data Science)
# Adding set of values
# with a single Key
# The Emp_ages doesn't exist to dictionary
Dict['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[3] = 'JavaTpoint'
print("\nUpdated key value: ")
print(Dict)
Output
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}
Dictionary after adding 3 elements:
{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}
Updated key value:
{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}
Deleting Elements using del Keyword
Employee = {"Name": "David", "Age": 30, "salary":55000,"Company":"WIPRO"}
print("printing Employee data .... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
12
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data Science)
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
Output
printing Employee data ....
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'WIPRO'}
Deleting some of the employee data
printing the modified information
{'Age': 30, 'salary': 55000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined.
Methods of dictionary:
Method Description
clear() Removes all the elements from the dictionary
Example:
numbers = {1: "one", 2: "two"}
numbers.clear() # removes all the items from the dictionary
print(numbers)
Output: {}
copy() Returns a copy of the dictionary
Example:
original_marks = {'Physics':67, 'Maths':87}
copied_marks = original_marks.copy()
13
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data Science)
print(original_marks)
print(copied_marks)
Output: {'Physics': 67, 'Maths': 87}
{'Physics': 67, 'Maths': 87}
fromkeys() Returns a dictionary with the specified keys and value
Example:
# keys for the dictionary
alphabets = {'a', 'b', 'c'}
# value for the dictionary
number = 1
# creates a dictionary with keys and values
dictionary = dict.fromkeys(alphabets, number)
print(dictionary)
Output: {'a': 1, 'c': 1, 'b': 1}
get() Returns the value of the specified key
Example:
person = {'name': 'Phill', 'age': 22}
print('Name: ', person.get('name'))
print('Age: ', person.get('age'))
Output: Name: Phill
Age: 22
items() Returns a list containing a tuple for each key value pair
Example:
marks = {'Physics':67, 'Maths':87}
print(marks.items())
Output: dict_items([('Physics', 67), ('Maths', 87)])
keys() Returns a list containing the dictionary's keys
Example:
numbers = {1: 'one', 2: 'two', 3: 'three'}
# extracts the keys of the dictionary
Print(numbers.keys())
14
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data Science)
Output: dict_keys([1, 2, 3])
setdefault() Returns the value of the specified key. If the key does not exist:
insert the key, with the specified value
Example:
person = {'name': 'Phill'}
# key is not in the dictionary
salary = person.setdefault('salary')
print(person)
# key is not in the dictionary
# default_value is provided
age = person.setdefault('age', 22)
print(person)
Output: {'name': 'Phill', 'salary': None}
{'name': 'Phill', 'age': 22, 'salary': None}
update() Updates the dictionary with the specified key-value pairs
Example:
marks = {'Physics':67, 'Maths':87}
internal_marks = {'Practical':48}
marks.update(internal_marks)
print(marks)
Output: {'Physics': 67, 'Maths': 87, 'Practical': 48}
values() Returns a list of all the values in the dictionary
Example:
marks = {'Physics':67, 'Maths':87}
print(marks.values())
Output: dict_values([67, 87])
File in python:
File is a named location on disk to store related information. It is used to permanently store data in a
non-volatile memory (e.g. hard disk). When we want to read from or write to a file we need to open it
first. When we are done, it needs to be closed, so that resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order.
1. Open a file
15
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data Science)
2. Read or write (perform operation)
3. Close the file
open a file: Python has a built-in function open() to open a file.
Syntax: file_object=open(file_name,mode)
The open() function takes two parameters;
Filename
mode.
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does notexist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
Refer the file named “demofile.txt” for the following example
demofile.txt
Good morning
Hello
Read from a File:
Welcome to python class
Example 1:
PESITM Shivamogga
f = open("demofile.txt", "r")
print(f.read())
f.close()
output:
Good morning
16
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data Science)
Hello
Welcome to python class
PESITM Shivamogga
Example 2: Read the 4 first characters of the file:
f = open("demofile.txt", "r")
print(f.read(4))
f.close()
output:
Good
Example 3: Read the lines by using the readline() method:
f = open("demofile.txt", "r")
print(f.readline()) #Read one line of the file:
f.close()
output:
Good morning
Example 4: Read the 3 lines by using the readline() method:
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
print(f.readline())
f.close()
output:
17
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data Science)
Good morning
Hello
Welcome to python class
Write to an Existing File
To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
Example 1: Open the file "demofile2.txt" and append content to the file:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())
f.close()
output:
Good morning
Hello
Welcome to python class
Now the file has more content!
Example 2: Open the file "demofile3.txt" and overwrite the content:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
#open and read the file after the writting:
f = open("demofile3.txt", "r")
print(f.read())
f.close()
18
Prerana Educational and Social Trust®
PES Institute of Technology and Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering(Data Science)
output:
Woops! I have deleted the content!
Note: the "w" method will overwrite the entire file.
Create a New File
To create a new file in Python, use the open() method, with one of the following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Example 1: Create a file called "myfile.txt":
f = open("myfile.txt", "x")
Result: a new empty file is created!
Example 2: Create a new file if it does not exist:
f = open("myfile.txt", "w")
Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:
Example: Remove the file "demofile.txt":
import os
os.remove("demofile.txt")
19