python simple pdf
python simple pdf
CO1 Develop Python programs using standard I/O functions and basic operators.
CO2 Develop Python programs using control flow and looping statements
CO – PO Mapping:
COs PO1 PO2 PO3 PO4 PO5 PO6 PO7
CO1 3
CO2 3
CO3 3 3
CO4 3 3 3
SAFETY PROCEDURES
PROBLEM STATEMENT:
The safety instructions are presented to the attention of the students as a mean of preventing accidents
while performing experiments and activities in the communication lab of the department.The purpose is to
draw attention to the risks involved in lab activities to prevent human suffering and damage to equipment.
Working in the lab is not allowed without following electricity precautions displayed. No individual work
is allowed in the lab.
Laboratory in charge is responsible for the arrangements of your lab activities; Listen carefully to his/her
instructions and follow them.
● Inform the lab in charge about dangerous conditions and faults in the lab or nearby environment.
Do not do any action that may harm people or equipment in the lab.
● Do not misuse any of the tools or instruments belong to the lab.
● Strict discipline should be maintained in the laboratory.
● Turn off cell phones before entering the lab.
● At the end and beginning of the laboratory, follow 5S procedures and leave the work table clean
and tidy.
ELECTRICAL SAFETY:
Consult the Electrical Engineering section available in the campus for electrical safety queries.
The lab equipment is powered from electrical sockets installed on the tables. Do not use equipment that is
powered from a damaged socket.
Do not use equipment that is powered from flexible cable with damaged insulation or if it’s plug is not
assembled properly.
Do not repair or disassemble electrical equipment including replacement of fuses installed in the
equipment.
Do not open the main fuse box, unless it is an emergency and you need to switch off main circuit breaker.
EMERGENCY SWITCHES:
The laboratory has circuit breakers, which are located in the main panel. Identify the place. In an
emergency condition,switch off circuit breakers immediately.
HANDLING ELECTROSTATIC DISCHARGE (ESD)
PROBLEM STATEMENT:
THEORY
In handling electronic devices, datasheets cautions about ESD (Electrostatic Discharge) precautions.
These devices are prone to damage because of electrostatic charges made by human body. These charges
may be up to 4000 volts and cause damage without being noticed. It is recommended to follow ESD
precautions on handling of these devices.
1. Make sure you have a reliable ground point available near the table.
2. Do not wear clothing which generates static electric charges every time you move.
3. Do not handle static generating objects while working on electronics.
4. Store all chips and other components in appropriate anti-static containers.
5. Keep all ESD sensitive components and spares in anti-static envelopes for storage.
6. Be sure to turn off the power and remove the power plug from all equipment before working,
repairing or assembling.
7. Do not plug in or remove equipment while the power is on.
Experiment 1
Install Python environment in Windows, Linux and Android, use of IDLE and
Python path
AIM
To install Python environment in Windows, Linux and Android, use of IDLE and Python path
INSTALLATION PROCEDURE
To begin with, writing Python Codes and performing various intriguing and useful operations,
one must have Python installed on their System. This can be done by following the step by step
instructions provided below:
Installing on Windows
The simplest way to install Python and all the scientific libraries in Windows OS is to use the
Anaconda distribution, which includes the Spyder integrated development environment (IDE) for
Python. The Anaconda distribution also includes Jupyter notebooks for those who prefer to
interact with Python using a web-based note- book format. The Anaconda package can be found
at https://www.anaconda.com/download/. Make sure to download Python 3.x (x should be 6 or
greater). The latest stable version is Python 3.11.1 as of January, 2023.
The other way to install is by downloading the executable file from the Python website using the
link https://www.python.org/downloads/.
Installing on Linux
Most of the Linux OS has Python pre-installed. To check if your device is pre-installed with
Python or not, just go to the terminal using Ctrl+Alt+T and run the below command.
python3 --version
If Python is already installed, it will generate a message with the Python version available.
For almost every Linux system, the following command could be used to install Python directly:
You can use any python editor like the default editor IDLE or Jupyter notebook or Spyder or any
plain text editor to write python codes.
Python programs are saved with the .py extension that contain lines of Python code.
Fig: Python IDLE Screen
To write a python program and save it in a file using the IDLE Shell, in the toolbar go to File>
New File or use shortcut Ctrl+N. It will open an editor window where we can write the code and
save. To run the code, in the toolbar go to Run> Run Module. The output/ error message will be
shown in the IDLE Shell.
Result:
Installed Python environment in Windows, Linux and Android, and used IDLE.
Experiment 2
Demonstrate input and output functions
AIM
THEORY
In this experiment, you will learn how to input or read data into a Python program, either from
the keyboard or a computer file. You also learn how to output or write data, either to a computer
screen or to a computer file.
Input Function:
Python has a function called input() for getting input from the user and assigning it a variable
name.
Syntax:
When the input function is executed, it prints to the computer screen the text in the quotes and
waits for input from the user. The user types a string of characters and presses the return key. The
input function then assigns that string to the variable name on the right of the assignment
operator “=”.
Output Function:
Syntax:
Parameters:
value(s) : Any value, and as many as you like. Will be converted to string before printed
sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than one.
Default :’’
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False).
Default: False
Example:
Output of Example:
By default the input function will take the data as String. If you want to change the data to a
number include int (for integer) or float (for float) before the input function. Another way to do
that is to use eval function.
Example:
Output of Example
Using % Operator
We can use the ‘%’ operator. % values are replaced with zero or more values of elements. The
formatting using % is similar to that of ‘printf’ in the C programming language.
● %d – integer
● %f – float
● %s – string
● %x – hexadecimal
● %o – octal
Example
Output of Example:
Result:
Demonstrated input and output functions in python and implemented the example programs for
the same and verified the output.
Experiment 3
Demonstrate standard data types in Python
AIM
To demonstrate standard data types which Python uses to store and organize numerical,
alphabetical, and other types such as strings, lists, tuples, and dictionaries.
THEORY
1. Integers
In Python, integers are zero, positive or negative whole numbers without a fractional part and
having unlimited precision, E.g. 0, 100, -10. Integers can be binary, octal, and hexadecimal
values.
2. Float
In Python, floating point numbers (float) are positive and negative real numbers with a fractional
part denoted by the decimal symbol “.” or the scientific notation E or e.
3. Complex Number
A complex number is a number with real and imaginary components. For example, 5 + 6j is a
complex number where 5 is the real component and 6 multiplied by j is an imaginary component.
4. Boolean
Python boolean type is one of the built-in data types provided by Python, which represents one
of the two values i.e. True or False. Generally, it is used to represent the truth values of the
expressions. For example, 1==1 is True whereas 2<1 is False.
5. Strings
Strings are lists of characters. Any character that you can type from a computer keyboard, plus a
variety of other characters, can be elements in a string. Strings are created by enclosing a
sequence of characters within a pair of single or double quotes.
Example
“abc”
“123”
‘#5xyz’
“{0:0.8g}”
Strings can be assigned variable names and it can be concatenated using the “+” operator.
Example
Output of Example
Example
Output of Example
6. Lists
Python has two data structures, lists and tuples, that consist of a list of one or more elements. The
elements of lists or tuples can be numbers or strings, or both. Lists are defined by a pair of
square brackets on either end with individual elements separated by commas.
Example
Output of Example
The indexing in List starts from zero. Individual elements of a list can be accessed using the
variable name for the list with an integer in square brackets.
Example
Output of Example
Output of Example
You access a subset of a list by specifying two indices separated by a colon “ : ”. This is a
powerful feature of lists that we will use often.
Example
7. Tuples
Tuples are lists that are immutable. That is, once defined, the individual elements of a tuple
cannot be changed. A tuple is written as a sequence of elements enclosed in round parentheses ().
Example
8. Set
A set never follows a sequence which we have mentioned in list or tuple. The elements of set is
written in curly brackets {}
Example
9. Dictionary
Each value in list will have a unique key to identify the elements
Example
Example
Result:
Demonstrated the standard data types used in Python to store and organize numerical,
alphabetical, and other types such as strings, lists, tuples, and dictionaries.
Experiment 4
Programs using Basic Operators
AIM
THEORY
Operators:
Python Operators in general are used to perform operations on values and variables. These are
standard symbols used for the purpose of logical and arithmetic operations. In this article, we
will look into different types of Python operators.
● OPERATORS: Are the special symbols. Eg- + , * , /, etc.
● OPERAND: It is the value on which the operator is applied.
Arithmetic Operators
1. Arithmetic operators
These are used to perform mathematical operations like addition, subtraction,
multiplication, and division.
Operator Description Syntax
> Greater than: True if the left operand is greater than the right x>y
< Less than: True if the left operand is less than the right x<y
is x is the same as y x is y
x is not
is not x is not the same as y
y
Output of Example
3. Logical Operators
Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is used
to combine conditional statements.
and Logical AND: True if both the operands are true x and y
Output of Example:
Bitwise Operators
4. Bitwise Operators
Bitwise operators act on bits and perform the bit-by-bit operations. These are used to operate on
binary numbers.
| Bitwise OR x|y
~ Bitwise NOT ~x
Output of Example:
5. Assignment Operators
Assignment operators are used to assign values to the variables.
Add AND: Add right-side operand with left side operand a+=b
+=
and then assign to left operand a=a+b
Subtract AND: Subtract right operand from left operand a-=b
-=
and then assign to left operand a=a-b
Divide AND: Divide left operand with right operand and a/=b
/=
then assign to left operand a=a/b
Output of Example:
6. Membership Operators
in and not in are the membership operators; used to test whether a value or variable is in a
sequence.
Output of Example:
Result:
To build programs using flow control or decision making statements: IF statement, IF-ELSE,
Nested IF and ELSE-IF statements.
THEORY:
There comes situations in real life when we need to do some specific task based on some specific
condition. Similarly there comes a situation in programming where a specific task is to be
performed if a specific condition is satisfied (or True). In such cases, conditional statements can
be used.
Conditionals:
Conditional statements allow a computer program to take different actions based on whether
some condition, or set of conditions is true or false. In this way, the programmer can control the
flow of a program.
1. if
2. if-else
3. Nested if
4. if-elif statements.
1. IF Statement
Syntax:
if (condition):
Example:
Output of example
2. IF ELSE Statement
In IF ELSE, an additional statement can be included in “IF condition” which will be executed
only if the “IF condition” is FALSE.
if (condition):
else:
Example:
Output of Example:
3. Nested IF Statement
In this, one or more IF conditions can be written inside other IF conditions. This means that the
inner IF condition will be checked only if the outer IF condition is true and by this, we can see
multiple conditions to be satisfied.
Syntax:
if (condition 1):
if (condition 2):
is True
Example:
Output of Example:
4. ELSE IF statement
ELSE IF is used when multiple IF conditions are to be used to verify different conditions and
based on that various statements are to be executed. In this an ELSE statement is written at the
end of the program.
if (first condition):
# Statements to execute when first IF condition is True
Sample Programs:
Output
Result:
Developed programs using flow control or decision making statements: IF statement, IF-ELSE,
Nested IF and ELSE-IF statements and verified the output
Experiment 5
Python programs using Control Flow- For Loop and While loop
AIM
To build programs using flow control or decision making statements: For loop and While loop.
THEORY
Python provides three ways for executing the loops. While all the ways provide similar basic
functionality, they differ in their syntax and condition checking time.
1. While Loop
A while loop is used to execute a block of statements repeatedly until a given condition is
satisfied. And when the condition becomes false, the line immediately after the loop in the
program is executed.
Syntax :
while (expression):
Statement to execute
All the statements indented by the same number of character spaces after a programming
construct are considered to be part of a single block of code. Python uses indentation as its
method of grouping statements.
Example:
Program that executes a while loop until the variable “count” exceeds a value 3.
Output
Syntax:
while condition:
# Statements to execute
else:
# Statements to execute
Example:
Output:
3. For loop
“For” loops are used for sequential traversal. For example: traversing a list or string or array etc.
In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for in” loop which is
similar to for each loop in other languages.
Syntax:
for iterator_var in (sequence):
statements(s)
Output:
Output:
$. Nested For loop
Python programming language allows to use one loop inside another loop.
Syntax:
for iterator_var in (sequence):
for iterator_var in sequence:
Statements to execute in second loop
Statements to execute in first loop
Example:
Output:
Example: Read 10 numbers from keyboard and find their sum and average and print the results
Output:
Output:
Example: Sum of the elements in a matrix.
In this example, Numpy (Numerical Python) library is used for working with arrays. In Python
we have lists that serve the purpose of arrays, but they are slow to process.
NumPy aims to provide an array object that is up to 50x faster than traditional Python lists. The
array object in NumPy is called ndarray, it provides a lot of supporting functions that make
working with ndarray very easy. Arrays are very frequently used in data science, where speed
and resources are very important.
Output
Result:
Performed programming using control flow statements such as For loops and While loops.
Experiment 6
User Defined Functions
AIM
To develop simple programs to demonstrate how to define and call user defined functions
THEORY
A function is a set of statements that take inputs, do some specific computation and produce
output. 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 call the
function.
Functions that readily come with Python are called built-in functions. Python provides built-in
functions like print(), input() etc., but we can also create our own functions. These functions are
known as user defined functions.
Syntax
In Python, def keyword is used to declare user defined functions. Function name can be decided
by the user. The arguments (input variables used in functions) can be given in parentheses as
given below.
Example:
Python function to check whether the given number is even or odd
Output
Example:
Find the sum and average of two integer numbers using user defined function
Output
Example:
Print multiplication table of the given number using user defined function
Output
RESULT
To implement File I/O handling functions such as open(), close(), read(), write(), tell() and seek()
THEORY
Python supports file handling and allows users to handle files such as to read and write files,
along with many other file handling options, to operate on files. Python treats files as text or
binary and this is important.
Text files: In this type of file, Each line of text is terminated with a special character called EOL
(End of Line), which is the new line character (‘\n’) in python by default.
Binary files: In this type of file, there is no terminator for a line and the data is stored after
converting it into machine understandable binary language.
1. open()
It is used to open a file. At the time of opening, we have to specify the mode, which
represents the purpose of the opening file.
Mode
r: open an existing file for a read operation.
w: open an existing file for a write operation. If the file already contains some data then it
will be overridden but if the file is not present then it creates the file as well.
a: open an existing file for append operation. It won’t override existing data.
r+: To read and write data into the file. The previous data in the file will be overridden.
w+: To write and read data. It will override existing data.
a+: To append and read data from the file. It won’t override existing data.
2. close()
Though Python automatically closes a file if the reference object of the file is allocated to
another file, it is a standard practice to close an opened file as a closed file reduces the
risk of being unwarrantedly modified or read.
Python has a close() method to close a file. The close() method can be called more than
once and if any operation is performed on a closed file it raises a ValueError.
3. read()
There is more than one way to read a file in Python. If you need to extract a string that
contains all characters in the file then we can use file.read()
Example
Output:
Another way to read a file is to call a certain number of characters like in the following
code the interpreter will read the first five characters of stored data and return it as a
string.
Example:
Output: The first 10 characters including space, comma are read.
4. write()
It is used to write/ manipulate a file using python. To do so, we need to open the file in
write mode.
Example
5. tell()
Sometimes it becomes important for us to know the position of the File Handle (like a
cursor). tell() method can be used to get the position of File Handle. tell() method returns
current position of file object. This method takes no parameters and returns an integer
value. Initially file pointer points to the beginning of the file(if not opened in append
mode). So, the initial value of tell() is zero.
Example:
Output
Output
6. seek()
In Python, seek() function is used to change the position of the File Handle to a given
specific position. File handle is like a cursor, which defines from where the data has to be
read or written in the file.
Syntax
f.seek(offset, from_what)
Parameters:
Offset: Number of positions to move forward
from_what: It defines a point of reference.
Returns: Return the new absolute position.
The reference point is selected by the from_what argument. It accepts three values:
Example:
Output
Example
RESULT
Implement File I/O handling functions such as open(), close(), read(), write(), tell() and seek()