Priciples of Python
Principles of Python
Principles Of Python
Contents
Introduction
to Python Programming
Output
Operations using print() function
Python
Typecasting / Type Conversions
Dynamic
and Strongly Typed Language
Sequential
Control Flow Statements:
Decision
Control Flow Statements / Selection
Control Statements
The
Countinue And Break Statement
Function
Definition and Calling
the Function / User- defined Functions
The
return statement and void Function
Scope
and Lifetime of Variables
String
Methods and Built-In Functions
List
methods and built – in functions
Copying
lists or cloning lists
Lists
as argument to a Function / Lists parameters
Accessing
Items in a Dictionary
Dictionary
Methods and Built-In Functions
Catching
the specific Exception
Chapter 1
Introduction to Python Programming
Python Introduction
·
The
most widely used and rapidly expanding computer programming language globally
is Python.
·
It
is a high-level, multipurpose programming language.
Python Inventor (3798361166a2e360f03e88de269bbf86.jpg
(800×800) (pinimg.com))
·
Although
Guido Van Rossum created Python in 1989, it wasn't until February 20, 1991,
that the program was made available to the general public.
·
Many
professions, including software engineers, data analysts, network engineers,
mathematicians, accountants, scientists, and many more, have used the Python
programming language. Python allows the solution of complicated problems with
fewer lines of code and in less time.
Characteristics of Python
The
Python is a very popular programming language with the following
characteristics.
·
Python
is a simple language to learn and comprehend.
·
Python
is a language for programming that is interpreted. Line by line, the code is
executed.
·
Cross-platform
programming is possible with Python. Any operating system, including Windows,
Linux, MAC OS, etc., can use it.
·
One
free and open-source programming language is Python.
·
Python
is a programming language that is procedural, functional, and object-oriented.
·
Python
is a versatile programming language.
·
High-order
programming languages like Python
·
Python
has a huge Community to get help all over the globe.
·
Python
has a large Ecosystem of Libraries, Frameworks, and Tools to work with it.
Python Interpreter
A
program called Python Interpreter is capable of reading and running Python
code. It executes in two different ways.
1.
REPL
2.
Mode for scripting
REPL
·
In
the REPL, We can query some statements, and python will interpret/execute them
and give you the output.
·
Interactive
mode is useful to test out our code before keeping them to the scripts.
·
We
can do operations like simple calculations, and printing some variables and
etc.
·
To
bring up the interactive python shell, Search for IDLE in windows.
·
For
Linux and Mac user, Goto Terminal and bring up the interactive python shell by
running python command.
We can
write our statements into interactive shell, In above case we written print("Hello
python") statement and pressed enter.
Then
python immediately executed our print statement and displayed the output. This
is called interactive mode.
Where we can perform simple operations and get the
results.
The
drawbacks of the interactive mode
•
Large
programs are not appropriate for the REPL
•
The
remarks are not saved in the REPL.
•
A
software we create is only good for that specific moment in time; it cannot be
used later. We have to retype each statement if we want to utilize it later.
•
It
takes a lot of work to edit code that is written in REPL. We must review every
command we have sent previously, and if we are still unable to amend, we must
type everything again.
Mode for Scripting
•
In
Python script mode, the script is written within a script file first, and then
it is executed.
•
The
Python IDE that is installed on our computer or the Command Prompt can both be
used to run the code script.
To execute a code in Mode of Scripting, take the
subsequent actions.
Step
1: Open a text editor and create a file. You are free to use any text editor
you choose; notepad is what I'm using here.
Step
2: Save the file with the ".py" suffix after writing the code.
Step
3: Go to the command directory where your file is kept and enter the command prompt.
Step
4: Type "filename.py" in Python and hit Enter.
Step
5: Your command prompt will display the output.
Example:
To run
"Hello Python" in REPL, we should create a file then save that file.
To run this file now, utilize the cmd.exe.
Google Colab
One
more important method is usage of google colab
to execute python code the code will be automatically saved in your
google account. You can download either ipynb file or py file by using google
colab.
Variables
Python
Variable is containers that store values. Python is not “statically typed”. We
do not need to declare variables before using them or declare their type. A
variable is created the moment we first assign a value to it. A Python variable
is a name given to a memory location. It is the basic unit of storage in a
program. Below is the Syntax for Variable creation.
Syntax:
variable_name = value
Notes:
• The value stored in a variable_name can be
changed during program execution.
• A Variables in Python is only a name given
to a memory location, all the operations done on the variable_name effects that
memory location.
Identifiers
Identifiers
are the name given to variables, classes, methods(functions), etc. For example,
language=’python’
Here, language is a variable (an identifier) which
holds the value 'Python'.
How to
give Identifier Name:
•
Identifiers
aren't allowed to be keywords.
•
It
is possible for identifiers to consist of a series of letters and numbers.
•
Case
matters. It must, however, start with a letter or _. An identifier's initial
letter cannot be a number.
•
It's
customary to begin an identifier with a letter as opposed to _.
• White space is not permitted.
Some Valid and Invalid Identifiers in Python
Python IO Operations
The io
module provides Python’s main facilities for dealing with various types of I/O.
There are three main types of I/O: text I/O, binary I/O and raw I/O.
In
Python, input and output operations (OI Operations) are performed using two
built-in functions. Following are the two built-in functions to perform output
operations and input operations.
• print( ) - Used for output operation.
• input( ) - Used for input operations.
Output Operations using print() function
The
built-in function print( ) is used to output the given data to the standard
output device (Screen).
Output Operations using print() function
To
output the specified data to the standard output device (Screen), use the
built-in print() function.
Displaying a message using print() function
In Python, using the print( ) function we can
display a text message. The print( ) takes a string as an argument and displays
the same.
Displaying a variable value using print() function
In
Python, the built-in function print() function is also used to display
variables value. The following example shows that how to display variable value
using print() function.
Use the formatted print() function to show a message
along with the value.
The
combination of message and variable value is likewise displayed using the
built-in print() function. Let's examine the subsequent illustration.
In
Python, we can use the formatted string that is prefixed with character "
f ". In the formatted string, the variable values are included using curly
braces ({ }).
The
format strings will contain the curly braces { } and the format() method will
use those curly braces { } as placeholders to replace with the content of the
parameters.
Input Operations using input() function
The
Python provides a built-in function input( ) to perform input operations. The
input( ) function can be used either with some message or without a message.
When
input( ) function is used without a message, it simply prompts for the input
value. When the user enters the input value it reads the entered value as a
string and assigns it to the left- hand-side variable.
Example :
a=input()
print(“The
number we have entered is “, a)
Here,
the major problem is that the user does not have any information regarding what
is the next step the user has to do? To solve this problem, we use the input( )
function with a message which tells the user that what the user has to do?
When
input( ) function is used with a message, it prompts with a given message for
the input value. When the user enters the input value it reads the entered
value as a string and assigns it to the left-hand-side variable.
Example :
num=input(‘Enter
any Number : ‘)
print(“The
number we have entered is “, num)
Declaring multiple variables in a single statement :
In
Python, it is possible to define more than one variable using a single
statement. When multiple variables are created using a single statement, the
variables and their corresponding value must be separated with a comma symbol.
Let's look at the following code which creates two variables with two different
values.
Example :
name,rollno=
('Soumya’,1)
print("Student
name is ",name," and " , "Roll number is ",rollno)
Always the input( ) function reads input value as
string value only.
To read the value
of any other data type,
there is no input function in Python. Explicitly we need to convert to the required
data type using
type casing.
Keywords
•
Keywords
are the reserved words in the Python programming language. All keywords are
designated with a special meaning to each.
•
The
meaning of all keywords is fixed and it cannot be modified or removed. All the
keywords need to be used as they have defined (Lower case or Upper case).
•
In
Python 3.10’s , there are 35 keywords .
Following is the Python code used to display all the
keywords in Python 3.12.
import keyword
print(keyword.kwlist)
Sample program to display all the keywords in
Python
Points to be Remembered
•
All
the keywords must be used as they have defined.
•
Keywords
should not be used as identifiers like variable names, functions name, class
name, etc.
•
The
meaning of each keyword is fixed, we cannot modify or remove it.
Python Data Types
Data
types specify the type of data like numbers and characters to be stored and
Manipulated within a program. Basic data types of Python are
• Numbers
• Boolean
• Strings
• None
Numbers /Numeric
The
Python programming language provides four numeric / Numbers data types. They
are as follows.
•
int
- All the numbers
without fraction part (Example : 10). For int, there is no upper limit.
•
float
- All the numbers
with a fraction part (Example : 10.5). It’s accurate up to 15 decimal places
•
complex
– Complex numbers
are written in the form 𝑥 + 𝑦𝑗 , where x is the real part and y is the imaginary
part. (Example : 5 + 10𝑗 ).
•
bool
- boolean values
True and False.
Boolean
The
python data type bool is used to store two values i.e True and False.
Bool
is used to test whether the result of an expression is true or false. The
Boolean values, True and False are treated as reserved words.
Syntax
To
check the boolean value of an expression or a variable, pass it as a parameter
to the bool function:
print(bool(expression))
or
print(expression)
Example
Python code to
illustrate all data types
When we run the above code, it produces the output as
follows.
Strings
A
string consists of a sequence of one or more characters, which can include
letters, numbers, and other types of characters.
A
string can also contain spaces. You can use single quotes or double quotes to
represent strings and it is also called a string literal.
Multiline
strings can be denoted using triple quotes, ‘ ‘ ‘ or “ “ “.
The
string data type in Python is called as 'str '.
Tips!
•
When
a string contains a single quotation as a character in it, then enclose it with
double quotes.
(Example - " It is a ‘python’
class")
•
When
a string contains double quotation as a character in it, then enclose it with
single quotes.
(Example
- 'we have python class on”mon,Tue,wed” in a week')
•
When
a string contains both double quotation and a single quotation as characters in
it, then enclose it with triple quotes.
(Example - '''It's so
"hot" outside''')
When we run the above code, it produces the output as
follows.
None
None
is another special data type in Python. None is frequently used to represent
the absence of a value . In Python, 'None' is the object which represents
nothing. When we want a value to hold nothing, we do assign it with value
'None'.
Indentation
•
Indentation
in Python is used to create a group of statements. Many popular languages such
as C, C++ and Java uses braces ({ }) to define a block of code and is for
readability, Python use indentation.
•
The
leading whitespaces (space and tabs) at the start of a line is used to
determine the indentation level of the line. You have to increase the indent
level to group the statements for that code block.
•
Python
uses indentation to indicate a block of code.
Statements and Expressions
A
statement is an instruction that the Python interpreter can execute. Python
program consists of a sequence of statements
For
example, z = 1 is an assignment statement.
Expression
is an arrangement of values and operators which are evaluated to make a new
value. Expressions are statements as well.
For example,
>>> 8 + 2
10
Comments
•
Comments
are an important part of any program. A comment is a text that describes what
the program or a particular part of the program is trying to do and is ignored
by the Python interpreter.
•
Comments
are used to help you and other programmers understand, maintain, and debug the
program.
Python uses two types of comments:
•
single-line
comment
•
multiline
comments
Single Line Comment : In Python, use the hash (#) symbol
to start writing a comment. Hash (#) symbol makes all text following it on the
same line into a comment.
For example,
#This is single line Python comment
Multi Line Comment : If the comment extends multiple
lines, then one way of commenting those lines is to use hash (#) symbol at the
beginning of each line.
For example,
# This is
# multiline comments
# in Python
Another
way of doing this is to use triple quotes, either ''' or """.
These triple quotes are generally used for multiline strings.
However,
they can be used as a multiline comment as well.
For
example,
'''This is
multiline comment
in Python using triple quotes'''
Python Typecasting / Type Conversions
•
In
all programming languages, frequently, we need to convert the values from one
data type to another data type.
•
The
process of converting a value from one data type to another data type is called
Typecasting or simply Casting.
•
In
Python, the typecasting is performed using built-in functions. As all the data
types in Python are organized using classes, the type casting is performed
using constructor functions.
The
following are the constructor functions used to perform typecasting.
Example - int( ) Typecasting
When we run the above code, it produces the output as
follows
Example - float( ) Typecasting
When we run the above code, it produces the output as
follows
Example - str( ) Typecasting
When we run the above code, it produces the output as
follows.
Points to be Remembered
•
In
Python, when an integer value is cast to float value, then it is appended with
the fractional part containing zeros (0).
•
In
Python, when a float value s cast to an integer it rounding down to the
previous whole number.
Operators
In
Python, an operator is a symbol used to perform arithmetical and logical
operations. In other words, an operator can be defined as a symbol used to
manipulate the value of an operand. Here, an operand is a value or variable on
which the operator performs its task. For example, '+' is a symbol used to
perform mathematical addition operation.
Consider the expression a = 10 + 30 .
Here,
variable 'a', values '10' and '30' are known as Operands and the symbols '='
and '+' are known as Operators.
Types of Operators in Python
In
Python, there is a rich set of operators, and they are classified as follows.
• Arithmetic Operators ( +, -, *, /, %, **,
// )
• Assignment Operators ( =, +=, -=, *=, /=,
%=, **=, //= )
• Comparison Operators ( <, <=, >,
>=, ==, != )
• Logical Operators ( and, or, not )
• Identity Operators ( is, is not )
• Membership Operators ( in, not in )
• Bitwise Operators ( &, |, ^, ~,
<<, >> )
Arithmetic Operators in Python
In
Python, the arithmetic operators are the operators used to perform a basic
arithmetic operation between two variables or two values.
Arithmetic
operators are used to execute arithmetic operations such as addition,
subtraction, division, multiplication etc.
The
following table presents the list of arithmetic operations in Python along with
their description.
To
understand the example let's consider two variables a with value 10 and b with
value 3.
Example - Arithmetic Operators in Python
m = 10
n = 3
print("Addition
of",m,"and",n,"is",m+n)
print("Subtraction
of",m,"and",n,"is",m-n) print("Multiplication
of",m,"and",n,"is",m*n) print("Division
of",m,"and",n,"is",m/n)
print("Modulo
of",m,"and",n,"is",m%n)
print("Exponent
of",m,"and",n,"is",m**n) print("Floor division
of",m,"and",n,"is",m//n)
Assignment Operators in Python
Here are the Assignment Operators in Python with
examples
Example - Assignment Operators
Comparison Operators in Python
Example - Comparison Operators in Python
Logical Operators
Truth Table for Logical Operators
Flow Chart for Logical AND operator in Python
Logical OR operator in Python
Logical NOT operator in Python
Example :
#Program for Logical Operators
a=10
b=3 c=20
print("10<3 and 10>20
is ", a < b and a > c) print("10<3 and 10>20 is ", a
< b or a > c) print("not 10>3 is ",not a > b)
When we run the above code, it produces the output as
follows.
Identity Operators
In
Python, identity operators are used to comparing the memory locations of two
objects or variables.
There
are two identity operators in Python. The following table presents the list of
identity operations in Python along with their description.
To
understand the example let's consider two variables a with value 10 and b with
value 3.
Example - Identity Operators in Python
a=10
b=3
print(f"{a}
is {b} : {a is b}")
print(f"{a}
is not {b} : {a is not b}")
When we run the above code, it produces the output as
follows.
Membership Operators
In
Python, the membership operators are used to test whether a value is present in
a sequence. Here the sequence may be String, List, or Tuple.
There
are two membership operators in Python. The following table presents the list
of membership operations in Python along with their description.
Example - Membership Operators in Python
When we run the above code, it produces the output as
follows.
Bitwise Operators in Python
In
Python, the bitwise operators are used to performs bit by bit operation. There
are six bitwise operators in Python.
The
following table presents the list of bitwise operations in Python along with
their description.
Example - bitwise Operators in Python
When we run the above code, it produces the output as
follows.
Precedence and Associativity
•
Operator
precedence determines the way in which operators are parsed with respect to
each other.
•
Operators
with higher precedence become the operands of operators with lower precedence.
Associativity determines the way in which operators of the same precedence are
parsed. Almost all the operators have left-to-right associativity.
•
Operator
precedence is listed in TABLE 2.9 starting with the highest precedence to
lowest precedence
Dynamic and Strongly Typed Language
•
Python
is a dynamic language as the type of the variable is determined during run-time
by the interpreter.
•
Python
is also a strongly typed language as the interpreter keeps track of all the
variables types. In a strongly typed language, you are simply not allowed to do
anything that’s incompatible with the type of data you are working with.
For
Example.
Chapter 2
Control Flow Statements
In
Python, the default execution flow of a program is a sequential order. But the
sequential order of execution flow may not be suitable for all situations.
Sometimes,
we may want to jump from line to another line, we may want to skip a part of
the program, or sometimes we may want to execute a part of the program again
and again.
To
solve this problem, Python provides control statements.
In
Python, the control statements are the statements which will tell us that in
which order the instructions are getting executed.
The
control statements are used to control the order of execution according to our
requirements. Python provides several control statements, and they are
classified as follows.
Sequential Control Flow Statements:
This
refers to the line by line execution, in which the statements are executed
sequentially, in the same order in which they appear in the program.
Decision Control Flow Statements / Selection
Control Statements
• In Python, the selection statements are
also known as decision making statements or branching statements.
• The selection statements are used to
select a part of the program to be executed based on a condition.
• Python provides the following selection
statements.
•
if
statement
•
if…else
statement
•
if…elif…else
statement
•
nested
if statement
Loop Control Flow Statements:
• The iterative statements are also known as
looping statements or repetitive statements.
• The iterative statements are used to
execute a part of the program repeatedly as long as the given condition is
True.
• Using iterative statements reduces the
size of the code, reduces the code complexity, makes it more efficient, and
increases the execution speed.
• Python provides the following iterative
statements.
•
while
statement
•
for
statement
if Decision Control Flow statement
If the
Boolean expression (Condition) evaluates to True then statements in the if
block will be executed; otherwise the result is False then none of the
statements are executed.
The syntax for if statement is,
The execution flow of if statement is as follows.
Syntax
if
condition:
Statement_1
Statement_2
Statement_3
...
• The if decision control flow statement
starts with if keyword and ends with a colon.
• The expression in an if statement should
be a Boolean expression.
• In Python, the if block statements are
determined through indentation.
Example 1: Program Reads a Number and Prints Whether eligible
to Vote
When we run the above code, it produces the output as
follows.
Example 2: Program to Check Whether a Number is Divisible by 5
When we run the above code, it produces the output as
follows
In the
above execution, the number 20 is divisible by 5. So, the condition becomes
True and the condition is evaluated to True. Then the if statement executes its
block of statements.
In the
above execution, the number 13 is not divisible by 5. So, the condition becomes
False and the condition is evaluated to False. Then the if statement ignores
execution of its block of statements. So it will print ‘Out of if statement’
if..else Decision Control Flow statement
• In Python, we use the if-else statement to
test a condition and pick the execution of a block of statements out of two
blocks based on that condition result.
• The if-else statement checks the given
condition then decides which block of statements to be executed based on the
condition result.
• If the condition is True, then the true
block of statements is executed and if it is False, then the false block of
statements is executed.
• The execution flow of if-else statement is
as follows.
Syntax
if
condition:
Statement_1
Statement_2 Statement_3
else:
Statement_4
Statement_5
Example
1: Program to
Find If a Given Number Is Odd or Even
The
following is the output that the code above generates when it is run.
The
following is the output that the code above generates when it is run.
The
following is the output that the code above generates when it is run.
The
following is the output that the code above generates when it is run.
The
following is the output that the code above generates when it is run.
The
following is the output that the code above generates when it is run.
Loop Control Flow Statements
While
loop
For
loop
The Countinue And Break Statement
Continue statement
The
continue statement is used to move the program execution control to the
beginning of the looping statement.
When
the continue statement is encountered in a looping statement, the execution control
skips the rest of the statements in the looping block and directly jumps to the
beginning of the loop. The continue statement can be used with looping
statements like while, do-while and for.
Example 1: Program on continue using for loop
for i in range(10): if (i == 5):
continue print(i)
When we run the above code, it produces the output as
follows
Example 2: Program on continue using for loop
When we run the above code, it produces the output as
follows
Exception Handling
Error
in Python can be of two types i.e. Syntax errors and Exceptions. Errors are
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 change
the normal flow of the program.
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.
• NameError: This exception is raised when a
variable or function name is not found in the current scope.
• IndexError: This exception is raised
when an index is out of range for a list, tuple, or other sequence types.
• KeyError: This exception is raised when a
key is not found in a dictionary.
• ValueError: This exception is raised when a
function or method is called with an invalid argument or input, such as trying
to convert a string to an integer when the string does not represent a valid
integer.
• AttributeError: This exception is raised when an
attribute or method is not found on an object, such as trying to access a
non-existent attribute of a class instance.
• IOError: This exception is raised when an I/O
operation, such as reading or writing a file, fails due to an input/output
error.
• ZeroDivisionError: This exception is raised when an
attempt is made to divide a number by zero.
• ImportError: This exception is raised when an
import statement fails to find or load a module.
These
are just a few examples of the many types of exceptions that can occur in
Python. It’s important to handle exceptions properly in your code using
try-except blocks or other error-handling techniques, in order to gracefully
handle errors and prevent the program from crashing.
Difference between Syntax Error and Exceptions
Syntax
Error: As the name suggests this error is caused by the wrong syntax in the
code. It leads to the termination of the program.
Example:
There
is a syntax error in the code . The ‘if' statement should be followed by a
colon (:), and the ‘print' statement should be indented to be inside the ‘if'
block.
amount
= 10000
if(amount
> 2999)
print("You
are eligible to purchase Dsa Self Paced")
Exceptions: Exceptions are raised when the
program is syntactically correct, but the code results in an error. This error
does not stop the execution of the program, however, it changes the normal flow
of the program.
Example:
Here
in this code a s we are dividing the ‘marks’ by zero so a error will occur
known as ‘ZeroDivisionError’ Try and Except Statement – Catching Exceptions Try
and except statements are used to catch and handle exceptions in Python.
Statements that can raise exceptions are kept inside the try clause and the
statements that handle the exception are written inside except clause.
Example: ZeroDivisionError
When we run the above code it gives output as follows
Example 2: TypeError
When we run the
above code we will get following result
Chapter 3
Functions
Functions
A
function is a block of statements under a name that can execute
independently.
The functions are used to perform a specific task. Functions allow us to divide
a larger problem into smaller subparts to solve efficiently, to implement the
code reusability concept and makes the code easier to read and understand.
The
Python provides several functions and methods to write code very easily, and
these functions and methods are called built-in function and methods. Python
allows us to create our functions and methods, and these are called
user-defined functions and methods.
Built-In Functions
The
Python interpreter has a number of functions that are built into it and are
always available
Table 1. Commonly used built in function
Commonly Used Modules
• Python standard library also consists of a
number of modules. While a function is a grouping of instructions, a module is
a grouping of functions.
• A module is created as a python (.py) file
containing a collection of function definitions.
• To use a module, we need to import the
module. Once we import a module, we can directly use all the functions of that
module.
The syntax of import statement is as follows:
import
modulename1 [,modulename2, …]
This
gives us access to all the functions in the module(s). To call a function of a
module, the function name should be preceded with the name of the module with a
dot(.) as a separator.
The syntax is as shown below:
modulename.functionname()
Built-in Modules
Python
library has many built-in modules that are really handy to programmers. Some
commonly used modules and the frequently used functions that are found in those
modules:
• math
• random
• statistics
math module:
It
contains different types of mathematical functions. In order to use the math
module we need to import it using the following statement: import math
Function Syntax |
Returns |
Example Output |
math.ceil(x) |
ceiling value
of x |
>>> math.ceil(-9.7) -9 >>> math.ceil (9.7) 10 >>> math.ceil(9) 9 |
math.floor(x) |
floor value
of x |
>>> math.floor(-4.5) -5 >>>
math.floor(4.5) 4 >>> math.floor(4) 4 |
math.fabs(x) |
absolute value
of x |
>>>
math.fabs(6.7) 6.7 >>>
math.fabs(-6.7) 6.7 >>> math.fabs(-4) 4.0 |
math.factorial(x) |
factorial of x |
>>> math.factorial(5) 120 |
math.fmod(x,y) |
x % y
with sign of x |
>>>math.fmod(4,4.9) 4.0 >>>math.fmod(4.9,4.9) 0.0 >>>math.fmod(-4.9,2.5) -2.4 >>>math.fmod(4.9,-4.9) 0.0 |
math.gcd(x,y) |
gcd (greatest common divisor) of x and y |
>>>
math.gcd(10,2) 2 |
math.pow(x,y) |
𝑥𝑦 (x raised
to the power
y) |
>>>
math.pow(3,2) 9.0 >>>math.pow(4,2.5) |
|
|
32.0 >>>math.pow(6.5,2) 42.25 >>>math.pow(5.5,3.2) 233.97 |
math.sqrt(x) |
square root
of x |
>>> math.sqrt(144) 12.0 >>> math.sqrt(.64) 0.8 |
math.sin(x) |
sine of x in radians |
>>>
math.sin(0) 0 >>> math.sin(6) -0.279 |
Random module:
This
module contains functions that are used for generating random numbers. In order
to use the random module we need to import it using the following statement:
import random
Commonly
used functions in random module
Statistics module:
This
module provides functions for calculating statistics of numeric (Real-valued)
data. In order to use the statistics module we need to import it using the
following statement:
import statistics
Commonly used functions in statistics module
• In order to get a list of modules
available in Python, we can use the following statement:
>>>
help("module")
• To view the content of a module say math,
type the following:
>>>
help("math")
From Statement
Instead
of loading all the functions into memory by importing a module, from statement
can be used to access only the required functions from a module. It loads only
the specified function(s) instead of all the functions in a module.
Syntax:
>>>
from modulename import functionname
Example
Function Definition and Calling the Function /
User-defined Functions
Defining a function in Python
The
Python programming language provides the keyword def to create functions. The
general syntax to create functions is as follows.
Syntax
def
function_name(list_of_parameters):
statement_1
statement_2
statement_3
...
•
The
list of parameters in a function definition needs to be separated with a comma.
•
In
Python, every function returns a None value by default. However, we can return
our value.
•
Every
function requires a function call to execute its code.
Function Prototypes:
Based
on the data flow between the calling function and called function, the
functions are classified as follows...
• Function without Parameters and without
Return value
• Function with Parameters and without
Return value
• Function without Parameters and with
Return value
• Function with Parameters and with Return
value
Function without Parameters and without Return value
•
In
this type of functions there is no data transfer between calling function and
called function.
•
Simply
the execution control jumps from calling-function to called function and
executes called function, and finally comes back to the calling function.
For example, consider the following program..
Function with Parameters and without Return value
•
In
this type of functions there is data transfer from calling-function to called
function (parameters) but there is no data transfer from called function to
calling-function (return value).
•
The
execution control jumps from calling-function to called function along with the
parameters and executes called function, and finally comes back to the calling
function.
For example, consider the following program...
Function without Parameters and with Return value
•
In
this type of functions there is no data transfer from calling-function to
called- function (parameters) but there is data transfer from called function
to calling- function (return value).
•
The
execution control jumps from calling-function to called function and executes
called function, and finally comes back to the calling function along with a
return value.
For example, consider the following program...
Function with Parameters and with Return value
•
In
this type of functions there is data transfer from calling-function to called-
function (parameters) and also from called function to calling-function (return
value).
•
The
execution control jumps from calling-function to called function along with
parameters and executes called function, and finally comes back to the calling
function along with a return value
Calling a function in Python
In
Python, we use the name of the function to make a function call. If the
function requires any parameters, we need to pass them while calling it.
The
general syntax for calling a function is as follows.
Syntax
function_name(parameter_1,
parameter_2,...)
Program to demonstrate a Function without arguments
When we run the above example code, it produces the
following output.
Write a user defined function to add 2 numbers and display
their sum.
When we run the above example code, it produces the
following output.
WAP
using a user defined function that displays sum of first n natural numbers,
where n is passed as an argument.
Write
a program using a user defined function calcFact() to calculate and display the
factorial of a number num passed as an argument
def
fact(num):
fact =
1
for i
in range(num,0,-1): fact = fact * i
print("Factorial
of",num,"is",fact)
num =
int(input("Enter the number: ")) fact(num)
When we run the above example code, it produces the
following output.
The return statement and void Function
In
Python, it is possible to compose a function without a return statement.
Functions like this are called void, and they return None
A
function may or may not return a value when called. The return statement
returns the values from the function.
A
return statement consists of the return keyword followed by an optional return
value.
If an
expression list is present, it is evaluated, else None is substituted
def
add(a, b): result = a + b return result
print(add(2,
2))
Output : 4
Armstrong
Number : The sum
of cubes of each digit is equal to the number itself.
For example:
153 =
1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number.
Program to Check If a 3 Digit Number Is Armstrong
Number or Not
num =
int(input("Enter a number: ")) sum = 0
temp =
num while temp > 0:
digit
= temp % 10 sum += digit ** 3 temp = temp//10
if num
== sum:
print(num,"is
an Armstrong number") else:
print(num,"is
not an Armstrong number")
When
we run the above example code, it produces the following output
Enter
a number: 153
153 is
an Armstrong number
Enter a number: 407
407 is an Armstrong number
Scope and Lifetime of Variables
The
part of the program where a variable is accessible can be defined as the scope
of that variable. A variable can have one of the following two scopes:
A
variable that has global scope is known as a global variable and a variable
that has a local scope is known as a local variable.
Figure 7.6: scope of a variable
Global Variable
A
variable that is defined outside any function or any block is known as a global
variable. It can be accessed in any functions defined onwards. Any change made
to the global variable will impact all the functions in the program where that
variable can be accessed.
Local Variable
A
variable that is defined inside any function or a block is known as a local
variable. It can be accessed only in the function or a block where it is
defined. It exists only till the function executes.
Program to Demonstrate the Scope of Variables
num1 = 5 #globalvariable def myfunc():
#
variable num1 outside the function print("Accessing num =",num1)
num =
10 #localvariable print("num reassigned =", num)
myfunc()
print("Accessing
num outside myfunc",num1)
Program to Demonstrate the Scope of Variables
num1 =
5 #globalvariable def myfunc():
#
variable num1 outside the function print("Accessing num =",num1)
num =
10 #localvariable print("num reassigned =", num)
myfunc()
print("Accessing
num outside myfunc",num1)
When we run the above example code, it produces the
following output
Calculate and Add the Surface Area of Two Cubes. Use
Nested Functions
def
add_cubes(a, b):
def
cube_surfacearea(x): return 6 * pow(x, 2)
return
cube_surfacearea(a) + cube_surfacearea(b)
def
main():
result=add_cubes(2,
3)
print("The
surface area after adding two Cubes is",result)
if
name == " main ": main()
Calculate
and Add the Surface Area of Two Cubes. Use Nested Functions
def
add_cubes(a, b):
def
cube_surfacearea(x): return 6 * pow(x, 2)
return
cube_surfacearea(a) + cube_surfacearea(b)
def
main():
result=add_cubes(2,
3)
print("The
surface area after adding two Cubes is",result)
if
name == " _main ": main()
When
we run the above example code, it produces the following output
Default Parameters / Default Arguments
Python
allows assigning a default value to the parameter. If the function is called
with value then, the function executed with provided value, otherwise, it
executed with the default value given in the function definition.
def
addition(num1, num2= 9, num3= 5): return num1 + num2 + num3
result
= addition(10, 20, 30) print("sum=",result)
result
= addition(10, 20)
print("sum=",result)
result
= addition(10)
print("sum=",result)
When we run the above example code, it produces the
following output
Keyword Arguments
The
keyword argument is an argument passed as a value along with the parameter name
(kwarg = value).
When
keyword arguments are used, we may ignore the order of arguments. We may pass
the arguments in any order because the Python interpreter uses the keyword
provided to match with the respective parameter.
def
student_info(rollNo, name, group): print(f'Roll Number : {rollNo}')
print(f'Student Name : {name}') print(f'Group : {group}')
student_info(name='Raju',
rollNo=111, group='MSDs')
*args and **kwargs
In
Python, we can pass a variable number of arguments to a function using special
symbols. There are two special symbols:
1. *args (Non Keyword Arguments)
2. **kwargs (Keyword Arguments)
We use
*args and **kwargs as an argument when we are unsure about the number of
arguments to pass in the functions.
Python
has *args which allow us to pass the variable number of non keyword arguments
to function. In the function, we should use an asterisk (*) before the
parameter name to pass a variable number of arguments.
Example program on *args
def largest(*numbers): return max(numbers)
def
largest(*numbers): return max(numbers)
print(largest(20,
35))
print(largest(2,
5, 3))
print(largest(10,
40, 80, 50))
print(largest(16,
3, 9, 12, 44, 40))
When
we run the above example code, it produces the following output
Python
has **kwargs which allows us to pass the variable length of keyword arguments
to the function. In the function, we use the double-asterisk (**) before the
parameter name to denote this type of argument.
Example program on **kwargs
def
Student_info(**kwargs): print(kwargs)
Student_info(name="Raju",rollno=111,group="MSDs")
When
we run the above example code, it produces the following output
Command Line Arguments
A
Python program can accept any number of parameters from the command line.
Python sys module stores the command line arguments into a list,
we can access
it using sys.argv
import
sys
print("Number
of arguments:",len(sys.argv))
print('The
command line arguments are:') for i in sys.argv:
print(i)
Save above code Filename.py (Ex:- Command.py)
Chapter 4
Strings
A
string is a sequence of characters which is enclosed in quotes. In Python, A
string can be created by enclosing one or more characters in single, double or
triple quote.. The Python treats both single quote and double quote as same.
For example, the strings 'Hi Friend' and "Hi
Friend" both are same.
Creating and Storing Strings
In
Python, creating string variables is very simple as we need to assign a string
value to a variable.
str1 =
'Hello World!'
str2 =
"Hello World!"
str3 =
"""Hello World!
welcome to the world of
Python"""
str4 =
'''Hello World!
welcome to the world of Python''
Accessing Characters in a String
• Each
individual character in a string can be accessed using a technique called
indexing.
• The
index specifies the character to be accessed in the string and is written in
square brackets ([ ]).
• The
index of the first character (from left) in the string is 0 and the last
character is n-1 where n is the length of the string.
• If
we give index value out of this range then we get an IndexError. The index must
be an integer (positive, zero or negative).
• The
index can also be an expression including variables and operators but the
expression must evaluate to an integer.
• Python
allows an index value to be negative also. Negative indices are used when we want to access the
characters of the string from right to left.
• Starting
from right hand side, the first character has the index as -1 and the last
character has the index –n where n is the length of the string.
Table 8.1: indexing of characters in string ‘Hello Word’
String is Immutable
A
string is an immutable data type. It means that the contents of the string
cannot be changed after it has been created. An attempt to do this would lead
to an error.
STRING OPERATIONS
Python
allows certain operations on string data type, such as concatenation,
repetition, membership and slicing.
Concatenation
To
concatenate means to join. Python allows us to join two strings using
concatenation operator plus which is denoted by symbol +.
Repetition
Python
allows us to repeat the given string using repetition operator which is denoted
by symbol *
Note:
str1 still remains the same after the use of repetition operator
Membership
Python
has two membership operators 'in' and 'not in'. The 'in' operator takes two
strings and returns True if the first string appears as a substring in the
second string, otherwise it returns False.
The
'not in' operator also takes two strings and returns True if the first string
does not appear as a substring in the second string, otherwise returns False.
Slicing
In
Python, to access some part of a string or substring, we use a method called
slicing. This can be done by specifying an index range.
To
access substring from a string, we use string variable name followed by square
brackets with starting index , ending index and Step of the required substring.
#first index > second index results in an #empty
'' string
If the
first index is not mentioned, the slice starts from index and If the second
index is not mentioned, the slicing is done till the length of the string.
The
slice operation can also take a third index that specifies the ‘step size’. For
example, str1[n:m:k], means every kth character has to be extracted from the
string str1 starting from n and ending at m-1. By default, the step size is
one.
Negative
indexes can also be used for slicing. If we ignore both the indexes and give
step size as -1, str1 string is obtained in the reverse order.
Joining
The string,
tuple), separated by a string separator.
Traversing A String
We
can access each character of a string or traverse a string using for loop and
String Traversal Using for Loop:
String Traversal Using while Loop:
String Methods and Built-In Functions
Method |
Description |
Example |
len() |
Returns the
length of the
given string |
>>> str1
= 'Hello World!' >>> len(str1) 12 |
title() |
Returns the string with first letter
of every word
in the string
in uppercase and rest in lowercase |
>>> str1
= 'hello WORLD!' >>> str1.title() 'Hello World!' |
lower() |
Returns the string with
all Uppercase letters converted to lowercase |
>>> str1
= 'hello WORLD!' >>>
str1.lower() 'hello world!' |
upper() |
Returns the string with
all lowercase letters converted to uppercase |
>>> str1
= 'hello WORLD!' >>>
str1.upper() 'HELLO WORLD!' |
count(str, start,
end) |
Returns number of times substring str occurs in the given string.
If we do not give
start index and end indexthen |
>>> str1
= 'Hello World! Hello Hello' >>>str1.count('Hello',12,25 )2 |
|
searching starts from index
0 and ends at length of the string |
>>>
str1.count('Hello') 3 |
find (str,start, end) |
Returns the first occurrence of index of
substring str occurring in the
given string. If we do not give start
and end then searching starts from index
0 and ends at length
of the string. If the
substring is not present in the
given string, then the function returns -1 |
>>> str1 = 'Hello World! Hello Hello' >>> str1.find('Hello',10,20) 13 >>> str1.find('Hello',15,25) 19 >>>
str1.find('Hello')0> >> str1.find('Hee) -1 |
Index (str, start, end) |
Same as find() but
raises an exception if the substring is not present in the given
string |
>>> str1 = 'Hello World! Hello Hello' >>> str1.index('Hello') 0 >>>
str1.index('Hee') ValueError: substring not found |
endswith() |
Returns True if the
given string ends with
the supplied substring otherwise returns
False |
>>> str1 = 'Hello World!' >>>str1.endswith('World!') True >>> str1.endswith('!') True >>> str1.endswith('lde') False |
startswith() |
Returns True if the
given string starts with
the supplied substring otherwise returns
False |
>>> str1 = 'Hello World!' >>>
str1.startswith('He') True >>> str1.startswith('Hee') False |
isalnum() |
Returns True if
characters of the given string are
either alphabets or numeric. If whitespace or special symbols are part
of the given string or the
string is empty it returns
False |
>>> str1 = 'HelloWorld' >>>
str1.isalnum() True >>> str1 = 'HelloWorld2' >>>
str1.isalnum() True >>> str1 = 'HelloWorld!!' >>> str1.isalnum() False |
islower() |
Returns True if the
string is non-empty and has all lowercase alphabets, or has at least one character
as lowercase alphabet and rest are non-alphabet characters |
>>> str1 = 'hello world!' >>>
str1.islower() True >>> str1 = 'hello 1234' >>>
str1.islower() True >>> str1 = 'hello ??' >>> str1.islower() True |
|
|
>>> str1
= 'Hello World!
Hello' >>> str1.replace('Hello','Bye') 'Bye World! Bye' |
join() |
Returns a string in which the characters
in the string have been joined by a separator |
>>> str1 = ('HelloWorld!') >>> str2 = '-' #separator >>> str2.join(str1) 'H-e-l-l-o-W-o-r-l-d-!' |
partition() |
Partitions the given
string at the first occurrence of the substring (separator) and returns the string partitioned into three parts. 1. Substring before
the separator 2. Separator 3. Substring after
the separator If the separator is not found
in the string, it returns the whole string itself and two empty strings |
>>> str1 =
'India is a Great Country' >>> str1.partition('is') ('India ', 'is', ' a Great
Country') >>> str1.partition(‘are’) (‘India is a Great
Country’,’ ‘,’ ‘) |
capitalize() |
Returns a copy of the string
with its first
character capitalized and the rest lowercased |
>>>str='hello world!' >>>str.capitalize() 'Hello world!' |
sasefold() |
returns a string where
all the characters are in lower case. It is similar to the lower() method, but the
casefold() method converts more characters into
lower case. |
>>>str="HELLO world" >>>str.casefold() 'hello world' |
Example Program on String Methods
str1 =
‘ hello World! ‘
print(“String
in Uppercase :”, str1.upper())
print(“String in Lower case :”, str1.lower())
print(“Capitalized String :”,
str1.capitalize())
print(“String
with first letter :”,str1.title())
print(“String alphanumeric :”,str1.isalnum())
print(“String in lowercase :“,str1.islower())
print(“String in uppercase :“,str1.isupper())
print(“Swapcase :“,str1.swapcase())
print(“Right
Strip of String :“,str1.rstrip())
print(“Left
Strip of String :“,str1.lstrip())
print(“Right & Left Strip of String
:“,str1.strip())
Output :
String
in Uppercase : HELLO WORLD!
String
in Lower case : hello world!
Capitalized
String : hello world!
String
with first letter : Hello World!
String
alphanumeric : False
String
in lowercase : False
String
in uppercase : False
Swapcase : HELLO wORLD!
Right
Strip of String : hello World!
Left Strip of String : hello World!
Right
& Left Strip of String : hello World!
Formatting String
The format strings will contain
the curly braces { } and
the format() method
will use those curly braces
{ } as
placeholders to replace with the content of the parameters.
Chapter 5
Lists
Introduction to list
Example :
Accessing elements in a list
Lists are mutable
Lists operation
Cancatenation:
Repetition
Membership:
Like
strings, the membership operators in checks if the element is present in the
list and returns True, else returns False
The
not in operator returns True if the element is not present in the list, else it
returns False.
Slicing:
Traversing a list:
List methods and built – in functions
Nested list
Copying lists or cloning lists
Aliasing
Lists as argument to a Function / Lists parameters
Tuples
Tuple is an immutable
Tuple operations
Tuple assignment
Tuple as
return value
Dictionaries:
Accessing Items in a Dictionary
dict2 =
{'Santhosh':95,'Avanthi':89,'College':92}
print(dict2['Avanthi'])
print(dict2['Santhosh'])
Dictionary Methods and Built-In Functions
Python provides many functions to work on dictionaries.
Built-in
functions and methods for dictionary
Method |
Description |
Example |
len() |
Returns the length
or number of key: value pairs
of the dictionary passed as the argument |
>>> dict1 = {'Santhosh':95,'Avanthi':89,'C ollege':92} >>> len(dict1) 3 |
dict() |
Creates a dictionary from
a sequence of key- value pairs |
>>> pair1 = [('Mohan',95),('Ram',89), ('Suhel',92),('Sangeeta',85)] >>> dict1 =
dict(pair1) >>> dict1 [('Mohan',95),('Ram',89), ('Suhel',92),('Sangeeta',85)] |
keys() |
Returns a list of keys in the dictionary |
>>>dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85} >>>
dict1.keys() dict_keys(['Mohan', 'Ram', 'Suhel','Sangeeta']) |
values() |
Returns a list of values
in the dictionary |
>>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> dict1.values() dict_values([95, 89, 92, 85]) |
items() |
Returns a list of
tuples(key – value) pair |
>>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> dict1.items() dict_items([( 'Mohan', 95), ('Ram',89),
('Suhel', 92), ('Sangeeta', 85)]) |
get() |
Returns the value
corresponding to the key passed as the Argument If the key is not present
in the dictionary it will return
None |
>>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> dict1.get('Sangeeta') 85 >>>
dict1.get('Sohan') >>> |
update() |
appends the key- value pair of the dictionary
passed as the argument to the key-value pair of the given dictionary |
>>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> dict2 = {'Sohan':79,'Geeta':89} >>> dict1.update(dict2) >>> dict1 {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85, 'Sohan': 79, 'Geeta':89} >>> dict2 {'Sohan': 79, 'Geeta':
89} |
del() |
Deletes the item
with the given
key To delete the dictionary from the memory
we write: del Dict_name |
>>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92,
'Sangeeta':85} >>> del dict1['Ram'] >>> dict1 {'Mohan':95,'Suhel':92, 'Sangeeta': 85} >>> del dict1 ['Mohan'] >>> dict1 {'Suhel': 92, 'Sangeeta': 85} >>> del dict1 >>> dict1 NameError: name
'dict1' is not defined |
clear() |
Deletes or clear all the items of the dictionary |
>>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> dict1.clear() >>> dict1 { } |
Advanced List Processing
Selection sort
Insertion sort
Merge sort
Merge
sort is one of the most important sorting algorithms based on the divide and
conquer technique.
Histogram
def
histogram(items): for n in items:
output=''
num=n
while
(num>0): output += '*' num=num-1 print(output)
histogram([2,3,5,6,4])
Output :
**
***
*****
******
****
Chapter 6
Files and Exception
Introduction to Files
• File is a collection of data that stored
on secondary memory like had disk of a computer.
• File handling in Python involves the
reading and writing process and many other file handling options.
• The built-in Python methods can manage two
file types,
text file and binary file.
• The Python programming language provides
built-in functions to perform operations on files.
File Operations in Python
The
following are the operations performed on files in Python programming
language...
•
Creating
(or) Opening a file
•
Reading
data from a file
•
Writing
data into a file
•
Closing
a file
Creating (or) Opening a file
• In Python, we use the built-in function
open( ). This function requires two parameters, the first one is a file name
with extension, and the second parameter is the mode of opening.
• The built-in function open( ) returns a
file object. We use the following syntax to open a file.
Syntax
file =
open("file_name.extension", "mode")
There are four different modes you can open a file
to:
1. “r” = If you want to read from a file.
2. “w” = If you want to write to a file erasing
completely previous data.
3. “a” = If you want to append to previously
written file.
4. “x” = If you want just to create a file.
Additional used modes to specify the type of file is:
1. “t” = Text file, Default value.
2. “b” = binary file. For eg. Images.
For
example : fp = open("my_file.txt", "w")
This
will open a file named my_file.txt in text format.
Writing data into a file
• To perform write operation into a file,
the file must be opened in either 'w' mode (WRITE) or 'a' mode (APPEND). The
Python provides a built-in method write( ) to write into the file..
• The 'w' mode overwrites any existing
content from the current position of the cursor. If the specified file does not
exist, it creates a new file and inserts from the beginning.
• The 'a' mode insert the data next from the
last character in the file. If the file does not exist, it creates a new file
and inserts from the beginning.
Reading data from a file
• First of all, to read data from a file,
you need to open it in reading mode. You can then call any of the Python
methods for reading from a file.
Three different methods have provided to read file
data.
• readline():The readline( ) method of file
object reads all the characters from the current cursor position to till the
end of the line. But, optionally we can also specify the number of characters
to be read.
• read():The read() method of file object
reads whole data from the open file. But, optionally we can also specify the
number of characters to be read.
• readlines():The readline( ) method of file
object reads all lines until file end and returns an object list.
Closing a file
The
Python has a built-in method close( ) of the file object to close the file.
file_object.close()
Example Program on Write and read metho
fPtr =
open('Sample.txt', 'w')
fPtr.write("Python
is an interpreted programming language ")
fPtr.close()
fPtr =
open('Sample.txt', 'r') print('The content of Sample.txt is: ')
print(fPtr.read())
fPtr.close()
Example Program on writelines, readline and readlines
Methods:
fptr=open("D:Sample.txt","w")
fptr.writelines("Hello world
\n Welcome to Technology")
fptr.close()
fPtr =
open('D:\Sample.txt', 'r')
print('The
content of Sample.txt : ')
print(fPtr.readline())
fPtr.close()
fPtr =
open('D:\Sample.txt', "a")
fPtr.writelines("\n
Welcome to Python")
fptr.close()
fPtr =
open('D:\Sample.txt', 'r')
print('The
updated content of Sample.txt : ')
print(fPtr.readlines())
fPtr.close()
Output :
Write
a Python Program to Count the Number of Words in a Text File
fPtr =
open('Sample.txt', 'w')
fPtr.write("Python
is an interpreted programming language ")
fPtr.close()
fPtr =
open('Sample.txt', 'r')
str =
fPtr.read()
l =
str.split()
count_words
= 0
for i
in l:
count_words = count_words + 1
print("The
no.of words in file is ",count_words)
fPtr.close()
Output :
The
no.of words in file is 6
Write a Python Program to Count the Number of Words
in a Text File
The
shutil module provides some easy to use methods using which we can remove as
well as copy a file in Python.
The
copyfile() method copies the content from the source to the target file using
the file paths. It returns the target file path.
The
target file path must be writeable or else an OSerror exception would occur.
import
shutil
shutil.copyfile(
'sample.txt' , 'targ.txt' )
fptr=open("targ.txt","r")
print(fptr.read())
fptr.close()
output :
Python
is an interpreted programming language
Format operator
• The argument of write has to be a string,
so if we want to put other values in a file, we have to convert them to
strings. The easiest way to do that is with str
• An alternative is to use the format
operator, %. When applied to integers, % is the modulus operator. But when the
first operand is a string, % is the format operator.
• The first operand is the format string,
which contains one or more format sequences, which specify how the second
operand is formatted. The result is a string.
• The format sequence '%d' means that the
second operand should be formatted as an integer (d stands for “decimal”):
Example :
Marks
= 42
print('Ramu
got %d Marks.' % Marks)
Output :
Ramu
got 42 Marks.
Errors and Exception
• Errors are the problems in a program due
to which the program will stop the execution.
• Syntax errors are detected when we have
not followed the rules of the particular programming language while writing a
program. These errors are also known as parsing errors.
• An exception is an abnormal situation that
is raised during the program execution.
• In simple words, an exception is a problem
that arises at the time of program execution.
• When an exception occurs, it disrupts the
program execution flow. When an exception occurs, the program execution gets
terminated, and the system generates an error.
• We use the exception handling mechanism to
avoid abnormal termination of program execution.
BUILT-IN EXCEPTIONS
Commonly
occurring exceptions are usually defined in the compiler/interpreter. These are
called built-in exceptions.
Built-in
exception in Python
S. No |
Name of the Built-in
Exception |
Explanation |
1 |
SyntaxError |
It is raised when there is an error in the syntax of the Python code |
2 |
ValueError |
It is raised
when a built-in
method or operation receives an argument that has the right data type but mismatched or inappropriate values. |
3 |
IOError |
It is raised when the file specified in a program statement cannot
be opened. |
4 |
ImportError |
It is raised when the requested module definition is not found. |
5 |
EOFError |
It is raised when
the end of file condition is reached without
reading any data
by input(). |
6 |
ZeroDivisionError |
It is raised when the denominator in a division operation is zero. |
7 |
IndexError |
It is raised when
the index or subscript in a sequence is out of range |
8 |
NameError |
It is raised when a local or
global variable name is not defined |
9 |
IndentationError |
It is raised due to incorrect indentation in the program code. |
10 |
TypeError |
It is raised when an operator is supplied with a value of incorrect data
type. |
Exception Handling
Exception
handling is a powerful mechanism to prevent the exception during the execution
of the program.
The
Python programming language provides three keywords to handle the exceptions.
• try
• except
• finally
try
The
try keyword is used to define a block of code which may cause an exception.
Syntax:
try:
statement(s)
except
The
except keyword is used to define a block of code which handles the exception.
Syntax:
except:
statement(s)
finally
The
finally keyword is used to define a block of code which is to execute,
regardless of an exception occurrence.
Syntax:
finally:
statement(s)
Note
: The Python
allows us to use an optional else keyword that can be used with try block. The
else is used to define a block of code to be executed if no exception were
raised.
The
following is the general syntax of exception handling in the Python.
Syntax:
try:
# the code that may raise an exception
except:
# the code that handles an exception
else:
# the code that to be executed if no exception were
raised
finally:
# the code that must be executed
try:
x =
int(input("enter first number: "))
y =
int(input("enter second number: "))
result=x/y
print("The
answer of x divide by y:", result)
except:
print("Can't divide with zero")
finally:
print("finally block")
When
we run the above example code, it produces the following output.
Catching the specific Exception
• In Python, the except block may also catch
a particular exception. In such a case, it handles only the particularized
exception, if any other exception occurs it terminates the execution.
a =
int(input('Enter a number: '))
b =
int(input('Enter a number: '))
try:
c = a / b
print('Result: ', c)
except
ZeroDivisionError:
print('Exception: value of b can not be zero!')
When
we run the above example code, it produces the following output for the values
a = r
and b = 5. Here, the exception is a ValueError which can not be handled by the
above code.
Modules
In
Python, a module is a python file containing functions, class, and variables. A
module is included in any python application using an import statement.
How to create a module?
In
Python programming, to create a module simply define the functions, classes,
and variables that you want to place in the module and save the file with .py
extension.
For
example, let's create a module which performs all arithmetic operations.
def
add(a, b):
return a + b
def
sub(a, b):
return a - b
def
mul(a, b):
return a * b
def
div(a, b):
return a / b
Save
the above code as Calci.py so that the module can be used as Calci.
How to use a module?
A
module is used in any python application by importing it using the import
keyword. Now, let's import the Calci module and use the functions of it.
import
Calci print(Calci.add(10, 5))
print(Calci.sub(10,
5))
print(Calci.mul(10,
5))
print(Calci.div(10,
5))
Packages
• A python package is a collection of
modules. Modules that are related to each other are mainly put in the same
package. When a module from an external package is required in a program, that
package can be imported.
• In Python, a package is a directory which
must contains a init .py file. This
file can be an empty file.
• A package in the Python can contain any
file with .py extension including modules
How to create a package?
To
create a package in Python, just create a directory with the package name, then
create an empty file init .py inside that directory. Then the directory acts as
a package which can be imported the same way a module can be imported.
How to use a package?
To use
a package in python, we must import the package using import statement the same
way a module has imported in the earlier tutorials.
For
example, a package with name My_Package can be imported as import My_Package.
A
specific module can also be imported using the syntax
from
Package_Name import Module_Name.
Example on creating a package:
• Let us create a package with two different
modules.
• Creating a directory is the first step in
creating a package.
• Let’s create a directory College
The
following step is to add three Python modules to the directory.
Create_init_.py
file
Code in file students.py
def
getStudents():
print("There are total 2500 students")
Code in file Teachers.py
def
getTeachers():
print("There are total 70 teachers")
Code in file Main.py
from
College.Students import getStudents
from College.Teachers
import getTeachers
getStudents()
getTeachers()
Comments
Post a Comment