MC4103 - PYTHON PROGRAMMING NOTES FOR ALL UNITS
MC4103 - PYTHON PROGRAMMING NOTES FOR ALL UNITS
5. Outline the logic to swap the content of two identifiers without using the third
variable.
x=5
y=7
print ("Before swapping: ")
print("Value of x : ", x, " and y : ", y
x, y = y, x
print ("After swapping: ")
print("Value of x : ", x, " and y : ", y)
6. What are the rules for naming the variable?
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-
z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different
variables)
A variable name cannot be any of the Python keywords.
PART B AND C
1. Explain the looping statement in python with example?
Python For loop
For loops are used for sequential traversal. For example: traversing a list or string or
array etc. In Python, there is “for in” loop which is similar to for each loop in other
languages. Let us learn how to use for in loop for sequential traversals.
Syntax:
for iterator_var in sequence:
statements(s)
Eg:
n=4
for i in range(0, n):
print(i)
WHILE LOOP
a while loop is used to execute a block of statements repeatedly until a given
condition is satisfied. And when the condition becomes false, the line immediately
after the loop in the program is executed.
Syntax:
while expression:
statement(s)
All the statements indented by the same number of character spaces after a programming
construct are considered to be part of a single block of code. Python uses indentation as
its method of grouping statements.
Eg:
# Python program to illustrate while loop
count = 0
while (count < 3):
count = count + 1
print("Hello")
BREAK STATEMENT
Break statement in Python is used to bring the control out of the loop when some
external condition is triggered. break statement is put inside the loop body (generally after
if condition). It terminates the current loop, i.e., the loop in which it appears, and resumes
execution at the next statement immediately after the end of that loop. If the break
statement is inside a nested loop, the break will terminate the innermost loop.
Syntax
while True:
...
if x == 10:
continue
print(x)
Eg:
for var in "sree":
if var == "e":
continue
print(var)
2. Summarize the precedence of mathematical operator in python?
An expression in python consists of variables, operators, values, etc. When the Python
interpreter encounters any expression containing several operations, all operators get
evaluated according to an ordered hierarchy, called operator precedence.
Precedence Operators Description Associativity
1 () Parentheses Left to right
2 x[index], x[index:in Subscription, Left to right
dex] slicing
3 await x Await expression N/A
4 ** Exponentiation Right to left
5 +x, -x, ~x Positive, Right to left
negative, bitwise
NOT
6 *, @, /, //, % Multiplication, Left to right
matrix, division,
floor division,
remainder
7 +, – Addition and Left to right
subtraction
8 <<, >> Shifts Left to right
9 & Bitwise AND Left to right
10 ^ Bitwise XOR Left to right
11 | Bitwise OR Left to right
12 in, not in, is, is Comparisons, Left to Right
not, <, <=, >, >=, !=, membership
== tests, identity
tests
13 not x Boolean NOT Right to left
14 and Boolean AND Left to right
15 or Boolean OR Left to right
16 if-else Conditional Right to left
expression
17 lambda Lambda N/A
expression
18 := Assignment Right to left
expression
(walrus operator)
Eg:
10 + 20 * 30 is calculated as 10 + (20 * 30)
and not as (10 + 20) * 30
To define the values of various data types and check their data types we use the type()
function.
1. NUMERIC
The numeric data type in Python represents the data that has a numeric value. A numeric value
can be an integer, a floating number, or even a complex number. These values are defined
as Python int, Python float, and Python complex classes in Python.
2.Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fractions or decimals). In Python, there is no limit to how long an integer
value can be.
3.Float – This value is represented by the float class. It is a real
number with a floating-point representation. It is specified by a decimal point. Optionally,
the character e or E followed by a
positive or negative integer may be appended to specify scientific notation.
4. Complex Numbers – Complex number is represented by a complex class. It is specified
as (real part) + (imaginary part)j. For example – 2+3j
5. SEQUENCE
The sequence Data Type in Python is the ordered collection of similar or different data types.
Sequences allow storing of multiple values in an organized and efficient fashion. There are
several sequence types in Python
6. String Data Type
Strings in Python are arrays of bytes representing Unicode characters. A string is a collection
of one or more characters put in a single quote, double-quote, or triple-quote. In python there
is no character data type, a character is a string of length one. It is represented by str class.
Creating String
Strings in Python can be created using single quotes or double quotes or even triple quotes.
Accessing elements of String
In Python, individual characters of a String can be accessed by using the method of
Indexing. Negative 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.
7. List Data Type
Lists are just like arrays, declared in other languages which is an ordered collection of data. It
is very flexible as the items in a list do not need to be of the same type.
Creating List
Lists in Python can be created by just placing the sequence inside the square brackets[].
Access List Items
In order to access the list items refer to the index number. Use the index operator [ ] to access
an item in a list. In Python, negative sequence indexes represent positions from the end of the
array. Instead of having to compute the offset as in List[len(List)-3], it is enough to just write
List[-3]. Negative indexing means beginning from the end, -1 refers to the last item, -2 refers
to the second-last item, etc.
8. Tuple Data Type
Just like a list, a tuple is also an ordered collection of Python objects. The only difference
between a tuple and a list is that tuples are immutable i.e. It is represented by a tuple
class.
Creating a Tuple
In Python, tuples are created by placing a sequence of values separated by a ‘comma’ with or
without the use of parentheses for grouping the data sequence. Tuples can contain any number
of elements and of any datatype (like strings, integers, lists, etc.).
Access Tuple Items
In order to access the tuple items refer to the index number. Use the index operator [ ] to
access an item in a tuple. The index must be an integer. Nested tuples are accessed using
nested indexing.
Data type with one of the two built-in values, True or False. Boolean objects that are equal to
True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can
be evaluated in a Boolean context as well and determined to be true or false. It is denoted by
the class bool.
9. Set
In Python, a Set is an unordered collection of data types that is iterable, mutable and has no
duplicate elements. The order of elements in a set is undefined though it may consist of
various elements.
Create a Set in Python
Sets can be created by using the built-in set() function with an iterable object or a sequence by
placing the sequence inside curly braces, separated by a ‘comma’. The type of elements in a
set need not be the same, various mixed-up data type values can also be passed to the set.
Access Set Items
Set items cannot be accessed by referring to an index, since sets are unordered the items has
no index. But you can loop through the set items using a for loop, or ask if a specified value is
present in a set, by using the in the keyword.
10.Dictionary
A dictionary in Python is an unordered collection of data values, used to store data values like
a map, unlike other Data Types that hold only a single value as an element, a Dictionary holds
a key: value pair. Key-value is provided in the dictionary to make it more optimized. Each
key-value pair in a Dictionary is separated by a colon : , whereas each key is separated by a
‘comma’.
Create a Dictionary
In Python, a Dictionary can be created by placing a sequence of elements within curly {}
braces, separated by ‘comma’. Values in a dictionary can be of any datatype and can be
duplicated, whereas keys can’t be repeated and must be immutable. The dictionary can also be
created by the built-in function dict(). An empty dictionary can be created by just placing it in
curly braces{}. Note – Dictionary keys are case sensitive, the same name but different cases
of Key will be treated distinctly.
Accessing Key-value in Dictionary
In order to access the items of a dictionary refer to its key name. Key can be used inside
square brackets. There is also a method called get() that will also help in accessing the element
from a dictionary.
c=a+b
print "Line 1 - Value of c is ", c
c=a-b
print "Line 2 - Value of c is ", c
c=a*b
print "Line 3 - Value of c is ", c
c=a/b
print "Line 4 - Value of c is ", c
c=a%b
print "Line 5 - Value of c is ", c
a=2
b=3
c = a**b
print "Line 6 - Value of c is ", c
a = 10
b=5
c = a//b
print "Line 7 - Value of c is ", c
OUTPUT
x1 = 2
y1 = 3
# point b
x2 = 5
y2 = 7
# distance b/w a and b
distance = ((x1 - x2)**2 + (y1 - y2)**2)**0.5
# display the result
print("Distance between points ({}, {}) and ({}, {}) is
{}".format(x1,y1,x2,y2,distance))
OUTPUT
PYTHON STATEMENT
A conditional statement is a logical expression where operators compare, evaluate, or check if
the input meets the conditions and returns ‘True’. If yes, the interpreter executes a specific set
of instructions. On the other hand, looping statements repeatedly execute a set of instructions
as long as the defined conditions are met or satisfied.
Types of statements in Python
The different types of Python statements are listed below:
Multi-Line Statements
Python Conditional and Loop Statements
Python If-else
Python for loop
Python while loop
Python try-except
Python with statement
Python Expression statements
Python pass statement
Python del statement
Python return statement
Python import statement
Python continue and break statement
Multiline Statements
Usually, we use the new line character (/n) to end a Python statement. However, if you want
to expand your code over multiple lines, like when you want to do long calculations and can’t
fit your statements into one line, you can use the continuation character (/).
Eg:
s = 10 + 15+ 30 + \
49 + 5 + 57 + \
3 - 54 - 2
Another way to create multiline statements is to use parentheses (), braces {}, square brackets
[], or even a semi-colon (;). While the continuation character marks an obvious line
continuation, the other multiline methods imply continuation indirectly.
Python if statement
The if statement is the most simple decision-making statement. It is used to decide whether a
certain statement or block of statements will be executed or not.
Syntax:
if condition:
# Statements to execute if
# condition is true
Here, the condition after evaluation will be either true or false. if the statement accepts
boolean values – if the value is true then it will execute the block of statements below it
otherwise not.
As we know, python uses indentation to identify a block. So the block under an if statement
will be identified as shown in the below example:
if condition:
statement1
statement2
BREAK STATEMENT
break statement in Python is used to bring the control out of the loop when some external
condition is triggered. break statement is put inside the loop body (generally after if
condition). It terminates the current loop, i.e., the loop in which it appears, and resumes
execution at the next statement immediately after the end of that loop. If the break statement is
inside a nested loop, the break will terminate the innermost loop.
SYNTAX
while True:
...
if x == 10:
continue
print(x)
Eg:
for var in "sree":
if var == "e":
continue
print(var)
7. Explain the various types of operators in python with suitable example?
PYTHON OPERATORS
In Python programming, Operators in general are used to perform operations on values and
variables. These are standard symbols used for the purpose of logical and arithmetic
operations.
OPERATORS: These are the special symbols. Eg- + , * , /, etc.
OPERAND: It is the value on which the operator is applied.
Types of Operators in Python
Arithmetic Operators
Comparison Operators
Logical Operators
Bitwise Operators
Assignment Operators
Identity Operators and Membership Operators
> Greater than: True if the left operand is greater than the right x>y
Operator Description Syntax
< Less than: True if the left operand is less than the right x<y
x ==
== Equal to: True if both operands are equal
y
Greater than or equal to True if the left operand is greater than or equal to x >=
>=
the right y
Less than or equal to True if the left operand is less than or equal to the x <=
<=
right y
= is an assignment operator and == comparison operator.
And Logical AND: True if both the operands are true x and y
| Bitwise OR x|y
Operator Description Syntax
~ Bitwise NOT ~x
Performs Bitwise left shift on operands and assign value to a <<= b a= a <<
<<=
left operand b
7. How to split string and what function is used to perform that operation?
The split() function in Python is a built-in string method that is used to split a string into
a list of substrings based on a specified delimiter. The function takes the delimiter as an
argument and returns a list of substrings obtained by splitting the original string
wherever the delimiter is found.
PART B AND C
1. Explain the following with example
(I) creating the list
Lists in Python can be created by just placing the sequence inside the square brackets[].
# Creating a List
List = []
print("Blank List: ")
print(List)
Eg:
List = []
print("Initial blank List: ")
print(List)
# Addition of Elements
# in the List
List.append(1)
List.append(2)
List.append(4)
print("\nList after Addition of Three elements: ")
print(List)
# Creating a List
List = [1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12]
print("Initial List: ")
print(List)
dict.items() Returns a list containing a tuple for each key value pair
dict.setdefault(key,default= set the key to the default value if the key is not specified
“None”) in the dictionary
dict.get(key, default = “None”) used to get the value specified for the passed key.
Eg:
# demo for all dictionary methods
dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}
# copy() method
dict2 = dict1.copy()
print(dict2)
# clear() method
dict1.clear()
print(dict1)
# get() method
print(dict2.get(1))
# items() method
print(dict2.items())
# keys() method
print(dict2.keys())
# pop() method
dict2.pop(4)
print(dict2)
# popitem() method
dict2.popitem()
print(dict2)
# update() method
dict2.update({3: "Scala"})
print(dict2)
# values() method
print(dict2.values())
LIST PROGRAM
list = [“apple”, ”ball”,” cat”,” dog”]
print(list)
print(list[0])
list2 = [1,3,5,7,8,4]
print(sum(list2))
print(min(list2))
print(max(list2))
print(list2[0])
print(list2[-1])
OUTPUT
[‘apple’,’ball’,’cat’,’dog’]
Apple
28
1
8
1
4
TUPLE PROGRAM
Tuple1 tuple(input(“enter the tuple elemets…”)
Print(tuple1)
Count = 0
For I in tuple1:
Print(“tuple1[%d] = %s”(count, i)
Count = count+1
OUTPUT
4. what is sets? Explain python sets in detail discussing the operation and methods
with suitable example?
Soln:
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage.
A set is a collection which is unordered, unchangeable*, and unindexed.
Sets are written with curly brackets.
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be
referred to by index or key.
Eg:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set has been
created.
Once a set is created, you cannot change its items, but you can remove items and add new
items
Python string is the collection of the characters surrounded by single quotes, double quotes, or
triple quotes. The computer does not understand the characters; internally, it stores
manipulated character as the combination of the 0's and 1's.
Each character is encoded in the ASCII or Unicode character. So we can say that Python
strings are also called the collection of Unicode characters.
In Python, strings can be created by enclosing the character or the sequence of characters in
the quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the
string.
We can create a string by enclosing the characters in single-quotes or double- quotes. Python
also provides triple-quotes to represent the string, but it is generally used for multiline string
or docstrings.
String Slicing
In Python, 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.
Example:
In this example, we will use the string-slicing method to extract a substring of the original
string. The [3:12] indicates that the string slicing will start from the 3rd index of the string to
the 12th index, (12th character not including). We can also use negative indexing in string
slicing.
Reversing a Python String
By accessing characters from a string, we can also reverse strings in Python. We can
Reverse a string by using String slicing method.
Example:
In this example, we will reverse a string by accessing the index. We did not specify the first
two parts of the slice indicating that we are considering the whole string, from the start index
to the last index.
Deleting/Updating from a String
In Python, the Updation or deletion of characters from a String is not allowed. This will
cause an error because item assignment or item deletion from a String is not supported.
Although deletion of the entire String is possible with the use of a built-in del keyword. This
is because Strings are immutable, hence elements of a String cannot be changed once
assigned. Only new strings can be reassigned to the same name.
Updating a character
A character of a string can be updated in Python by first converting the string into a Python
List and then updating the element in the list. As lists are mutable in nature, we can update
the character and then convert the list back into the String.
Another method is using the string slicing method. Slice the string before the character you
want to update, then add the new character and finally add the other part of the string again
by string slicing.
Updating Entire String
As Python strings are immutable in nature, we cannot update the existing string. We can only
assign a completely new value to the variable with the same name.
Deleting a character
Python strings are immutable, that means we cannot delete a character from it. When we try to
delete thecharacter using the del keyword, it will generate an error.
Deleting Entire String
Deletion of the entire string is possible with the use of del keyword. Further, if we try to print
the string, this will produce an error because the String is deleted and is unavailable to be
printed.
Escape Sequencing in Python
While printing Strings with single and double quotes in it causes SyntaxError because String
already contains Single and Double Quotes and hence cannot be printed with the use of either
of these. Hence, to print such a String either Triple Quotes are used or Escape sequences are
used to print Strings.
Escape sequences start with a backslash and can be interpreted differently. If single quotes are
used to represent a string, then all the single quotes present in the string must be escaped and
the same is done for Double Quotes.
Formatting of Strings
Strings in Python can be formatted with the use of format() method which is a very versatile
and powerful tool for formatting Strings. Format method in String contains curly braces {} as
placeholders which can hold arguments according to position or keyword to specify the order.
Python String constants
Built-In Function Description
Returns True if a string ends with the given suffix otherwise returns
String.endswith()
False
Returns True if a string starts with the given prefix otherwise returns
String.startswith()
False
String.Isalnum Returns true if all the characters in a given string are alphanumeric.
String.partition splits the string at the first occurrence of the separator and returns a tuple.
Returns the highest index of the substring inside the string if substring is
String.rindex
found.
string.lower Return a copy of s, but with upper case, letters converted to lower case.
Return a list of the words of the string, If the optional second argument
string.split
sep is absent or None
string.rsplit() Return a list of the words of the string s, scanning s from the end.
Return a list of the words of the string when only used with two
string.splitfields
arguments.
It returns a copy of the string with both leading and trailing white spaces
string.strip()
removed
string.lstrip Return a copy of the string with leading white spaces removed.
string.rstrip Return a copy of the string with trailing white spaces removed.
Built-In Function Description
string.swapcase Converts lower case letters to upper case and vice versa.
Pad a numeric string on the left with zero digits until the given width is
string-zfill
reached.
Encodes the string into any encoding supported by Python. The default
string.encode
encoding is utf-8.
The term "IDE" refers for "Integrated Development Environment," which is a coding tool
that aids in automating the editing, compiling, testing, and other steps of an SDLC while
making it simple for developers to execute, write, and debug code.
It is specifically made for software development and includes a number of tools that are
used in the creation and testing of the software.
PyCharm
Spyder
PyDev
Atom
Wing
Jupyter Notebook
Thonny
Pycharm
The Jet Brains created PyCharm, a cross-platform Integrated Development Environment
(IDE) created specifically for Python. It is the most popular IDE and is accessible in both
a premium and a free open-source version. By handling everyday duties, a lot of time is
saved.
It is a full-featured Python IDE with a wealth of features including auto code completion,
easy project navigation, quick error checking and correction, support for remote
development, database accessibility, etc.
Features
o Smart code navigation
o Errors Highlighting
o Powerful debugger
spyder
Spyder is a well-known open-source IDE that is best suited for data research and has a
high level of recognition in the industry. Scientific Python Development Environment is
Spyder's full name. It supports all popular operating systems,including Windows, MacOS
X, and Linux.
A number of features are offered by it, including a localised code editor, a document
viewer, a variable explorer, an integrated console, etc. It also supports a number of
scientific modules, including SciPy and NumPy.
Features
o Proper syntax highlighting and auto code completion
o Performs well in multi-language editor and auto code completion mode
pydev
As an external plugin for Eclipse, PyDev is one of the most popular Python IDEs. The
Python programmers who have a background in Java naturally gravitate towards this
Python interpreter because it is so well-liked by users.
In 2003-2004, Aleksandar Totic, who is well known for his work on the Mosaic
browser, contributed to the Pydev project.
Django integration, code auto-completion, smart and block indents, among other
features, are features of Pydev.
Features
o Strong Parameters like refactoring, debugging, code analysis, and
codecoverage function.
o It supports virtual environments, Mypy, and black formatter.
o Also supports PyLint integration, remote debugger, Unit test integration, etc.
Atom
GitHub, a company that was first founded as an open-source, cross-platform project, is
the company that creates Atom. It is built on the Electron framework, which enables
cross-platform desktop applications utilising Chromium and Node.js and is dubbed the
"Hackable Text Editor for the 21st Century."
Features
o Visualize the results on Atom without open any other window.
o A plugin named "Markdown Preview Plus" provides built-in
support forediting and visualizing Markdown files.
WING
It's described as a cross-platform IDE with a tonne of useful features and respectable
development support. It is free to use in its personal edition. The 30- day trial period for
the pro version is provided for the benefit of the developers.
Features
Customizable and can have extensions as well
JUPYTER NOTEBOOK
Jupyter is one of the most used Python notebook editors that is used across the Data
Science industry. You can create and edit notebook documents using this web application,
which is based on the server-client architecture. It utilises Python's interpretive nature to
its fullest potential.
Features
o Supports markdowns
o Easy creation and editing of codes
o Ideal for beginners in data science
THONNY
Thonny is a Python IDE (Integrated Development Environment) that is open- source,
free, and geared towards beginners. Since its initial release in 2016, it has grown to be a
well-liked option for novice Python coders.
Thonny IDE that works well for teaching and learning programming is Thonny.
Software that highlights syntax problems and aids code completion was created at the
University of Tartu.
Features
o Simple debugger
o Supports highlighting errors and auto code completion
6. Explain about packages in python with example?
The files are organize in different folders and subfolders based on some criteria, so that
they can be managed easily and efficiently. For example, we keepall our games in a
Games folder and we can even subcategorize according to the genre of the game or
something like this. The same analogy is followed by the packages in Python.
What is a Python Package?
Python modules may contain several classes, functions, variables, etc.
whereas Python packages contain several modules. In simpler terms, Package
in Python isa folder that contains various modules as files.
Creating Package
create a package in Python named mypckg that will contain two modules mod1 and mod2.
To create this module follow the below steps:
Create a folder named mypckg.
Inside this folder create an empty Python file i.e. init .py
Then create two modules mod1 and mod2 in this folder.
init__.py helps the Python interpreter recognize the folder as a package. It alsospecifies the
resources to be imported from the modules. If the init__.py is empty this means that all the
functions of the modules will be imported. We can also specify the functions from each
module to be made available.
For example,
from .mod1 import gfg
from .mod2 import sum
Import Modules from a Package
We can import these Python modules using the from…import statement
and thedot(.) operator.
Syntax:
import package_name.module_name
Example
from mypckg
import mod1from mypckg
import mod2mod1.gfg()
res = mod2.sum(1, 2)print(res)
Syntax
file.seek(offset, from_where)
The seek method takes two arguments: the first is the offset from the beginning ofthe file,
and the second is an optional reference point that specifies where the offset is relative to.
By default, the reference point is the beginning of the file. Theoffset can be positive (to
move the pointer forward) or negative (to move the pointer backward).
Example
tell() method
The tell method returns the current position of the file pointer, in bytes from the start of
the file. The position is an integer that represents the number of bytes from the beginning
of the file.’
Syntax:
file.tell()
The seek() and tell() methods are used for file cursor manipulation. The seek() method
EXAMPLE
with open("file.txt", "r") as f:
print(f.read(5)) # Prints the first 5 characters of the file
print("Current position:", f.tell()) # Prints the current position of the file pointer
f.seek(5) # Move the file pointer to the 6th character
print(f.read(5)) # Prints the next 5 characters of the file
repositions
the cursor to a specified byte offset, facilitating navigation within the file, while the tell()
method returns the current cursor position. These methods aid in precise file navigation and data
manipulation
1. Syntax errors
2. Logical errors (Exceptions)
SYNTAX ERRORS
When the proper syntax of the language is not followed then a syntax error
isthrown.
Example
# initialize the amount
variableamount = 10000
# check that You are eligible
to # purchase Dsa Self Paced
or notif(amount>2999)
print("You are eligible to purchase Dsa Self Paced")
LOGICAL ERRORS(EXCEPTION)
When in the runtime an error that occurs after passing the syntax test is called
exception or logical type. For example, when we divide any number by zero
thenthe ZeroDivisionError exception is raised, or when we import a module that
doesnot exist then ImportError is raised.
Example
# initialize the amount
variablemarks = 10000
# perform division with
0a = marks / 0
print(a)
Error Description
Error Description
Syntax Description
Operation
Open the file for reading and writing and creates new
Append a+ file if it doesn‟t exist. All additions are made at the end
and Read of the file and no existing data can be modified.
Example
writelines() : For a list of string elements, each string is inserted in the textfile.Used
to insert multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
Reading from a file
There are three ways to read data from a text file.
read() : Returns the read bytes in form of a string. Reads n bytes, if no n
specified, reads the entire file.
File_object.read([n])
readline() : Reads a line of the file and returns in form of a string.For
specified n,reads at most n bytes. However, does not reads more than
one line, even if n exceeds the length of the line.
File_object.readline([n])
readlines() : Reads all the lines and return them as each line a string
element in alist.
File_object.readlines()
Example
# Program to show various ways to read and
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]# \n is
placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.writelines(L)
file1.close()
#to change file access modes
file1 = open("myfile.txt","r+")
print("Output of Read function is ")
print(file1.read())
print()
# seek(n) takes the file handle to the nth# byte from the beginning.
file1.seek(0)
print( "Output of Readline function is ")
print(file1.readline())
print file1.seek(0)
# To show difference between read and readline
print("Output of Read(9) function is ")
print(file1.read(9))
print() file1.seek(0)
print("Output of Readline(9) function is ")
print(file1.readline(9))
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
UNIT IV
MODULES, PACKAGES AND FRAMEWORKS
Modules: Introduction – Module Loading and Execution – Packages – Making Your
Own Module – The Python Libraries for data processing, data mining and
visualization- NUMPY, Pandas, Matplotlib, Plotly-Frameworks- -Django, Flask,
Web2Py.
1. What is module and package in python?
MODULE
a. In python, module is a way to structure program. Each program file in a
module,which imports either modules like object and attribute.
b. A module is a simply a file that defines one or more related functions grouped
together. To reuse the function of a given module, we need to import module.
PACKAGE
c. A package is a collection of modules in Directories that gives a package
hierarchy. When a complex application/program is created it is better to be
organized.
d. The package gives a hierarchical file directory structure of the python
application environment that consists of modules and sub packages and sub-
sub packages
and soon.
2. What are the ways to import a module?
a. Using the import statement
b. Using from clause
c. Using from clause and *
3. What is meant by module in python?
In python, module is a way to structure program. Each program file in a module,which
imports either modules like object and attribute. A module is a simply a file that defines one
or more related functions groupedtogether. To reuse the function of a given module, we need
to import module.
Syntax: import <modulename>
4. List some built in modules in python?
a. OS module for interacting with the operating system.
b. Date time module for working with dates and times.
c. Math module for mathematical operations.
d. csv module for reading and writing csv files.
e. JSON module for working with JSON data.
5. What are the data visualization libraries in python?
Matplotlib
Seaborn
Bokeh
Plotly
PART B and C
1. Explain data visualization techniques in python ?
Python provides various libraries that come with different features for visualizing
data. All these libraries come with different features and can support various types of
graphs.
Scatter Plot
Scatter plots are used to observe relationships between variables and uses dots to
represent the relationship between them. The scatter() method in the matplotlib
library is used to draw a scatter plot.
Line Chart
Line Chart is used to represent a relationship between two data X and Y on a
different axis. It is plotted using the plot() function.
Bar Chart
A bar plot or bar chart is a graph that represents the category of data with rectangular
bars with lengths and heights that is proportional to the values which they represent.
It can be created using the bar() method.
Histogram
A histogram is basically used to represent data in the form of some groups. It is a
type of bar plot where the X-axis represents the bin ranges while the Y-axis gives
information about frequency. The hist() function is used to compute and create a
histogram. In histogram, if we pass categorical data then it will automatically
compute the frequency of that data i.e. how often each value occurred.
Seaborn
Seaborn is a high-level interface built on top of the Matplotlib. It provides beautiful
design styles and color palettes to make more attractive graphs.
To install seaborn type the below command in the terminal.
pip install seaborn
Scatter Plot
Scatter plot is plotted using the scatterplot() method. This is similar to Matplotlib,
but additional argument data is required.
Line Plot
Line Plot in Sea born plotted using the lineplot() method. In this, we can pass only
the data argument also.
BOKEH
Bokeh is mainly famous for its interactive charts visualization. Bokeh renders its
plots using HTML and JavaScript that uses modern web browsers for presenting
elegant, concise construction of novel graphics with high-level interactivity.
To install this type the below command in the terminal.
pip install bokeh
Interactive Data Visualization
One of the key features of Bokeh is to add interaction to the plots.
Interactive Legends
click_policy property makes the legend interactive. There are two types of
interactivity –
Hiding: Hides the Glyphs.
Muting: Hiding the glyph makes it vanish completely, on the other hand, muting
the glyph just de-emphasizes the glyph based on the parameters.
Adding Widgets
Bokeh provides GUI features similar to HTML forms like buttons, sliders,
checkboxes, etc. These provide an interactive interface to the plot that allows
changing the parameters of the plot, modifying plot data, etc. Let’s see how to use
and add some commonly used widgets.
Buttons: This widget adds a simple button widget to the plot. We have to pass a
custom JavaScript function to the CustomJS() method of the models class.
Checkbox Group: Adds a standard check box to the plot. Similarly to buttons
we have to pass the custom JavaScript function to the CustomJS() method of the
models class.
Radio Group: Adds a simple radio button and accepts a custom JavaScript
function.
This is the last library of our list and you might be wondering why plotly.
Plotly has hover tool capabilities that allow us to detect any outliers or anomalies
in numerous data points.
It allows more customization.
It makes the graph visually more attractive.
To install it type the below command in the terminal.
pip install plotly
UNIT V
OBJECT ORIENTED PROGRAMMING IN
UNIT V PYTHON
Creating a Class, Class methods, Class Inheritance, Encapsulation, Polymorphism,
class method vs. static methods, Python object persistence.
1. How to create a class in python?
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.
Inheritance allows us to define a class that inherits all the methods and
properties from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived
class.
4. Define encapsulation?
Encapsulation is a mechanism of wrapping the data (variables) and code
acting on the data (methods) together as a single unit. In encapsulation, the
variables of a class will be hidden from other classes, and can be accessed
only through the methods of their current class
5. Define polymorphism?
Polymorphism defines the ability to take different forms. Polymorphism in
Python allows us to define methods in the child class with the same name as
defined in their parent class.
PART B AND C
1. Explain briefly about OOPs concept in python?
OOPS CONCEPT IN PYTHON
An object-oriented paradigm is to design the program using classes and objects. The
object is related to real-word entities such as book, house, pencil, etc. The oops
concept focuses on writing the reusable code. It is a widespread technique to solve the
problem by creating objects.
Major principles of object-oriented programming system are given below.
o Class
o Object
o Method
o Inheritance
o Polymorphism
o Data Abstraction
o Encapsulation
Class
The class can be defined as a collection of objects. It is a logical entity that has some
specific attributes and methods. For example: if you have an employee class, then it
should contain an attribute and method, i.e. an email id, name, age, salary, etc.
Object
The object is an entity that has state and behavior. It may be any real-world object like
the mouse, keyboard, chair, table, pen, etc.Everything in Python is an object, and
almost everything has attributes and methods. All functions have a built-in attribute
__doc__, which returns the docstring defined in the function source code.
Method
The method is a function that is associated with an object. In Python, a method is not
unique to class instances. Any object type can have methods.
Inheritance
Inheritance is the most important aspect of object-oriented programming, which
simulates the real-world concept of inheritance. It specifies that the child object
acquires all the properties and behaviors of the parent object.By using inheritance, we
can create a class which uses all the properties and behavior of another class. The new
class is known as a derived class or child class, and the one whose properties are
acquired is known as a base class or parent class.It provides the re-usability of the
code.
Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many, and
morph means shape. By polymorphism, we understand that one task can be performed
in different ways. For example - you have a class animal, and all animals speak. But
they speak differently. Here, the "speak" behavior is polymorphic in a sense and
depends on the animal. So, the abstract "animal" concept does not actually "speak",
but specific animals (like dogs and cats) have a concrete implementation of the action
"speak".
Encapsulation
Encapsulation is also an essential aspect of object-oriented programming. It is used to
restrict access to methods and variables. In encapsulation, code and data are wrapped
together within a single unit from being modified by accident.
Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are nearly
synonyms because data abstraction is achieved through encapsulation. Abstraction is
used to hide internal details and show only functionalities. Abstracting something
means to give names to things so that the name captures the core of what a function or
a whole program does.
The class method in Python is a method, which is bound to the class but not the object
of that class. The static methods are also same but there are some basic differences.
For class methods, we need to specify @classmethod decorator, and for static method
@staticmethod decorator is used.
The class method takes the Static methods do not know about class
class as parameter to know state. These methods are used to do some
about the state of that class. utility tasks by taking some parameters.
@classmethod decorator is @staticmethod decorator is used here.
used here.
The Static methods are used to do some utility tasks, and class methods are used
for factory methods. The factory methods can return class objects for different use
cases.
Example code
from datetime import date as dt
class Employee:
def __init__(self, name, age):
self.name = name
self.age = age
@staticmethod
defisAdult(age):
if age > 18:
return True
else:
return False
@classmethod
defemp_from_year(emp_class, name, year):
return emp_class(name, dt.today().year - year)
def __str__(self):
return 'Employee Name: {} and Age: {}'.format(self.name, self.age)
e1 = Employee('Dhiman', 25)
print(e1)
e2 = Employee.emp_from_year('Subhas', 1987)
print(e2)
print(Employee.isAdult(25))
print(Employee.isAdult(16))