Python Record
Python Record
Write a program to perform various list of operations (eg: Arithmetic, logical, bitwise
etc) in python.
Python Operators
Operators are used FOR performing operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
print(10 + 5)
out put- 15
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical operations:
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
== Equal x == y
!= Not equal x != y
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the result not(x < 5 and x <
is true 10)
is not Returns True if both variables are not the same x is not y
object
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
Operator Description Example
not in Returns True if a sequence with the specified value is not x not in y
present in the object
<< Zero fill Shift left by pushing zeros in from the right x << 2
left shift and let the leftmost bits fall off
Operator Precedence
Operator precedence describes the order in which operations are performed.
Example
Parentheses has the highest precedence, meaning that expressions inside parentheses must be
evaluated first:
print((6 + 3) - (6 + 3))
Example
Multiplication * has higher precedence than addition +, and therefor multiplications are evaluated
before additions:
print(100 + 5 * 3)
The precedence order is described in the table below, starting with the highest precedence at the top:
Operator Description
() Parentheses
** Exponentiation
+x -x ~x Unary plus, unary minus, and bitwise
NOT
^ Bitwise XOR
| Bitwise OR
and AND
or OR
Or
The or keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Not
The not keyword is a logical operator, and is used to reverse the result of the conditional statement:
Example
Test if a is NOT greater than b:
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
Nested If
You can have if statements inside if statements, this is called nested if statements.
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
The pass Statement
if statements cannot be empty, but if you for some reason have an if statement with no content, put in
the pass statement to avoid getting an error.
Example
a = 33
b = 200
if b > a:
pass
3. Write programs implementing various predefined functions of Lists, Sets, Tuples, and
Dictionaries.
List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets:
Example
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
list1 = ["abc", 34, True, 40, "male"]
print(list1[2:4])
Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Set, and Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Set
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage.
A set is a collection which is unordered, unchangeable*, and unindexed.
* Note: Set items are unchangeable, but you can remove items and add new items.
Sets are written with curly brackets.
Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Dictionary
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
Dictionaries are written with curly brackets, and have keys and values:
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
4.Write a program covering various arguments for a function
Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function is called, we
pass along a first name, which is used inside the function to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Arbitrary Arguments, *args
def my_function(*kids):
print("The youngest child is " + kids[2])
Types of Functions in Python : There are two types of functions available in python. These are:
Built-in functions are the functions that are already written or defined in python. We only need to
remember the names of built-in functions and the parameters used in the functions. As these
functions are already defined so we do not need to define these functions. Below are some built-
in functions of Python.
Output:
#5
# <class 'list'>
The functions defined by a programmer to reduce the complexity of big problems and to use that
function according to their need. This type of functions is called user-defined functions.
Output:
#7
Python 2.7
print("Enter your name:")
x = raw_input()
print("Hello ", x)
8. Write a program to create a class and its constructors.
Python Classes/Objects
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.
Create a Class
To create a class, use the keyword class:
Example
Create a class named MyClass, with a property named x:
class MyClass:
x=5
Create Object
Now we can use the class named MyClass to create objects:
Example
Create an object named p1, and print the value of x:
p1 = MyClass()
print(p1.x)
9. Write a program to implement inheritance.
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
Create a Parent Class
Any class can be a parent class, so the syntax is the same as creating any other class:
Example
Create a class named Person, with firstname and lastname properties, and a printname method:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x=Person("John", "Doe")
x.printname()
Create a Child Class
To create a class that inherits the functionality from another class, send the parent class as a parameter
when creating the child class:
Example
Create a class named Student, which will inherit the properties and methods from the Person class:
class Student(Person):
pass
10. Write a program for exception handling.
Exception Handling
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The finally block lets you execute code, regardless of the result of the try- and except blocks.
When an error occurs, or exception as we call it, Python will normally stop and generate an error
message.
These exceptions can be handled using the try statement:
Example
The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
11. Write a program to perform various linear algebra operations like finding eigen
vales and vectors, determinant for a matrix.
# importing numpy library
import numpy as np
# create numpy 2d-array
m = np.array([[1, 2],[2, 3]])
print("Printing the Original square array:\n",m)
# finding eigenvalues and eigenvectors
w, v = np.linalg.eig(m)
# printing eigen values
print("Printing the Eigen values of the given square array:\n",w)
# printing eigen vectors
print("Printing Right eigenvectors of the given square array:\n",v)
12. Write a program to read a file.
Python File Open
To open the file, use the built-in open() function.
The open() function returns a file object, which has a read() method for reading the content of the file:
Example
f = open("demofile.txt", "r")
print(f.read())
13. Write a program to use System,math etc packages.
Constants in Math Module
The value of numerous constants, including pi and tau, is provided in the math module so that we do
not have to remember them. Using these constants eliminates the need to precisely and repeatedly
write down the value of each constant. The math module includes the following constants:
1. Euler's Number
2. Tau
3. Infinity
4. Pi
5. Not a Number (NaN)
CODE
# importing the required library
import math
# printing the value of Euler's number using the math module
print( "The value of Euler's Number is: ", math.e )
# Printing the value of tau using math module
print ( "The value of Tau is: ", math.tau )
# Printing the value of positive infinity using the math module
print( math.inf )
# Printing the value of negative infinity using the math module
print( -math.inf )
14. Write a program for visualizing the data using matplotlib package.
Python math Module
Python has a built-in module that you can use for mathematical tasks.
The math module has a set of methods and constants.
Math Methods
Method Description
math.comb() Returns the number of ways to choose k items from n items without
repetition and order
math.copysign() Returns a float consisting of the value of the first parameter and the sign of
the second parameter
math.dist() Returns the Euclidean distance between two points (p and q), where p and q
are the coordinates of that point
Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under
the plt alias:
import matplotlib.pyplot as plt
Now the Pyplot package can be referred to as plt.
Example
Draw a line in a diagram from position (0,0) to position (6,250):
import matplotlib.pyplot as plt
import numpy as np
plt.plot(xpoints, ypoints)
plt.show()
Result:
15. Write a program to access data from the web and validate it.
Python program to validate an IP Address
# Python program to validate an Ip address
# re module provides support
# for regular expressions
import re
# Make a regular expression
# for validating an Ip-address
regex = "^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?
[0-9])$"
# Define a function for
# validate an Ip address
def check(Ip):