PYTHONPROGRAMMING_UNIT1
PYTHONPROGRAMMING_UNIT1
PYTHON programming
programming language.
It is simple and easy to learn and provides lots of high-level data structures.
Features of Python:-
Open Source:- There is no need to pay for Python software. It can be free
downloaded from www.python.org website.
Portable:- Due to its open-source nature, Python has been ported to many
platforms. Python programs can work on any platforms without any
modification.
Easy to Learn and Use :- Python is easy to learn as compared to other
programming languages. Its syntax is straight forward and much the same as
Python programming Bhavani M
2|Page
Python Applications
Desktop GUI Applications:- The GUI stands for the Graphical User
Interface, which provides a smooth interaction to any application.
Python provides a Tk GUI library to develop a user interface. Some
popular GUI libraries are Tkinter or Tk , wxWidgetM , Kivy (used for
writing multitouch applications )
PYTHON VERSIONS
Python is a high-level programming language known for its simplicity
and readability.
Over the years several versions of python have been released each
introducing new features and improvements.
Here are some key points about different Python versions
Python 2.x:
Python 2.x was the original major version of Python and was released in the
year 2000.
Python 2.7, released in 2010, is the last version of Python 2 and is still used
in some legacy systems.
Python 2.x has reached its end-of-life status, and no new features or bug
fixes are being released for it. It is strongly recommended to migrate to
Python 3.
Python 3.x:
Python 3.8 (2019): Introduced the "walrus operator" (:=) for assignment
expressions and added the "math. Prod()" function.
Python 3.9 (2020): Brought features like dictionary merging (| operator)
and improved support for type annotations.
Note: Beyond September 2021, several more Python versions have been
released, including Python 3.10 in October 2021 and subsequent updates.
PYTHON INSTALLATION
included with your Python installation. Pip allows you to easily install and
manage additional Python libraries.
python get-pip.py
Verify the installation: After the installation is complete, you can verify
if pip is installed correctly by running the following command:
pip --version
To access the Python command line mode, you can follow these steps:
Open your terminal or command prompt.
Type python or python3 (depending on your Python installation) and press
Enter.
This will start the Python interpreter and display the Python version and a
prompt >>>.
Now, you can start typing Python statements and press Enter to execute them.
The interpreter will immediately evaluate the statement and display the result (if
any).
Python programming Bhavani M
7|Page
You can continue entering statements one by one, and the interpreter will
execute them sequentially.
To exit the Python command line mode, you can type exit() or quit() and press
Enter. This will exit the interpreter and return you to the terminal.
Hello, World!
>>> x = 10
>>> y = 5
>>> x + y
15
>>> exit()
In this example, we start the Python interpreter by typing python in the
terminal.
We then enter various Python statements, such as printing a string, assigning
values to variables (x and y), and performing arithmetic operations. The
interpreter evaluates the statements and displays the results.
Finally, we exit the Python command line mode by typing exit(), and the
prompt returns to the terminal.
PYTHON IDE’S
There are several popular Integrated Development Environments (IDEs) available
for Python programming.
PyCharm: Developed by JetBrains, PyCharm is a powerful and rich feature IDE for
Python. It offers a wide range of tools for code editing, debugging, testing, and version
control integration. PyCharm is available in both a free Community edition and a paid
Professional edition.
Visual Studio Code (VS Code): VS Code is a highly popular and extensible code editor
that provides excellent support for Python. It offers a wide range of extensions that can be
installed to enhance Python development. VS Code is free and available for Windows,
macOS, and Linux.
Anaconda: Anaconda is a Python distribution that comes with its own IDE called
Anaconda Navigator. It is focused on data science and scientific computing, providing
accurate collection of Python packages for these domains. Anaconda is available for free
and supports multiple platforms.
Spyder: Spyder is another IDE specifically designed for scientific computing and data
analysis with Python. It offers an interactive development environment with features like
code introspection, debugging, and variable exploration. Spyder is open-source and can be
installed using Anaconda or directly via pip.
Jupyter Notebook/Jupyter Lab: Jupyter Notebook is a web-based interactive
environment that allows you to create and share documents containing live code,
visualizations, and explanatory text. Jupyter Lab is the next-generation UI for Jupyter
Notebook, offering a more versatile and extensible interface. Both Jupyter Notebook and
Jupyter Lab are widely used for data analysis, research, and prototyping.
float() is used to convert the input into floating-point numbers (allowing for
decimal values).
The program then adds the two numbers together and stores the result in the
result variable.
Finally, the program uses the print() function to display the result on the
console, along with an informative message.
PYTHON BASICS
Identifiers
Identifier is the name given to various program elements like variables, function,
arrays, classes, strings etc.
Keywords
The keywords are also called as reserved word. The keywords have predefined
meaning.
X=3;
Print(x)
Expression
An expression is a combination of operators and operands that is interpreted to
produce some other value.
Variables
Operator
Operators are special symbols that perform operations on variables and values.
Assignment Operator: Assignment operators are used to assign values to the variables.
Bitwise Operator: a bit is the smallest unit of data storage and it can have only
one of the two values i.e 0 and 1. Bitwise operators works on bits and perform bit
by bit operation.
Operator Precedence: - This is used in an expression with more than one operator with
different precedence to determine which operation to perform first. Operator precedence
affects how an expression is evaluated.
Operator Associativity: -If an expression contains two or more operators with the
same precedence, then Operator Associativity is used to determine. It can either be Left
to Right or from Right to Left.
Example: “*” and “/” have the same precedence and their associativity is Left to Right,
so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.
** Exponent right-to-left
+– Addition/subtraction left-to-right
is, Identity
isnot left-to-right
Membership operators
in,
notin
or Logical OR left-to-right
= Assignment right-to-left
Example: x = 7 + 3 * 2;
here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first
multiplies 3*2 and then adds into 7.
Data Types
A data type represents the type of data stored into a variable or memory. There
are 5 different data types are:
None type
Numeric type
Sequences
Sets
Dictionary
different data type elements, but an array can store only one type of
elements.
List can grow dynamically in memory but the size of array is fixed
and they cannot grow dynamically.
Example: list=[10,3.5,-20, “evening ”+‟Saturday”] # create a list
print(list) #it display all elements in the list
10,3.5,-20,evening,Saturday
Tuple data type:
A tuple is similar to list.
A tuple contains group of elements which can be different types.
The elements in the tuple are separated by commas and enclosed in parentheses ().
The only difference is that tuples are immutable. Tuples once created cannot be
modified.
The tuple cannot change dynamically.
Dictionary:
In Python dictionaries are written with curly brackets, and they have keys and values.
That means dictionary contains pair of elements such that first element
represents the key and the next one becomes its value.
The key and value should be separated by a colon(:) and every pair should
be separated by comma.
All the elements should be enclosed inside curly brackets.
Here, d is the name of dictionary. 3 is the key and its associated value is “ssc”.
The next is 4 and its value is “tarun” and so on.
Print(d) # it displays :
{3: “ssc”+ 4: “tarun”+ 5:‟kvc”+ 6: “vedish”}
Print(d[5]) # it display : kvc
Indentation
if 5 > 2:
Example 2:- Python will give you an error if you skip the indentation
if 5 > 2:
Comment:
The triple double quotes („‟ ”‟) or triple single quotes (“““ ”””) are called
multi line comments.
computer is called input. The results returned by the computer are called
output. So, we can say that a computer takes input, processes that input and
produces the output.
To provide input to a computer, Python provides some statements which are
called Input statements. Similarly, to display the output, there are Output
statements available in Python.
Output statements
To display output or results, Python provides the print() function.
This function can be used in different formats.
print() Statement :-When the print() function is called simply, it will throw
the cursor to the next line. It means that a blank line will be displayed.
print('value=‟%i%x)
value= 10
As seen above, to display a single variable (i.e. x), we need not wrap it inside parentheses.
Python programming Bhavani M
22 | P a g e
Input Statements
To accept input from keyboard, Python provides the input () function. This
function takes a value from the keyboard and returns it as a string.
For example
str = input('Enter your name:')
Enter your name: Raj
print(str)
output: Raj
Type conversion refers to changing a given object from one data type to another data
type.
Type conversion in Python is used to convert values from one data type to another,
either automatically by the Python interpreter or manually by the programmer using
in- built functions.
Note that not all data types can be converted into each other. For example, there's no
way a string consisting of English letter alphabets can be converted into an integer.
Implicit Type Conversion
Implicit type conversion is when the Python interpreter converts an object from one
data type to another on its own without the need for the programmer to do it
manually.
The smaller data type is covered into higher data type to prevent any loss of data
during the runtime. Since the conversion is automatic, we do not require to use any
function explicitly in the code.
Example:
english, science, maths, sst, it = 95, 92, 97, 90, 98
Python programming Bhavani M
23 | P a g e
PYTHON LIBRARY
A Python library is a collection of related modules.
It contains bundles of code that can be used repeatedly in different programs.
It makes Python Programming simpler and convenient for the programmer. As we don‟t
need to write the same code again and again for different programs.
Modules on the other hand refer to any python file saved with the .py extension.
Modules often contain code such as functions, classes and statements that can be
imported and used within other programs.
Python libraries are pre-written sets of code that provide various functionalities to
developers.
These libraries contain modules and packages that can be imported into your python
programs to extend their capabilities.
Python libraries are created and maintained by the Python community and cover a wide
range of areas, including data analysis, web development, machine learning, scientific
computing, and more.
To import a library in Python, you can use the import statement. Here are the
steps to import a library:
Identify the library: Determine the name of the library you want to import.
Libraries in Python often come with built-in functionality or provide additional
features for specific purposes.
Import the library: Use the import statement followed by the name of the
library. You can place the import statement at the beginning of your Python script
or module.
Utilize the library's features: Once the library is imported, you can access its
functions, classes, or other elements using the library's name followed by a dot (.)
notation.
Examples for library
Matplotlib: This library is responsible for plotting numerical data. And that‟s why
it is used in data analysis. It is also an open-source library and plots high-defined
figures like pie charts, histograms, scatterplots, graphs, etc.
Pandas: It is an open-source machine learning library that provides flexible high-
level data structures and a variety of analysis tools. It eases data analysis, data
manipulation, and cleaning of data. Pandas support operations like Sorting, Re-
Here's an example that demonstrates the steps to import and use the math library,
which provides various mathematical functions:
Step 1: Identify the library
# The math library provides mathematical functions
num = 16
sqrt = math.sqrt(num)
print("The square root of", num, "is", sqrt) #
Calculate the value of pi
pi = math.pi
print("The value of pi is", pi)
In this example, the math library is imported using the import statement. After
importing, we can access the library's functions and constants using the math.
prefix.
We calculate the square root of a number (math.sqrt()) and assign it to the
variable sqrt. We then print the result. Additionally, we access the value of pi
(math.pi) and print it.
By importing the math library, we gain access to its features and can use them in
our program.
Conditional statements
In Python, condition statements act depending on whether a given condition is true
or false.
Condition statements always evaluate either True or False.
If the condition is True, then the True block of code will be executed, and if the
Python programming Bhavani M
27 | P a g e
condition is False, then the block of code is skipped, and the controller moves to the
next line
We can call these conditional statements as decision making statements because
they are used to make decision based on given condition
If statement :
In control statements, The if statement is the simplest form. It takes a condition and
evaluates to either True or False.
If the condition is True, then the True block of code will be executed, and if the
condition is False, then the block of code is skipped, and The controller moves to the
next line
Example-1
a=6
b = 10
if a < b:
print (“a is less than b”)
output:
a is less than b
Example-2
a = int (input (“enter no:”))
if a < 10:
print (“a value is less than 10”)
output:
enter no:6
a value is less than 10
If – else statement:
The if-else statement checks the condition and executes the if block of code when the condition
is True, and if the condition is False, it will execute the else block of code.
Syntax for if-else statement
if condition:
statement 1
else:
statement 2
If the condition is True, then statement 1 will be executed If the condition is False, statement 2
will be executed
Example-1
a=int (input (“enter a value:”))
b = int (input (“enter b value:”))
if a < b:
print (“a is smaller no”)
else:
print(“b is smaller no ”)
output 1:
enter a value :2
Python programming Bhavani M
29 | P a g e
Example2:
password = input ('Enter password ')
if password == "nisha123":
print("Correct password")
else:
print("Incorrect Password")
if (a<20):
print (“a value is less than 20”)
elif (a==30):
print (“a value is equal to 30”)
elif (a==40):
print (“a value is equal to 40”)
else:
print(“number not found”)
output:
Enter number : 9
a value is less than 20
Enter number : 30
a value is equal to 3
Output 2:
Enter first number 29
Enter second number 78
29 is smaller than 78
While Loop
For Loop
Nested For Loops
While Loop In Python
Input_password=input(“enter password:”)
while password != input_password:
Input_password=input(“enter password:”)
else:
print(“unlocked!!!!!!!!!”)
output:
enter password:11111
enter password:135656
enter password:123456
unlocked!!!!!!!!!
Example2:
for i in range(10):
print(i)
output:
0
1
2
3
4
5
6
7
8
9
Note: In above example i did not given starting range, so by default it will take value 0
Example:
for loop to display the multiplication table of 5.
num = 5
for i in range(1, 11):
print(num, 'x', i, '=', num*i)
output:
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
are for loop and while loop. Using these loops we can create nested loops in Python. Nested
loops mean loops inside a loop. For example, while loop inside the for loop, for loop inside the
for loop, etc.
Python Nested Loops Syntax:
Outer_loop Expression:
Inner_loop Expression:
Statement inside inner_loop
Statement inside Outer_loop
for a in range(1,3):
for b in range(1, 11):
print(a, "x", b, "=", a*b)
output:
1X1=1
1X2=2
1X3=3
1X4=4
1X5=5
1X6=6
1X7=7
1X8=8
1X9=9
1 X 10 = 10
2X1=2
2X2=4
2X3=6
2X4=8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
Break statement:
The break statement is used to terminate the loop or statement in which it is present.
After that, the control will pass to the statements that are present after the break
statement, if available.
If the break statement is present in the nested loop, then it terminates only those loops
which contains break statement.
Syntax:
break
Program:
for a in range(1,11):
print(a)
if a==5:
break
output:
1
2
3
4
Continue statement:
Continue is also a loop control statement just like the break statement.
continue statement is opposite to that of break statement, instead of terminating the loop,
it forces to execute the next iteration of the loop.
As the name suggests the continue statement forces the loop to continue or execute the
next iteration.
When the continue statement is executed in the loop, the code inside the loop following
the continue statement will be skipped and the next iteration of the loop will begin.
Syntax:
Continue
output:
1
3
5
7
9
Pass statement:
As the name suggests pass statement simply does nothing.
The pass statement in Python is used when a statement is required syntactically but you
do not want any command or code to execute.
It is like null operation, as nothing will happen if it is executed.
Python programming Bhavani M
38 | P a g e
Pass statement can be used for writing empty loops, control statement, function and
classes.
Syntax:
pass Program:
if “a” in “india”:pass
The exit() function in Python is used to exit or terminate the current running script or
program.
You can use it to stop the execution of the program.
When the exit() function is called, the program will immediately stop running and
exit.
for i in range(10):
if i == 5:
print(exit) # prints the exit message
exit()
print(i)
Output
0
1
2
3
4
EXCEPTION HANDLING
Exception
An exception is an event, which occurs during the execution of a program that disrupts
the normal flow of the program's instructions.
When a Python encounters a situation that it cannot cope with it raises an exception.
Python programming Bhavani M
39 | P a g e
Rules of Exceptions
Exceptions must be class objects
For class exceptions, you can use try statement with an except clause
which mentions a particular class.
Even if a statement or expression is syntactically correct, it may display
an error when an attempt is made to execute it.
except <ExceptionType>:
<handler>
Here, <body> contains the code that may raise an exception. When an
exception occurs, the rest of the code in <body> is skipped.
If the exception matches an exception type, the corresponding handler is
executed.
<handler> is the code that processes the exception.
Example:
Def divide(a,b):
try:
c = a/b
return c
except:
print ("Error in divide function")
print(divide(10,0))#function call
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
# Output: Error: Denominator cannot be 0.
In the example, we are trying to divide a number by 0.
Here, this code generates an exception. To handle the exception, we have put
the code, result = numerator/denominator inside the try block.
Now when an exception occurs, the rest of the code inside the try block is
skipped.
The except block catches the exception and statements inside the except block
are executed. If none of the statements in the try block generates an exception,
the except block is skipped.
Since the list index starts from 0, the last element of the list is at index 3.
Notice the statement, print(even_numbers[5])
Here, we are trying to access a value to the index 5. Hence, IndexError
exception occurs. When the IndexError exception occurs in the try block,
The ZeroDivisionError exception is skipped.
The set of code inside the IndexError exception is executed.
Output
If we pass an odd number:
Enter a number: 1 Not an even number!
If we pass an even number, the reciprocal is computed and displayed.
Enter a number: 4 0.25
However, if we pass 0, we get ZeroDivisionError as the code block inside else
is not handled by preceding except.
Note: Exceptions in the else clause are not handled by the preceding except
clauses.
Python try...finally
In Python, the finally block is always executed no matter whether there is an
exception or not. The finally block is optional. And, for each try block, there
can be only one finally block.
Let's see an example
try:
numerator = 10
denominator = 0
result = numerator/denominator print(result)
except:
print("Error: Denominator cannot be 0.")
finally:
print("This is finally block”)
Output
Error: Denominator cannot be 0. This is finally block.
In the above example, we are dividing a number by 0 inside the try block. Here,
this code generates an exception.
The exception is caught by the except block. And, then the finally block is
executed.
Function
Python programming Bhavani M
46 | P a g e
Built-in functions:- Python has several functions that are readily available for
use. These functions are called built- in functions.
Ex: abs(),all().ascii(),bool()………so on….
Sum=x+y
Return(sum)
print("The sum is", add_numbers(5, 20))
Output:
The sum is 25
Defining a function
Calling a Function
Calling a function executes the code in the function.
In a function‟s definition, you define what it is to do. To use a function, you
have to call or invoke it.
The program that calls the function is called a caller.
Example:
def add(a,b): here a and b are parameters
result=add(12,13)#12 and 13 are arguments
print(result)
There are various ways to use arguments in a function. In Python, we have the
following 4 types of function arguments.
• Keyword arguments
• Default arguments
• Variable length arguments
• Positional arguments
Keyword Arguments
When we call a function with some values, these values get assigned to
the arguments according to their position.
Python allows functions to be called using keyword arguments. When we
call functions in this way, the order (position) of the arguments can be
changed.
If you have some functions with many parameters and you want to
specify only some of them, then you can give values for such parameters
by naming them this is called keyword arguments we use the name
(keyword) instead of the position to specify the arguments to the function.
Example:
Python programming Bhavani M
49 | P a g e
Def display(a,b):
Print(a,b)
display(b=20,a=10)
Default Arguments
In a function, arguments can have default values.
We assign default values to the argument using the „=‟ (assignment)
operator at the time of function definition.
You can define a function with any number of default arguments.
The default value of an argument will be used inside a function if we do
not pass a value to that argument at the time of the function call. Due to
this, the default arguments become optional during the function call.
It overrides the default value if we provide a value to the default
arguments during function calls.
Example:
Let‟s define a function student() with four arguments name, age, grade,
and school.
In this function, grade and school are default arguments with default
values.
If you call a function without school and grade arguments, then the
default values of grade and school are used.
The age and name parameters do not have default values and are
required (mandatory) during a function call.
Output:
Student Details: Jon 12 Five ABC School
Variable-length arguments
Sometimes you may need more arguments to process function than you
mentioned in the definition.
If we don‟t know in advance about the arguments needed in function, you
can use variable-length arguments also called arbitrary arguments.
For this an asterisk (*) is placed before a parameter in function definition
which can hold non-keyword variable-length arguments and a double
asterisk (**) is placed before a parameter in function which can hold
keyword variable-length arguments.
Example
def wish(*names):
"""This function greets all
the person in the names tuple."""
print("Hello",name)
wish("MRCET","CSE","SIR","MADAM")
Output:
Hello MRCET Hello CSE Hello SIR Hello MADAM
Positional Arguments:
Positional arguments are those arguments where values get assigned to the
arguments by their position when the function is called.
For example, the 1st positional argument must be 1st when the function is
called. The 2nd positional argument needs to be 2nd when the function is called,
etc.
By default, Python functions are called using the positional arguments.
Example: Program to subtract 2 numbers using positional arguments.
def data(name, roll no):
Example:
Def display(a,b):
Print(a,b)
Display(a=10,b=20) #For a 10 will be assigned and for b 20will be assigned
Recursion
Recursion is the process of defining something in terms of itself.
A function that call itself until a given condition is satisfied is called
recursive function
print(c)
Output: 22
Call/Pass by Reference
In pass by reference (also known as call by reference), the argument
passed to the function‟s parameter is the original object.
If we change the value of object inside the function, the original object
will also change.
Example
def my_pass_by_reference(r):
r += 10
print(r)
ref1=100
h=my_pass_by_reference(ref1)
print(h)
Output 110