Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
49 views

Python Record

Operators in Python are used to perform operations on variables and values. There are several types of operators including arithmetic, assignment, comparison, logical, identity, membership, and bitwise operators. Python uses indentation to define scope rather than curly brackets. Conditional statements like if, elif, else, and, or, not allow control flow based on conditions. If statements can be written on one line for simple cases.

Uploaded by

Rahul N
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Python Record

Operators in Python are used to perform operations on variables and values. There are several types of operators including arithmetic, assignment, comparison, logical, identity, membership, and bitwise operators. Python uses indentation to define scope rather than curly brackets. Conditional statements like if, elif, else, and, or, not allow control flow based on conditions. If statements can be written on one line for simple cases.

Uploaded by

Rahul N
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

1.

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

Python Assignment Operators


Assignment operators are used to assign values to variables:
Operator Example Same As

= 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

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Python Comparison Operators


Comparison operators are used to compare two values:
Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Python Logical Operators


Logical operators are used to combine conditional statements:
Operator Description Example

and Returns True if both statements are true x < 5 and x < 10

or Returns True if one of the statements is true x < 5 or x < 4

not Reverse the result, returns False if the result not(x < 5 and x <
is true 10)

Python Identity Operators


Identity operators are used to compare the objects, not if they are equal, but if they are actually the
same object, with the same memory location:
Operator Description Example

is Returns True if both variables are the same object x is y

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

in Returns True if a sequence with the specified value is x in y


present in the object

not in Returns True if a sequence with the specified value is not x not in y
present in the object

Python Bitwise Operators


Bitwise operators are used to compare (binary) numbers:
Operato Name Description Example
r

& AND Sets each bit to 1 if both bits are 1 x&y

| OR Sets each bit to 1 if one of two bits is 1 x|y

^ XOR Sets each bit to 1 if only one of two bits is 1 x^y

~ NOT Inverts all the bits ~x

<< Zero fill Shift left by pushing zeros in from the right x << 2
left shift and let the leftmost bits fall off

>> Signed Shift right by pushing copies of the x >> 2


right shift leftmost bit in from the left, and let the
rightmost 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

* / // % Multiplication, division, floor division,


and modulus

+ - Addition and subtraction

<< >> Bitwise left and right shifts

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

== != > >= < <= is is Comparisons, identity, and membership


not in not in operators

not Logical NOT

and AND

or OR

2. Write a program to implement control flow statements.


Python Conditions and If statements
Python supports the usual logical conditions from mathematics:
 Equals: a == b
 Not Equals: a != b
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops.
An "if statement" is written by using the if keyword.
Example
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
In this example we use two variables, a and b, which are used as part of the if statement to test
whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we
print to screen that "b is greater than a".
Indentation
Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other
programming languages often use curly-brackets for this purpose.
Example
If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
Elif
The elif keyword is Python's way of saying "if the previous conditions were not true, then try this
condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we
print to screen that "a and b are equal".
Else
The else keyword catches anything which isn't caught by the preceding conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this example a is greater than b, so the first condition is not true, also the elif condition is not true,
so we go to the else condition and print to screen that "a is greater than b".
You can also have an else without the elif:
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.
Example
One line if statement:
if a > b: print("a is greater than b")
Short Hand If ... Else
If you have only one statement to execute, one for if, and one for else, you can put it all on the same
line:
Example
One line if else statement:
a=2
b = 330
print("A") if a > b else print("B")
This technique is known as Ternary Operators, or Conditional Expressions.
You can also have multiple else statements on the same line:
Example
One line if else statement, with 3 conditions:
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
And
The and keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")

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])

my_function("Emil", "Tobias", "Linus")


Keyword Arguments
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")


5. Write a program to implement various types of functions.

Types of Functions in Python : There are two types of functions available in python. These are:

 Built-in Functions or Pre-defined


 User-defined Functions

1). Built-in Functions:

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.

Built-in Functions used in Python

Function name Description

len() It returns the length of an object/value.

list() It returns a list.

max() It is used to return maximum value from a sequence (list,sets) etc.

min() It is used to return minimum value from a sequence (list,sets) etc.

open() It is used to open a file.

print() It is used to print statement.

str() It is used to return string object/value.

sum() It is used to sum the values inside sequence.

type() It is used to return the type of object.


tuple() It is used to return a tuple.

Let’s see one example of built-in functions

#In built functions


x = [1,2,3,4,5]
print(len(x)) #it return length of list
print(type(x)) #it return object type

Output:

#5
# <class 'list'>

2). User-Defined Functions:

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.

Example of user-defined functions :

#Example of user defined function


x=3
y=4
def add():
print(x+y)
add()

Output:

#7

6. Write a program to implement recursion.


Recursion
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")


tri_recursion(5)
7. Write a program to implement command line arguments.
Command Line Input
Python allows for command line input.
That means we are able to ask the user for input.
The method is a bit different in Python 3.6 than Python 2.7.
Python 3.6 uses the input() method.
Python 2.7 uses the raw_input() method.
The following example asks for the user's name, and when you entered the name, the name gets
printed to the screen:
Python 3.6
print("Enter your name:")
x = input()
print("Hello ", x)

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.acos() Returns the arc cosine of a number

math.acosh() Returns the inverse hyperbolic cosine of a number

math.asin() Returns the arc sine of a number

math.asinh() Returns the inverse hyperbolic sine of a number

math.atan() Returns the arc tangent of a number in radians

math.atan2() Returns the arc tangent of y/x in radians

math.atanh() Returns the inverse hyperbolic tangent of a number

math.ceil() Rounds a number up to the nearest integer

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.cos() Returns the cosine of a number

math.cosh() Returns the hyperbolic cosine of a number

math.degrees() Converts an angle from radians to degrees

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

xpoints = np.array([0, 6])


ypoints = np.array([0, 250])

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):

# pass the regular expression


# and the string in search() method
if(re.search(regex, Ip)):
print("Valid Ip address")
else:
print("Invalid Ip address")
# Driver Code
if __name__ == '__main__' :
# Enter the Ip address
Ip = "192.168.0.1"
# calling run function
check(Ip)
Ip = "110.234.52.124"
check(Ip)
Ip = "366.1.2.2"
check(Ip)
Output:
Valid Ip address
Valid Ip address
Invalid Ip address
16. Write a program to demonstrate multi- threading.
# Python program to illustrate the concept
# of threading
# importing the threading module
import threading
def print_cube(num):
# function to print cube of given num
print("Cube: {}" .format(num * num * num))
def print_square(num):
# function to print square of given num
print("Square: {}" .format(num * num))
if __name__ =="__main__":
# creating thread
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(10,))
# starting thread 1
t1.start()
# starting thread 2
t2.start()
# wait until thread 1 is completely executed
t1.join()
# wait until thread 2 is completely executed
t2.join()
# both threads completely executed
print("Done!")
out put Square: 100
Cube: 1000
Done

You might also like