0% found this document useful (0 votes)
17 views60 pages

Python String Basics and Formatting

The document provides a comprehensive overview of string handling in Python, including string creation, accessing characters, slicing, formatting, and modification. It also covers file handling, detailing how to open, read, write, and append to files using various modes and the 'with' statement for resource management. Examples and code snippets illustrate each concept clearly.

Uploaded by

eagleab8005
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)
17 views60 pages

Python String Basics and Formatting

The document provides a comprehensive overview of string handling in Python, including string creation, accessing characters, slicing, formatting, and modification. It also covers file handling, detailing how to open, read, write, and append to files using various modes and the 'with' statement for resource management. Examples and code snippets illustrate each concept clearly.

Uploaded by

eagleab8005
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

 Python String

• In Python, Strings are arrays of bytes representing Unicode


characters.
• However, Python does not have a character data type, a single
character is simply a string with a length of 1.
• Square brackets can be used to access elements of the string.

Creating a String
Strings in Python can be created using single quotes or double quotes or
even triple quotes.
CODE;-
# Python Program for
# Creation of String
#
# Creating a String
# with single Quotes
String1 = 'Welcome to the Latur'
print("String with the use of Single Quotes: ")
print(String1)

# Creating a String
# with double Quotes
String1 = "I'm a AB"
print("\nString with the use of Double Quotes: ")
print(String1)

# Creating a String
# with triple Quotes
String1 = '''I'm a AB and I live on "Earth"'''
print("\nString with the use of Triple Quotes: ")
print(String1)

# Creating String with triple


# Quotes allows multiple lines
String1 = '''
Hello
Cocsit
Latur'''
print("\nCreating a multiline String: ")
print(String1)

OUTPUT:-

String with the use of Single Quotes:

Welcome to the Latur

String with the use of Double Quotes:

I'm a AB

String with the use of Triple Quotes:

I'm a AB and I live on "Earth"

Creating a multiline String:

Hello

Cocsit

Latur

Accessing characters in Python

• In Python, 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.
CODE:-

# Python Program to Access


# characters of String

String1 = "HELLOCOCSITLATUR"
print("Initial String: ")
print(String1)

# Printing First character


print("\nFirst character of String is: ")
print(String1[0])

# Printing Last character


print("\nLast character of String is: ")
print(String1[-1])

OUTPUT:-
Initial String:
HELLOCOCSITLATUR

First character of String is:


H

Last character of String is:


R

String Slicing
To access a range of characters in the String, the method of slicing is
used. Slicing in a String is done by using a Slicing operator (colon).

CODE:-

# Python Program to
# demonstrate String slicing

# Creating a String
String1 = "HELLOCOCSITLATUR"
print("Initial String: ")
print(String1) #Printing start
index value print("Start Index:")
print(String1[5:]) #Printing End
index value print("End Index:")
print(String1[:9]) # 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])

OUTPUT:-

Initial String:

HELLOCOCSITLATUR

Start Index:

COCSITLATUR

End Index:

HELLOCOCS
Slicing characters from 3-12:

LOCOCSITL

Slicing characters between 3rd and 2nd last character:

LOCOCSITLAT

String Formatting in Python


String formatting is the process of infusing things in the string dynamically
and presenting the string. There are four different ways to perform string
formatting:-
• Formatting with % Operator.
• Formatting with format() string method.
• Formatting with string literals, called f-strings.
• Formatting with String Template Class

Formatting string using % Operator


It is the oldest method of string formatting. Here we use the modulo %
operator. The modulo % is also known as the “string-formatting operator”.

CODE:-

# Python program to demonstrate the use of formatting


using %

# Initialize variable as a string


variable = '15'
string = "Variable as string = %s" %(variable)
print (string )

# Printing as raw data


print ("Variable as raw data = %r"
%(variable))
# Convert the variable to integer
# And perform check other formatting options
variable = int(variable) # Without this the below
statement
# will give error.
string = "Variable as integer = %d" %(variable)
print (string)
print ("Variable as float = %f"
%(variable)) # printing as any
string or char after a mark print
("Variable as printing with special char
= %chello"
%(variable))

print ("Variable as hexadecimal = %x" %(variable))


print ("Variable as octal = %o" %(variable))
print("Hello %s"%('World!'))
print("Value of A: %d"%10)

OUTPUT:-
Variable as string = 15

Variable as raw data = '15'

Variable as integer = 15

Variable as float = 15.000000

Variable as printing with special char = ☼hello

Variable as hexadecimal = f

Variable as octal =

17 Hello World!

Value of A: 10

Float precision with the placeholder method:

• Floating-point numbers use the format %[Link].


• Here, a would be the minimum number of digits to be present in the
string; these might be padded with white space if the whole number
doesn’t have this many digits.
• Close to this, bf represents how many digits are to be displayed after
the decimal point.
Let us see a few examples:
Float point precision using % operator:-
CODE:-

print('The value of float point is: %5.4f'


%(30.58967)) print('The value of float point is:
%6.3f' %(30.58967))

OUTPUT:-

The value of float point is: 30.5897

The value of float point is: 30.590

You can use multiple format conversion types in a single print statement

CODE:-

variable = 20

string = "Variable as integer = %d \n\


Variable as float = %f" %(variable,
variable)

print (string)

OUTPUT:-
Variable as integer = 20
Variable as float = 20.000000

Formatting string using format() method:-


• Format() method was introduced with Python3 for handling
complex string formatting more efficiently.
• Formatters work by putting in one or more replacement fields and
placeholders defined by a pair of curly braces { } into a string and
calling the [Link]().
• The value we wish to put into the placeholders and concatenate with
the string passed as parameters into the format function.

Syntax: ‘String here {} then also {}’.format(‘something1′,’something2’)

Formatting string using format() method

The .format() method has many advantages over the placeholder method:
• We can insert object by using index-based position

• We can insert objects by using assigned keywords

• We can reuse the inserted objects to avoid duplication

CODE:-
print('We all are {}.'.format('equal'))
print('{2} {1} {0}'.format('directions',
'the', 'Read')) print('a: {a}, b: {b}, c:
{c}'.format(a = 1,
b = 'Two',
c = 12.3))
print('We {p} {p} {p}'.format(p = 'are'))

OUTPUT:-

We all are

equal. Read the

directions a: 1,

b: Two, c: 12.3

We are are are

Float precision with the .format() method:


Syntax: {[index]:[width][.precision][type]}
CODE:-

a = 30.58967
print("Float Point Number: {0:6.4f}".format(a))
print("Float Point Number: {0:5.3f}".format(a))
print("Float Point Number: {0:4.2f}".format(a))

OUTPUT:-

Float Point Number: 30.5897

Float Point Number: 30.590

Float Point Number: 30.59

Formatted String using F-strings

• To create an f-string, prefix the string with the letter “ f ”.


• The string itself can be formatted in much the same way that you
would with [Link]().
• F-strings provide a concise and convenient way to embed python
expressions inside string literals for formatting.
• This new formatting syntax is very powerful and easy.
• You can also insert arbitrary Python expressions and you can even
do arithmetic operations in it.
CODE:-

a = 'A'
print(f"We are all
{a}") b = 10 c =
20
print(f"Addition is: {b+c}")

d
=
3
0
print(f"This is the value of d: {d}")
e =
30.589
67
print(f"This is float point number: {e:{1}.{6}}")
print(f"This is float point number: {e:{2}.{5}}")
print(f"This is float point number: {e:{3}.{4}}")

OUTPUT:-
We are all A
Addition is: 30
This is the value of d: 30
This is float point number: 30.5897
This is float point number: 30.59
This is float point number: 30.59

 Modifying String:-
Python strings are immutable

Python recognize as strings everything that is delimited by quotation


marks (” ” or ‘ ‘).

CODE:-

a = "Your_Name_is_displayed_on_TV."
print(a)
print(len(a)) # length of string
# Modifying string
print([Link]()) # upper the letters
print([Link]()) # lower the letters
print([Link]()) # capital the first letter of
total string
print([Link]()) # capital the first letter of word
in total string
print([Link]()) # capital to small and small to
capital
print([Link]('o')) #count 'o' in string
print([Link]('_')) # count '_' in string
print([Link]('Name')) #find the position in string
print([Link]('T')) #find particular one value in
string print([Link]('on')) # find the letters on in
string print([Link]('is')) # split from 'is' word
print([Link]('dis')) #split from 'dis' word
print([Link]('Y')) # If string starts with 'Y'
then print true,otherwise returns false.
print([Link]('.'))# If string ends with '.' then
print true,otherwise returns false.
print('.'*30) # repeating of string
[Link]('Your','Our')
print(a) # replacing the word from existing word
print(" ".join(a)) #add a whitespace between every
char print("+".join(a)) #add + whitespace between
every char

# String
Cocatenation b =
'ABC'
c =
'DEF'
print(
b+c)
OUTPUT:-

Your_Name_is_displayed_on_TV.

29

YOUR_NAME_IS_DISPLAYED_ON_TV.

your_name_is_displayed_on_tv.

Your_name_is_displayed_on_tv.

Your_Name_Is_Displayed_On_Tv.

yOUR_nAME_IS_DISPLAYED_ON_tv.

5
5

26

23

['Your_Name_', '_d', 'played_on_TV.']

['Your_Name_is_', 'played_on_TV.']

True

True

..............................

Your_Name_is_displayed_on_TV.

Your_Name_is_displayed_on_TV.

Y+o+u+r+_+N+a+m+e+_+i+s+_+d+i+s+p+l+a+y+e+d+_+o+n+_+T+V+.

ABCDEF
 FILE HANDLING
• Python too supports file handling and allows users to handle files
i.e., to read and write files, along with many other file handling
options, to operate on files.

• The concept of file handling has stretched over various other


languages, but the implementation is either complicated or lengthy,
but like other concepts of Python, this concept here is also easy and
short.

• Python treats file differently as text or binary and this is important.


Each line of code includes a sequence of characters and they form
text file. Each line of a file is terminated with a special character,
called the EOL or End of Line characters like comma {,} or
newline character.

• It ends the current line and tells the interpreter a new one has begun.
Let’s start with Reading and Writing files.

Working of open() function


Before performing any operation on the file like read or write, first we
have to open that file. For this, we should use Python’s inbuilt function
open() Syntax: variable = open(‘filename’, ‘mode’)
Where the following mode is supported:
1. r: open an existing file for a read operation.
2. w: open an existing file for a write operation. If the file already
contains some data then it will be overridden.
3. a: open an existing file for append operation. It won’t override
existing data.
4. r+: To read and write data into the file. The previous data in the file
will not be deleted.
5. w+: To write and read data. It will override existing data.
6. a+: To append and read data from the file. It won’t override existing
data.

CODE:-
a =
open('[Link]','r
') for i in a:
print(i)

OUTPUT:-
Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

The open command will open the file in the read mode and the for loop
will print each line present in the file.
Working of read() mode
There is more than one way to read a file in Python. If you need to extract
a string that contains all characters in the file then we can use [Link]().
The full code would work like this:

CODE:-
a =
open('[Link]','r')
print([Link]())

OUTPUT:-

Hello_World!
Hello_World!
Hello_World!
Hello_World!
Hello_World!
Hello_World!
Hello_World!
Hello_World!
Hello_World!
Hello_World!

Another way to read a file is to call a certain number of characters like in


the following code the interpreter will read the first five characters of
stored data and return it as a string:
CODE:-

a =
open('[Link]','r')
print([Link](1))
print([Link](2))
print([Link](3))
print([Link](4))

OUT
PUT
:-

el
lo_

Worl

Creating a file using write() mode


• Let’s see how to create a file and how write mode works:
To manipulate the file, write the following in your Python
environment:
• The close() command terminates all the resources in use and frees
the system of this particular program.

CODE;-

a = open('[Link]','w')
[Link]("This is write function")
[Link]('''This will
override data which is
stored in our file''')
[Link]()

OUTPUT:-

Working of append() mode


Let’s see how the append mode works:

CODE:-
a = open('[Link]','a')
[Link]("\nThis is APPEND MODE")
[Link]('''This will NOT
override data which is
stored in our file''')
[Link]()

OUTPUT:-

Using read along with the with() function


We can also use the read function along with the with() function:
CODE:-
with open('[Link]','r')
as a: for i in a:
print(i)

OUTPUT:-
Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

CODE:- with
open('[Link]','r') as
a:
print([Link]())

OUTPUT:-
Hello_World!
Hello_World!
Hello_World!
Hello_World!
Hello_World!
Hello_World!
Hello_World!
Hello_World!
Hello_World!
Hello_World!

Using write along with the with() function


We can also use the write function along with the with() function:
CODE:- with
open('[Link]','w') as
a:
[Link]("This is a write function")
[Link]('''
This will
override
existing data
''')

OUTPUT:-

split() using file handling


We can also split lines using file handling in Python. This splits the
variable when space is encountered. You can also split using any
characters as we wish. Here is the code: CODE:- with
open("[Link]", "r") as file: data =
[Link]() for line in data:
word = [Link]('_')
print (word)

OUTPUT:-
['Hello', 'World!']
Modifying file pointer position
In real-world applications, sometimes we need to change the file pointer
location externally since we may need to read or write the content at
various locations.

For this purpose, the Python provides us the seek() method which enables
us to modify the file pointer position externally.

The syntax to use the seek() method is given below.

Syntax: <file-ptr>.seek(offset[, from)

The seek() method accepts two parameters:

offset: It refers to the new position of the file pointer within the file.

from: It indicates the reference position from where the bytes are to be
moved. If it is set to 0, the beginning of the file is used as the reference
position. If it is set to 1, the current position of the file pointer is used as
the reference position. If it is set to 2, the end of the file pointer is used as
the reference position.

Consider the following example:-

CODE:-

# open the file [Link] in read mode


fileptr = open("[Link]","r")

#initially the filepointer is at 0


print("The filepointer is at byte
:",[Link]())

#changing the file pointer location to 10.


[Link](10);

#tell() returns the location of the fileptr.


print("After reading, the filepointer is
at:",[Link]())
OUTPUT:-

The filepointer is at byte : HELLO_WORLD!

After reading, the filepointer is at: D!

CODE;-

with open('[Link]','a+') as a:
[Link](0)
print([Link]())
[Link]("\nThis is append+ mode")
[Link]()

OUTPUT:-

HELLO_WORLD!

HELLO_WORLD!

HELLO_WORLD!

HELLO_WORLD!

HELLO_WORLD!
Python OS module
Renaming the file

The Python os module enables interaction with the operating system. The
os module provides the functions that are involved in file processing
operations like renaming, deleting, etc. It provides us the rename() method
to rename the specified file to a new name. The syntax to use the rename()
method is given below.

Syntax: rename(current-name, new-name)

The first argument is the current file name and the second argument is the
modified name. We can change the file name bypassing these two
arguments.

CODE:-

import
os
[Link]('[Link]','[Link]')
OUTPUT:-

Removing the file


The os module provides the remove() method which is used to remove the
specified file. The syntax to use the remove() method is given below.

Syntax: remove(file-name)

CODE:-
import
os
[Link]('[Link]')

OUTPUT:-
Creating the new directory:-
The mkdir() method is used to create the directories in the current working
directory. The syntax to create the new directory is given below.

Syntax: mkdir(directory name)

CODE:-

import
os
[Link]('New Folder')

OUTPUT:-
The getcwd() method:-
This method returns the current working directory.

The syntax to use the getcwd() method is given below:

CODE:-

import os
print([Link]())

OUTPUT:-

F:\COCSIT\[Link](CS)- TY(Python)\File_Handling

Changing the current working directory:-

The chdir() method is used to change the current working directory to a


specified directory.

The syntax to use the chdir() method is given below.

Syntax chdir("new-directory")
CODE:-

import
os
[Link]("F:\\COCSIT\\[Link](CS)-
TY(Python)\\File_Handling\\New Folder")
print([Link]())

OUTPUT:-

F:\COCSIT\[Link](CS)- TY(Python)\File_Handling\New Folder

Deleting directory
The rmdir() method is used to delete the specified directory.

The syntax to use the rmdir() method is given below.

Syntax [Link](directory name)

CODE:-

OUTPUT:-
After writing [Link]() line in our code:-

 Reading data from CSV/EXCEL file in python


First of all, what is a CSV ?
1. CSV (Comma Separated Values) is a simple file format used to
store tabular data, such as a spreadsheet or database. A CSV file
stores tabular data (numbers and text) in plain text.

2. Each line of the file is a data record. Each record consists of one or
more fields, separated by commas.

3. The use of the comma as a field separator is the source of the name
for this file format.

4. For working CSV files in python, there is an inbuilt module called


csv.

CODE:-

import csv a =
open('[Link]
') for i in a:
print(i)

[Link] file:-

OUTPUT:-
USING with as

FUNCTION:- CODE:-
import csv
with open('[Link]')
as a: for i in a:
print(i)
OUTPUT:-
Sno.,Name,Roll_No.

1,A,10

2,B,20

3,C,30

4,D,40

Reading CSV files:-


Python provides various functions to read csv file. We are describing few
method of reading function.

o Using [Link]() function

In Python, the [Link]() module is used to read the csv file. It takes each
row of the file and makes a list of all the columns.

CODE:-

import csv
filename =
'[Link]' a =
open(filename,'r
') b =
[Link](a)
for i in b:
print(i)
OUTPUT:-

['Roll No', 'Name']


['1', 'A']
['2', 'B']
['3', 'C']
['4', 'D']

CODE:-

# importing csv module


import csv

# csv file name


filename =
"[Link]"

# initializing the titles and


rows list fields = [] rows = []

# reading csv file with


open(filename, 'r') as
csvfile: # creating a csv
reader object csvreader =
[Link](csvfile)

# extracting field names through first row


fields = next(csvreader)

# extracting each data row one


by one for row in csvreader:
[Link](row)

# get total number of rows


print("Total no. of rows:
%d"%(csvreader.line_num))
# printing the field names
print('Field names are:' + ', '.join(field for
field in fields))

# printing first 5 rows


print('\nFirst 5 rows
are:\n') for row in
rows[:5]:
# parsing each column of
a row for col in row:
print("%s"%col)
OUTPUT:-
Total no. of rows: 6

Field names are:Roll No, Name

First 5 rows are:

Let us try to understand this piece of


code. with open(filename, 'r') as
csvfile:
csvreader = [Link](csvfile)
Here, we first open the CSV file in READ mode. The file object is
named as csvfile.
The file object is converted to [Link] object. We save the [Link]
object as csvreader.
fields = [Link]()
csvreader is an iterable object. Hence, .next() method returns the
current row and advances the iterator to the next row.

Since the first row of our csv file contains the headers (or field names),
we save them in a list called fields.
for row in csvreader:
[Link](row)
Now, we iterate through remaining rows using a for loop. Each row is
appended to a list called rows.

If you try to print each row, one can find that row is nothing but a
list containing all the field values. print("Total no. of rows:
%d"%(csvreader.line_num)) csvreader.line_num is nothing but a
counter which returns the number of rows which have been
iterated.

Writing to CSV file


CODE:-

# importing the csv module


import csv

# field names
fields = ['Name', 'Branch', 'Year', 'CGPA']

# data rows of csv file rows


= [ ['A', 'COE', '2',
'9.0'], ['B', 'COE',
'2', '9.1'],
['C', 'IT', '2', '9.3'],
['D', 'SE', '1', '9.5'],
['E', 'MCE', '3', '7.8'],
['F', 'EP', '2', '9.1']]

# name of csv file


filename = "[Link]"

# writing to csv file with


open(filename, 'w') as
csvfile: # creating a csv
writer object csvwriter =
[Link](csvfile)

# writing the fields


[Link](fields)

# writing the data rows


[Link](rows)

OUTPUT:-

Let us try to understand the above code in pieces.


fields and rows have been already defined. fields is a list containing all
the field names. rows is a list of lists.
Each row is a list containing the field values of
that row. with open(filename, 'w') as
csvfile: csvwriter =
[Link](csvfile)
Here, we first open the CSV file in WRITE mode. The file object is
named as csvfile.
The file object is converted to [Link] object. We save the
[Link] object as csvwriter. [Link](fields)
Now we use writerow method to write the first row which is
nothing but the field names. [Link](rows)
We use writerows method to write multiple rows at once.

 Pickling and Unpickling of Data


Python pickle module is used for serializing and de-serializing python
object structures. The process to converts any kind of python objects (list,
dict, etc.) into byte streams (0s and 1s) is called pickling or serialization
or flattening or marshalling. We can converts the byte stream (generated
through pickling) back into python objects by a process called as
unpickling.
Why Pickle?: In real world sceanario, the use pickling and unpickling are
widespread as they allow us to easily transfer data from one server/system
to another and then store it in a file or database.
Precaution: It is advisable not to unpickle data received from an untrusted
source as they may pose security threat. However, the pickle module has
no way of knowing or raise alarm while pickling malicious data.
Only after importing pickle module we can do pickling and unpickling.
Importing pickle can be done using the following command −
import pickle
CODE:-
import
pickle
mylist = ['a', 'b', 'c', 'd']
with open('[Link]', 'wb')
as a: [Link](mylist,
a)

OUTPUT:-
In the above code, list – “mylist” contains four elements (‘a’, ‘b’, ‘c’, ‘d’).
We open the file in “wb” mode instead of “w” as all the operations are done
using bytes in the current working directory.

A new file named “[Link]” is created, which converts the mylist


data in the byte stream.

Unpickling of Data:-

CODE:-
import
pickle
pickle_off = open ("[Link]",
"rb") emp = [Link](pickle_off)
print(emp)

Output: On running above scripts, you can see your mylist data again as
output.
['a', 'b', 'c', 'd']
Pickling is a way to convert a python object (list, dict, etc.) into a character
stream. The idea is that this character stream contains all the information
necessary to reconstruct the object in another python script
Pickle a simple dictionary :-

CODE:-
import
pickle
EmpID =
{1:"Zack",2:"53050",3:"IT",4:"38",5:"Flipkart"
} pickling_on = open("[Link]","wb")
[Link](EmpID, pickling_on)
pickling_on.close()
OUTPUT:-

Unpickle a dictionary :-

CODE:-
import
pickle
pickle_off = open("[Link]", 'rb')
EmpID = [Link](pickle_off)
print(EmpID)

OUTPUT:-

On running above script(unpickle) we get our dictionary back as we


initialized earlier. Also, please note because we are reading bytes here, we
have used “rb” instead of “r”.

{1: 'Zack', 2: '53050', 3: 'IT', 4: '38', 5: 'Flipkart'}

Pickle Exceptions
Below are some of the common exceptions raised while dealing with pickle
module −
• [Link]: If the pickle object doesn’t support pickling,
this exception is raised.
• [Link]: In case the file contains bad or corrupted
data.
• EOFError: In case the end of file is detected, this exception is raised.
Prons:
• Comes handy to save complicated data.
• Easy to use, lighter and doesn’t require several lines of code.
• The pickled file generated is not easily readable and thus provide
some security.
Cons:
• Languages other than python may not able to reconstruct pickled
python objects.
• Risk of unpickling data from malicious sources.

CODE:-
# Pickling without a file
import pickle
# initializing data to be stored in db
Omkar = {'key' : 'Omkar', 'name' : 'Omkar Pathak',
'age' : 21, 'pay' : 40000}
Jagdish = {'key' : 'Jagdish', 'name' : 'Jagdish
Pathak',
'age' : 50, 'pay' : 50000}
#
data
base
db =
{}
db['
Omka
r']
=
Omka
r
db['
Jagd
ish'
] =
Jagd
ish

# For storing
b = [Link](db) # type(b) gives <class
'bytes'>

# For loading
myEntry =
[Link](b)
print(myEntry)

Advantages of using Pickle Module:

1. Recursive objects (objects containing references to themselves):


Pickle keeps track of the objects it has already serialized, so later
references to the same object won’t be serialized again. (The marshal
module breaks for this.)\
2. Object sharing (references to the same object in different places):
This is similar to self- referencing objects; pickle stores the object
once, and ensures that all other references point to the master copy.
Shared objects remain shared, which can be very important for
mutable objects.

3. User-defined classes and their instances: Marshal does not support


these at all, but pickle can save and restore class instances
transparently. The class definition must be importable and live in the
same module as when the object was stored.

 Python Functions
Python Functions is a block of related statements designed to perform a
computational, logical, or evaluative task. The idea is to put some
commonly or repeatedly done tasks together and make a function so that
instead of writing the same code again and again for different inputs, we
can do the function calls to reuse code contained in it over and over again.
Functions can be both built-in or user-defined. It helps the program to be
concise, non-repetitive, and organized.
Syntax: def function_name(parameters):
"""docstri
ng"""
statement(s
) return
expression

Creating a Function

We can create a Python function using the def keyword.

Example: Python Creating Function

CODE;-
# A simple Python function
def fun():
print("Welcome to
COCSIT")
Calling a Function
After creating a function we can call it by using the name of the function
followed by parenthesis containing parameters of that particular function.

Example: Python Calling Function

CODE:-
# A simple Python function
def fun():
print("Welcome to
COCSIT")

# Driver code to call a function


fun()

OUTPUT:-
Welcome to COCSIT

Arguments of a Function
Arguments are the values passed inside the parenthesis of the function. A
function can have any number of arguments separated by a comma.
Example: Python Function with arguments

In this example, we will create a simple function to check whether the


number passed as an argument to the function is even or odd.

CODE:-
# A simple Python function to check
# whether x is even or odd

def evenOdd(x):
if (x % 2 ==
0):
print("even")
else:
print("odd")
# Driver code to call the
function evenOdd(2)
evenOdd(3)

OU
TPU
T:-
even
odd

Types of Arguments:-

Python supports various types of arguments that can be passed at the time
of the function call. Let’s discuss each type in detail.
Default arguments
A default argument is a parameter that assumes a default value if a value is
not provided in the function call for that argument. The following example
illustrates Default arguments.

CODE:-
# Python program to demonstrate
# default arguments

def myFun(x,
y=50):
print("x: ",
x)
print("y: ",
y)

# Driver code (We call myFun() with only


# argument)
myFun(10)

OUTPUT:-
x

Keyword arguments
The idea is to allow the caller to specify the argument name with values so
that caller does not need to remember the order of parameters.
CODE:-
# Python program to demonstrate Keyword
Arguments def student(firstname, lastname):
print(firstname, lastname)

# Keyword arguments
student(firstname='A', lastname='B')
student(lastname='B', firstname='A')

OUTPUT:-
A B
A B

Variable-length arguments

In Python, we can pass a variable number of arguments to a function using


special symbols. There are two special symbols:

• *args (Non-Keyword Arguments)


• **kwargs (Keyword Arguments)
Example 1: Variable length non-keywords argument
CODE:-

# Python program to illustrate


# *args for variable number of arguments

def
myFun(*argv):
for arg in
argv:
print(arg)

myFun('Hello', 'Welcome', 'to', 'COCSIT')

OUTPUT:-

Hello

Welcome

to

COCSIT

Example 2: Variable length keyword arguments


CODE:-

# Python program to illustrate


# *kwargs for variable number of keyword arguments

def myFun(**kwargs): for key,


value in [Link]():
print("%s == %s" % (key, value))

# Driver code
myFun(first='Hello', mid='Welcome', last='To
Cocsit')

OUTPUT:-

first == Hello
mid ==

Welcome last

== To Cocsit

Docstring

The first string after the function is called the Document string or
Docstring in short. This is used to describe the functionality of the
function.

The use of docstring in functions is optional but it is considered a good


practice.
The below syntax can be used to print out the docstring of a function:
Syntax: print(function_name.__doc__)

Example: Adding Docstring to the function

CODE:-
# A simple Python function to check
# whether x is even or odd

def evenOdd(x):
"""Function to check if the number is even or
odd"""
if (x
% 2 == 0):
print("even")
else:

print("odd")

# Driver code to call the function


print(evenOdd.__doc__)

OUTPUT:-

Function to check if the number is even or odd


The return statement
The function return statement is used to exit from a function and go back
to the function caller and return the specified value or data item to the
caller.
Syntax: return [expression_list]

The return statement can consist of a variable, an expression, or a constant


which is returned to the end of the function execution. If none of the above
is present with the return statement a None object is returned.

Example: Python Function Return Statement

CODE:-

def
square_value(num):
"""This function returns the
square value of the entered
number""" return num**2

print(square_valu
e(2))
print(square_valu
e(-4))

OUTPUT:-

Is Python Function Pass by Reference or pass by value?

One important thing to note is, in Python every variable name is a


reference.
When we pass a variable to a function, a new reference to the object is
created. Parameter passing in Python is the same as reference passing in
Java.
CODE:-

# Here x is a new reference to same


list lst def myFun(x): x[0] = 20

# Driver Code (Note that lst is modified


# after function call.
lst = [10, 11, 12, 13,
14, 15] myFun(lst)
print(lst)
OUTPUT:-
[20, 11, 12, 13, 14, 15]

When we pass a reference and change the received reference to


something else, the connection between the passed and received
parameter is broken. For example, consider the below program.
CODE;-
def
myFun(x
):

# After below line link of x with previous


# object gets broken. A new object is assigned
# to x.
x = [20, 30,
40]

# Driver Code (Note that lst is not modified


# after function call.
lst = [10, 11, 12, 13,
14, 15] myFun(lst)
print(lst)
OUTPUT:-
[10, 11, 12, 13, 14, 15]

Another example to demonstrate that the reference link is broken if we


assign a new value (inside the function).
CODE:-

def myFun(x):

# After below line link of x with previous


# object gets broken. A new object is
assigned # to x.
x
= 20

# Driver Code (Note that lst is not modified


# after function
call. x = 10
myFun(x)
print(x)

OUTPUT:-
10

Python Function within Functions

A function that is defined inside another function is known as the inner


function or nested function.
Nested functions are able to access variables of the enclosing scope. Inner
functions are used so that they can be protected from everything happening
outside the function.
CODE:-
# Python program to
# demonstrate accessing of
# variables of nested functions
def f1(): s =
'Hello World!!!!'

def f2():
print(s)
f2()
# Driver's
code f1()

OUTPUT:-
Hello World!!!!

 Using Python Libraries


WHAT IS A LIBRARY?

As mentioned above that a library is a collection of modules (and


packages) that together cas a specific type of applications or
requirements. A library can have multiple modules.

This will become clearer to you when we talk about what modules are
in coming lines Some commonly used Python libraries are as listed
below

Python standard library :-

This library is distributed with Python that contains module for various
types of functionalities. Some commonly used modules of Python
standard library are:-

math module:- which provides mathematical functions to support


different types calculations

cmath module:- which provides mathematical functions for complex


numbers.

random module:- which provides functions for generating pseudo-


ranidos numbers

statistics module:- which provides mathematical statistics functions

Urllib module:- which provides URL handling functions so that you


can access websites from within your program

NumPy library:- This library provides some advance math functionalities


along with tools to create and manipulate numeric arrays.
SciPy library:- This is another useful library that offers algorithmic and
mathematical tools for scientific calculations.

tkinter library:- This library provides traditional Python user interface


toolkit and helps you to create userfriendly GUI interface for different
types of applications.

Matplotlib library:- This library offers many functions and tools to


produce quality output in variety of formats such as plots, charts, graphs
etc.
A library can have multiple modules in it. Let us know what a module
means

What is a Module ?

The act of partitioning a program into individual components (known as


modules) is called modularity. A module is a separate unit in itself.

The justification for partitioning a

program is it reduces its complexity to

some degree and

it creates a number of well defined documented boundaries within the


program.
Another useful feature of having modules, is that its contents can be reused
in other programs, without having to rewrite or recreate them.

Structure of a Python Module:-

A Python module can contain much more than just functions.

A Python module is a normal Python file (.py file) containing one or


more of the following objects related to a particular task.

docstrings :- triple quoted comments; useful for documentation purposes.


For documentation, the docstrings should be the first string stored inside a
module/function - body/class
variables and constants:- labels for data

classes :- templates/blueprint to create objects of a certain kind.

Objects:- instances of classes. In general, objects are representation of


some abstract entity

statements:- instructions

functions:- named group of instructions

 Python Classes and Objects

• A class is a user-defined blueprint or prototype from which objects


are created. Classes provide a means of bundling data and
functionality together.
• Creating a new class creates a new type of object, allowing new
instances of that type to be made. Each class instance can have
attributes attached to it for maintaining its state. Class instances can
also have methods (defined by their class) for modifying their state.
• To understand the need for creating a class let’s consider an
example, let’s say you wanted to track the number of students that
may have different attributes like name, age.
• If a list is used, the first element could be the student’s name while
the second element could represent its age.
• Let’s suppose there are 100 different students, then how would you
know which element is supposed to be which? What if you wanted
to add other properties to these students? This lacks organization
and it’s the exact need for classes.
• Class creates a user-defined data structure, which holds its own data
members and member functions, which can be accessed and used by
creating an instance of that class. A class is like a blueprint for an
object.
Some points on Python class:
• Classes are created by keyword class.
• Attributes are the variables that belong to a class.
• Attributes are always public and can be accessed using the dot (.)
operator. Eg.: [Link]
Class Definition
Syntax: class
ClassName:
# Statement-1
.
.
.
# Statement-N

CODE:-
# Python3 program to
# demonstrate defining
# a class
class
Student:
pass

In the above example, the class keyword indicates that you are creating a
class followed by the name of the class (Student in this case).

Class Objects
An Object is an instance of a Class. A class is like a blueprint while an
instance is a copy of the class with actual values.
It’s not an idea anymore, it’s an actual student, like a student of name A
who’s seventeen years old. You can have many students to create many
different instances, but without the class as a guide, you would be lost, not
knowing what information is required.

An object consists of :
• State: It is represented by the attributes of an object. It also reflects the
properties of an object.
• Behavior: It is represented by the methods of an object. It also reflects
the response of an object to other objects.
• Identity: It gives a unique name to an object and enables one object to
interact with other objects.

Declaring Objects (Also called instantiating a class)


When an object of a class is created, the class is said to be instantiated. All
the instances share the attributes and the behavior of the class.
But the values of those attributes, i.e. the state are unique for each object. A
single class may have any number of instances.

CODE:-
# Python3 program to
# demonstrate instantiating
# a
clas
s

class Student:

# A simple class
# attribute
attr1 = "A"
attr2 = "B"

# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)

# Driver code #
Object
instantiation
obj1 = Student()

# Accessing class
attributes # and method
through objects
print("Calling attribute using object 1:
",obj1.attr1) [Link]()

OUTPUT:-
Calling attribute using object 1: A
I'm a A
I'm a B

The self
• Class methods must have an extra first parameter in the method
definition. We do not give a value for this parameter when we call the
method, Python provides it.
• If we have a method that takes no arguments, then we still have to have
one argument.
• This is similar to this pointer in C++ and this reference in Java.
When we call a method of this object as [Link](arg1, arg2),
this is automatically converted by Python into
[Link](myobject, arg1, arg2) – this is all the special self is
about.

__init__ method

The __init__ method is similar to constructors in C++ and Java.


Constructors are used to initializing the object’s state. Like methods, a
constructor also contains a collection of statements(i.e. instructions) that
are executed at the time of Object creation. It runs as soon as an object of
a class is instantiated.
The method is useful to do any initialization you want to do with your
object.

CODE:-

# A Sample class with init method


class Person:

# init method or
constructor def
__init__(self, name):
[Link] = name

# Sample Method def


myfun(self): print('Hello, my
name is', [Link])
p =
Person('AB
')
[Link]()

Class and Instance Variables


Instance variables are for data, unique to each instance and class variables
are for attributes and methods shared by all instances of the class. Instance
variables are variables whose value is assigned inside a constructor or
method with self whereas class variables are variables whose value is
assigned in the class.
Defining instance variable using a constructor.

CODE:-
# Python3 program to show that the variables with a
value # assigned in the class declaration, are class
variables and
# variables inside methods and constructors are
instance
# variables.

# Class for Student


class Student:

# Class Variable
person = 'student'

# The init method or constructor


def __init__(self, name, age):

# Instance Variable
[Link] = name
[Link] = age

# Objects of Dog
class obj1 =
Student("A", 20) obj2
= Student("B", 30)

print('Obj1 details:')
print('Obj1 is a',
[Link]) print('Name: ',
[Link]) print('Age: ',
[Link])
print('\nObj2 details:')
print('Obj2 is a',
[Link]) print('Name:
', [Link]) print('Age:
', [Link])

# Class variables can be accessed using class


# name also
print("\nAccessing class variable using class
name") print([Link])

OUTPUT:-

Obj1 details:
Obj1 is a student
Name: A
Age: 20

Obj2 details:
Obj2 is a student
Name: B
Age: 30

Accessing class variable using class name


student

 Constants of Maths in Python

Math module is a standard in-built module in Python that can be used for
performing the mathematical tasks. The math module has a set of
methods and constants.
Note: For more information, refer to Math-library-functions

1. Python math.e constant: The math.e constant returns the Euler’s


number: 2.71828182846.

Syntax: math.e
Returns: Return a float value, 2.71828182846, representing the mathematical
c onstant e
Exa
mpl
e:

# Import math

Library import math

# Print the value of Euler e

print (math.e)

Out
put:
2.718281828459045
2. Python [Link] constant: The [Link] constant returns the value pi:
3.14159265359. It is defined as the ratio of the circumference to the
diameter of a circle.

Syntax: [Link]
Returns: A float value, 3.14159265359, representing the mathematical
constan t PI
Exa
mpl
e:

# Import math

Library import math

# Print the value of


pi

print ([Link])
Out
put:
3.141592653589793

3. Python [Link] constant: The [Link] constant returns the value


tau:
6.283185307179586. It is defined as the ratio of the circumference to the
radius of a circle.

Syntax: [Link]
Returns: A float value, 6.283185307179586, representing the mathematical
con stant tau
Exa
mpl
e:

# Import math

Library import math

# Print the value of


tau

print ([Link])

Out
put:
6.283185307179586
4. Python [Link] constant: The [Link] constant returns of positive
infinity. For negative infinity, use -[Link] inf constant is equivalent to
float(“inf”).

Syntax: [Link]
Returns: A float value, returns the value of positive infinity.
Example:

# Import math

Library import math

# Print the positive infinity

print ([Link])

# Print the negative infinity

print (-[Link])

Out
put:
inf
-inf
5. Python [Link] constant: The [Link] constant returns a floating-
point nan (Not a Number) value. This value is not a legal [Link] nan
constant is equivalent to float(“nan”).

Syntax: [Link]
Returns: A float value, nan (Not a Number)
Example:

# Import math

Library import math

# Print the value of


nan

print ([Link])

Out
put:
nan

You might also like