HG NOTES
HG NOTES
HG NOTES
ppypython
UNIT 1
Introduction To Data Structures
IV SEM CSE 1
Data structure with python 20CS41P
ppypython
IV SEM CSE 2
Data structure with python 20CS41P
ppypython
Python
Tuple1 = ()
print("Initial empty Tuple:
") print(Tuple1)
Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of
String: ") print(Tuple1)
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List:
") print(tuple(list1))
Tuple1 = tuple('Geeks')
print("\nTuple with the use of
IV SEM CSE 3
Data structure with python 20CS41P
ppypython
function: ") print(Tuple1)
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python',
'geek') Tuple3 =
(Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)
Output:
Initial Tuple:
empty
()
Tuple with the use of String:
('Geeks', 'For')
Tuple using List:
(1, 2, 4, 5, 6)
Tuple with the use of function:
('G', 'e', 'e', 'k', 's')
Tuple with nested tuples:
((0, 1, 2, 3), ('python',
'geek'))
Note – The creation of a Python tuple without the use of
parentheses is known as Tuple Packing.
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.
The code creates a tuple named ‘tuple1′ with five elements: 1, 2,
3, 4, and
5. Then it prints the first, last, and third last elements of the
tuple using indexing.
Python
IV SEM CSE 4
Data structure with python 20CS41P
ppypython
print(tuple1[-1])
print(type(True))
print(type(False
))
print(type(true)
)
Output:
<class 'bool'
>
<class 'bool'>
Traceback (most recent call
last):
File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8,
in print(type(true))
NameError: name 'true' is not defined
IV SEM CSE 5
Data structure with python 20CS41P
ppypython
IV SEM CSE 6
Data structure with python 20CS41P
ppypython
set1 = set()
print("Initial blank Set:
") print(set1)
set1 = set("GeeksForGeeks")
print("\nSet with the use of
String: ") print(set1)
set1 = set(["Geeks", "For",
"Geeks"]) print("\nSet with the
use of List: ") print(set1)
set1 = set([1, 2, 'Geeks', 4, 'For', 6,
'Geeks']) print("\nSet with the use of Mixed
Values")
print(set1)
Output:
Initial blank
Set: set()
Set with the use of
String:
{'F', 'o', 'G', 's', 'r', 'k', 'e'
}
Set with the use of
List:
{'Geeks', 'For'
}
Set with the use of Mixed
Values
{1, 2, 4, 6, 'Geeks', 'For'}
Access Set Items
Set items cannot be accessed by referring to an index, since
sets are unordered the items have 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.
Example: This Python code creates a set named set1 with
the values “Geeks”, “For” and “Geeks”. The code then prints the
initial set, the elements of the set in a loop, and checks if the
value “Geeks” is in the
IV SEM CSE 7
Data structure with python 20CS41P
ppypython
set using the ‘in’ operator
Python
IV SEM CSE 8
PYTHON PROGRAMMING 20CS31P
for i in set1:
print(i, end=" ")
print("Geeks" in
set1)
Output:
Initial
set:
{'Geeks', 'For'
}
Elements of
set:
Geeks
For
True
Note – To know more about sets, refer to Python Sets.
5. Dictionary Data Type in Python
A dictionary in Python is an unordered collection of data values,
used to store data values like a map, unlike other Python 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
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.
Example: This code creates and prints a variety of dictionaries.
The first dictionary is empty. The second dictionary has integer
keys and string values. The third dictionary has mixed keys, with
one string key and one integer key. The fourth dictionary is
created using the dict() function, and
the fifth dictionary is created using the [(key, value)] syntax
Python
Dict
III SEM =
CSE{} 9
print("Empty Dictionary:
") print(Dict)
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer
PYTHON PROGRAMMING 20CS31P
print(Dict)
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair:
") print(Dict)
Output:
Empty
Dictionary:
{}
Dictionary with the use of Integer
Keys:
{1: 'Geeks', 2: 'For', 3:
'Geeks'} Dictionary with the use of
Mixed Keys:
{1: [1, 2, 3, 4], 'Name':
'Geeks'}
Dictionary with the use of
dict():
{1: 'Geeks', 2: 'For', 3:
'Geeks'} Dictionary with each item as
a pair:
{1: 'Geeks', 2: 'For'}
PYTHON OPERATOR:
Python Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Run example »
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
:= print(x := 3) x =
print(x)
ADVERTISEMENT
== Equal x == y
!= Not equal x != y
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the not(x < 5 and x <
result is true
<< Zero fill left Shift left by pushing zeros in from the right and let x << 2
shift the leftmost bits fall off
UNIT 3
CONTROL FLOW:
CONDITIONAL BLOCKS
In programming languages, most of the time in large projects we have to
control the flow of execution of our program and we want to execute some set
of statements only if the given condition is satisfied, and a different set of
statements when it’s not satisfied. Conditional statements are also known as
decision-making statements. We need to use these conditional statements to
execute the specific block of code if the given condition is true or false.
In Python we can achieve decision making by using the following statements:
• if statements
• if-else statements
• elif statements
• Nested if and if-else statements
• elif ladder
In this tutorial, we will discuss all the statements in detail with some real-time
examples
#1) if statements
Python if statement is one of the most commonly used conditional statements
in programming languages. It decides whether certain statements need to be
executed or not. It checks for a given condition, if the condition is true, then
the set of code present inside the ” if ” block will be executed otherwise not.
The if condition evaluates a Boolean expression and executes the block of code
only when the Boolean expression becomes TRUE.
Syntax:
If ( EXPRESSION == TRUE ):
Block of code
else:
Block of code
Here, the condition will be evaluated to a Boolean expression (true or false). If
the condition is true, then the statement or program present inside the ” if ”
block will be executed and if the condition is false, then the statements or
program present inside the “else” block will be executed.
Let’s see how it looks on a flow chart
If you observe the above flow-chart, first the controller will come to an if
condition and evaluate the condition if it is true, then the statements will be
executed, otherwise the code present outside the block will be executed.
Let’s see some examples of ” if ” statements.
Example:
1 num = 5
In the above example, we declared a variable called ‘Num’ with the value as 5
and the ” if ” statement is checking whether the number is lesser than 10 or
not. If the condition is true then a set of statements inside the if block will be
executed.
Example: 2
a=7
b=0
if (a > b):
print(“a is greater than
b”) Output:
a is greater than b
In the above example, we are checking the relationship between a and b using
the greater than (>) operator in the if condition. If “a” is greater than “b” then
we will get the above output.
Example: 3
a=0
b=7i
f (b > a):
print(“b is greater than a”)
Output:
b is greater than a.
Example: 4
a=7
b=0
if (a):
print(“true”)
Output:
True
If you observe, in the above example, we are not using or evaluating any
condition in the “if” statement. Always remember that in any programming
language, the positive integer will be treated as true value and an integer
which is less than 0 or equal to 0 will be treated as false.
Here the value of a is 7 which is positive, hence it prints true in the
console output.
Example: 5
if (‘Python’ in [‘Java', ‘Python’, ‘C#’]):
print(“true”)
Output:
True
Here, we are verifying if the element ‘Python’ is present in the given list or not.
Hence it prints true because “ Python “ is present in the given list.
Let’s take one real-life example where we will use the Python if statement.
For Example: You have written an exam for a total score of 100 and if your
score is above or equal to 60 then you will be considered as PASS in the exam.
Let’s write the code for it.
Example: 6
passing_Score = 60
my_Score = 67
if(my_Score >= passing_Score):
print(“Congratulations! You have passed your exam”)
Output: Congratulations! You have passed your exam.
Remember to use the (:) operator at the end of the if statement, because
whatever the code you write after the colon operator will be a part of “if
block” and indentation is very important in Python.
Example: 7
passing_Score = 60
my_Score = 67 i
f(my_Score >= passing_Score):
print(“You passed the
exam”)
print(“Congratulations!”)
Output: You passed the exam Congratulations!
UNIT 4
Control Flow:
Loops Python
Loops:
The flow of the programs written in any programming language is sequential
by default. Sometimes we may need to alter the flow of the program. The
execution of a specific code may need to be repeated several number of times.
For this purpose, the programming languages provide various types of loops
which are capable of repeating some specific code several numbers of times.
Consider the following diagram to understand the working of a loop statement.
Advantages of loopS:
There are the following advantages of loops in Python
2. Using loops, we do not need to write the same code again and again.
3. Using loops, we can traverse over the elements of data structures (array or
linked lists).
Python While loop:
The Python while loop allows a part of the code to be executed until the given
condition returns false. It is also known as a pre-tested loop.
Syntax for while loop
while condition:
# body of while loop
A while loop evaluates the condition
If the condition evaluates to True, the code inside the while loop is executed.
condition is evaluated again.
This process continues until the condition is False.
When condition evaluates to False, the loop stops.
print("%d X %d = %d \n"%(number,i,number*i))
i = i+1
Output
Output:
Example-2
var = 1
while(var != 2):
while i <= n:
if i % 2 == 0:
sum += i i += 1
print("Sum of even numbers till
n:",sum) Output:
UNIT 5
Data Collections
SETS
Set is an unordered data collection that is iterable, mutable and does not
contain any duplicate elements. Sets are used to store multiple values in a
single variable. The major advantage of set when compared to lists is that sets
are optimized for checking whether a specific element is present in the set. The
sets have this advantage because they are stored based on data structure
known as hash table.
Sets are represented by {} with the values enclosed in the curly braces.
Example:
fruits = {“apple”, “kiwi”, “orange”}
Concept of mutability:
Mutable refers to a feature where we have ability to change. In python
mutable is the ability of objects to change their values. Sets are mutable
meaning we change the values in the set. However, the elements in the set
should be immutable.
Features:
The following are the major features of sets.
Sets are unordered: The elements in the set are not stored in the order as
specified in the definition of set.
Set elements are unique: The duplicate elements in the set are represented
in the set only once.
Sets are mutable: A set can be modified after its creation. The elements
contained in the set must be an immutable type.
Sets are heterogeneous: sets can contain elements of different type.
Declaration and Initialization:
Operations:
Below are the various operations which can be performed on the
sets. These can be accomplished with the built in methods
provided.
Adding an element to the set: add()
The add method can be used to add an element to the set. The
element can be any immutable data type. Below is the snapshot of
example code and its output when executed is highlighted in blue
color.
Clear() : This method removes all the elements from this set.
Below is the snapshot of example code and its output when
executed is highlighted in blue color.
UNIT 6
LISTS
Introduction
In any programming language a variable can hold a single value
of any type at once. To assign multiple values,we may need to
create separate variables and assign the values. But this method is
less efficient and more error prone.
To overcome these demerits, Python provides data types to
store collection of data with a single name. These are lists, tuples,
sets and dictionaries.
Definition:
The list is a sequence data type which is used to store the
collection of data. Tuples and String are other types of sequence
data types.
A List can be defined as an ordered collection of data-items of any
data type and allows duplicated data items.
Lists are one of 4 built-in data types in Python used to store
collections of data, the other three are tuples, sets and dictionary,
all with different qualities and usage.
How to create list??
In Python a list can be created in three different ways
List can be created by placing comma sepearated values inside
square brackets.
syntax:
List_name=[item1,item2,.........itemn]
Where : List_name is any valid identifier
item1,item2,.......itemn can be value of any data type
Examples
1) List1=[1,2,3] # List of integers
III SEM CSE 42
PYTHON PROGRAMMING 20CS31P
3) The comparison operators can also be used with the lists for
comparing one list with the other.
Example:
a = ['foo', 'bar', 'baz', 'qux']
print( ‘foo’ in a) # prints True because ‘foo’ is present in a
print( ‘xyz’ in a) # prints False
print( ‘abc’ not in a) # Returns True as ‘abc’ is not present in a
Features of Lists:
2) Lists can contain any arbitrary objects: A list can contain data
items of any type
3) List items can be accessed by index: Each individual data items
from the list can be accessed by indexing. The index for a data
item in the list can be positive or negative.
4) Lists can be nested to arbitrary depth.
The items in the list can be of any type.
A list can contain another list as its item.
A list can contain sublists, which in turn can contain sublists
themselves, and so on to arbitrary depth.
Example:
x = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', ['hh', 'ii'], 'j']
print(x) ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', ['hh', 'ii'], 'j']
print(x)
UNIT 7
DICTIONARY
Dictionary
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:
You can initialize a dictionary with multiple items at once. Here's how:
my_dictionary = {
'apple': 'A sweet, edible fruit',
'banana': 'A long, curved fruit',
'cherry': 'A small, round fruit',
}
Now that we have a dictionary with some items, let's learn how to access
these items. We can do this using the keys:
my_dictionary = {
'apple': 'A sweet, edible fruit',
'banana': 'A long, curved fruit',
'cherry': 'A small, round fruit',
}
In this example, we've accessed the value of 'apple' using the key and
printed it. It's like saying, "Give me the definition of 'apple'."
Basic operations:
items() Returns a list containing a tuple for each key value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert
specified value
Membership operators:
Indexing:
UNIT 8
Arrays and
Strings Arrays
Features:
Each array element is of the same data type and size. For
example: For an array of integers with the int data type,
each element of the array will occupy 4 bytes.
Elements of the array are stored in contiguous memory
locations.
Create:
Array in Python can be created by importing an
array module. array(data_type, value_list) is used to create array in
Python with data type and value list specified in its arguments.
In below code Python create array : one of integers and one of
doubles. It then prints the contents of each array to the
Output
The new created array is1
2 3
Initialize:
comprehension
range(4)}
# printing result
Output
New dictionary with empty lists as keys : {0: [], 1: [], 2:
[], 3: []}New dictionary with empty lists as keys : {0: [],
1: [], 2: [], 3: []}
Strings:
Syntax
Following is the syntax of Python dictionary str() method −
str(dict)
empty = dict ()
(empty))
Assigning:
Add to Python Dictionary Without Overwriting Values
Output
original dictionary: {'a': 1, 'b': 2}
updated dictionary: {'a': 100, 'b': 2, 'c': 3, 'd': 4}
Indexing :
In Python, indexing refers to the process of accessing a specific
element in a sequence, such as a string or list, using its position
or index number. Indexing in Python starts at 0, which means
that the first element in a sequence has an index of 0, the
second element has an index of 1, and so on. For example, if
we have a string "Hello", we can access the first letter "H" using
its index 0 by using the square bracket notation: string[0].
Python's built-in index() function is a useful tool for finding the index of a
specific element in a sequence. This function takes an argument
representing the value to search for and returns the index of the first
occurrence of that value in the sequence.
If the value is not found in the sequence, the function raises a ValueError.
For example, if we have a list [1, 2, 3, 4, 5], we can find the index of the
value 3 by calling list.index(3), which will return the value 2 (since 3 is the
third element in the list, and indexing starts at 0).
The index() function is a powerful tool in Python as it simplifies the process
of finding the index of an element in a sequence, eliminating the need for
writing loops or conditional statements. This function is especially useful
when working with large datasets or complex structures, where manual
searching could be time-consuming and error-prone.
Example
Get your own Python
Server
What is the position of the value "cherry":
x = fruits.index("cherry”)
String operators:
UNIT 9
FUNCTIONS
Introduction:
Python Functions is a block of statements that return the specific
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.
Need of Function:
So it turns out you already know what a function is. You have
been using it the whole time while studying this tutorial!
Example
int main() {
printf("Hello World!");
return 0;
}
Types:
There are two types of functions in python:
Define function:
Calling Function:
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()
Arguments:
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the
function to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias
")
my_function("Linus"
)
Recursion:
Recursion is a common mathematical and programming concept. It means
that a function calls itself. This has the benefit of meaning that you can loop
through data to reach a result.
The developer should be very careful with recursion as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess
amounts of memory or processor power. However, when written correctly
recursion can be a very efficient and mathematically-elegant approach to
programming.
Example
Recursion Example
def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-
1)
else: print(resul
t)
return
result result = 0
print("\n\nRecursion Example
Results") tri_recursion(6)
UNIT 10
MODULES AND PACKAGES
Why Modules:
Consider a module to be the same as a code library.
Create a Module
To create a module just save the code you want in a file with the file
extension .py:
Example
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule
my module.greeting("Jonathan")
Variables in Module
The module can contain functions, as already described, but also variables of
all types (arrays, dictionaries, objects etc):
Example
Save this code in the file mymodule.py
person1 =
{ "name": "John",
"age": 36,
"country":
"Norway"
}
Example
Import the module named mymodule, and access the person1 dictionary:
import mymodule
a =
mymodule.person1["age"] print(a)
Naming a Module
You can name the module file whatever you like, but it must have the file
extension .py
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Example
Create an alias for mymodule called mx:
import mymodule as mx
a =
mx.person1["age"] print(a)
Built-in Modules
There are several built-in modules in Python, which you can import whenever
you like.
Example
Import and use the platform module:
import platform
x =
platform.system() print(x)
Packages:
Python Package
includes the
UNIT 11
NUMPY AND PANDAS
Numpy:
NumPy is a Python library used for working with arrays.
Arrays are very frequently used in data science, where speed and resources
are very important.
It is best practice to install NumPy with the full SciPy stack. The binary
distribution of the SciPy stack is specific to the operating systems.
Windows
On the Windows operating system, The SciPy stack is provided by the
Anaconda which is a free distribution of the Python SciPy package.
Simple Arithmetic
You could use arithmetic operators + - * / directly between NumPy arrays,
but this section discusses an extension of the same where we have functions
that can take any array-like objects e.g. lists, tuples etc. and perform
arithmetic conditionally.
Addition
The add() function sums the content of two arrays, and return the results in
a new array.
Example
Add the values in arr1 to the values in arr2:
import numpy as np
newarr = np.add(arr1,
arr2) print(newarr)
Subtraction
The subtract() function subtracts the values from one array with the
values from another array, and return the results in a new array.
Example
Subtract the values in arr2 from the values in arr1:
import numpy as np
newarr = np.subtract(arr1,
arr2) print(newarr)
Multiplication
The multiply() function multiplies the values from one array with the
values from another array, and return the results in a new array.
Example
Multiply the values in arr1 with the values in arr2:
import numpy as np
newarr = np.multiply(arr1,
arr2) print(newarr)
Division
The divide() function divides the values from one array with the values
from another array, and return the results in a new array.
Example
Divide the values in arr1 with the values in arr2:
import numpy as np
arr2) print(newarr)
Power
The power() function rises the values from the first array to the power of
the values of the second array, and return the results in a new array.
Example
Raise the valules in arr1 to the power of values in arr2:
import numpy as np
newarr = np.power(arr1,
arr2) print(newarr)
Remainder
Both the mod() and the remainder() functions return the remainder of the
values in the first array corresponding to the values in the second array, and
return the results in a new array.
Example
Return the remainders:
import numpy as np
newarr = np.mod(arr1,
arr2) print(newarr)
Example
Return the quotient and mod:
import numpy as np
newarr = np.divmod(arr1,
arr2) print(newarr)
PANDAS INTRODUCTION:
What is Pandas ?
Pandas is a Python library used for working with data sets.
The name "Pandas" has a reference to both "Panel Data", and "Python Data
Analysis" and was created by Wes McKinney in 2008.
Pandas can clean messy data sets, and make them readable and relevant.
Environment Setup:
Windows
Anaconda (from https://www.continuum.io) is a free Python distribution
for SciPy stack. It is also available for Linux and Mac.
Windows
Anaconda (from https://www.continuum.io) is a free Python distribution
for SciPy stack. It is also available for Linux and Mac.
Canopy (https://www.enthought.com/products/canopy/) is available as
free as well as commercial distribution with full SciPy stack for
Windows, Linux and Mac.
Python (x,y) is a free Python distribution with SciPy stack and Spyder
IDE for Windows OS. (Downloadable from http://python-xy.github.io/)
Linux
Package managers of respective Linux distributions are used to
install one or more packages in SciPy stack.
UNIT 12
FILE CONCEPT
Features:
File handling in Python is a powerful and versatile tool that can
be used to perform a wide range of operations. However, it is
important to carefully consider the advantages and
disadvantages of file handling when writing Python programs,
to ensure that the code is secure, reliable, and performs well.
In this article we will explore Python File Handling, Advantages,
Disadvantages and How open, write and append functions works in
python file.
File operations:
File Handling
The key function for working with files in Python is the open() function.
"r" - Read - Default value. Opens a file for reading, error if the file does not
exist
"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
In addition you can specify if the file should be handled as binary or text mode
Opening files:
Open a File on the Server
Assume we have the following file, located in the same folder as Python:
demofile.txt
The open() function returns a file object, which has a read() method for
reading the content of the file:
Example
f = open("demofile.txt", "r")
print(f.read())
Closing Files:
You should always close your files, in some cases, due to buffering, changes
made to a file may not show until you close the file.
Syntax
file.close()
Writing to files:
To write to an existing file, you must add a parameter to the open() function:
Example
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()
f = open("demofile2.txt", "r")
print(f.read())
Reading files:
Read Only (‘r’) : Open text file for reading. The handle is positioned
at the beginning of the file. If the file does not exist, raises the
I/O error. This is also the default mode in which a file is
opened.
Read and Write (‘r+’): Open the file for reading and writing. The
handle is positioned at the beginning of the file. Raises I/O error
File Methods:
Python has a set of methods available for the file object.
UNIT 13
ERROR AND EXCEPTION HANDLING
Errors are the problems in a program due to which the program
will stop the execution. On the other hand, exceptions are raised
when some internal events occur which changes the normal flow
of the program. Two types of Error occurs
in python.
1. Syntax errors
2. Logical errors (Exceptions)
Python Errors:
Syntax Errors
Syntax errors, also known as parsing errors, are perhaps the most
common kind of complaint you get while you are still learning Python:
The parser repeats the offending line and displays little ‘arrow’s pointing at the
token in the line where the error was detected. The error may be caused by
the absence of a token before the indicated token. In the example, the
error is detected at the
, since a
function print() colon ( ':') is missing before it. File name and line number are
printed so you know where to look in case the input came from a script.
Exceptions
Even if a statement or expression is syntactically correct, it may cause an
error when an attempt is made to execute it. Errors detected
during execution are called exceptions and are not unconditionally
fatal: you will soon learn how to handle them in Python programs. Most
exceptions are not handled by programs, however, and result in error
messages as shown here:
10 * (1/0)
Traceback (most recent call
last): File "<stdin>", line 1,
in <module>
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call
last): File "<stdin>", line 1,
in <module>
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call
last): File "<stdin>", line 1,
The last line of the error message indicates what happened. Exceptions
come in different types, and the type is printed as part of the message:
the types in the example are ZeroDivisionError, NameError and
TypeError. The string printed as the exception type is the name of the
built-in exception that occurred. This is true for all built-in exceptions, but
need not be true for user-defined exceptions (although it is a useful
convention). Standard exception names are built-in identifiers (not
reserved keywords).
The rest of the line provides detail based on the type of exception and
what caused it.
The preceding part of the error message shows the context where the
exception occurred, in the form of a stack traceback. In general it contains
a stack traceback listing source lines; however, it will not display lines
read from standard input.
How to Catch Exceptions:
Different types of exceptions in python:
In Python, there are several built-in Python exceptions that can be
raised when an error occurs during the execution of a program.
Here are some of the most common types of exceptions in
Python:
SyntaxError: This exception is raised when the interpreter
encounters a syntax error in the code, such as a
misspelled keyword, a missing colon, or an unbalanced
parenthesis.
TypeError: This exception is raised when an operation
or function is applied to an object of the wrong type,
such as adding a string to an integer.
Raising Exceptions:
As a Python developer you can choose to throw an exception if a condition
occurs.
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
You can define what kind of error to raise, and the text to print to the user.
Example
Raise a TypeError if x is not an integer:
x = "hello"