Professional Documents
Culture Documents
Operators
Operators are symbols that perform some operations.
E.g.
5+3
Types of Operators
1. Unary Operator
It has one operator and one operand.
E.g.
a = 10
b = -a
2. Binary Operator
It has one operator and two operands.
E.g.
5+3
3. Ternary Operator
It has one operator and three operands.
Categories of Operator
1. Arithmetic Operator
It performs arithmetic operations.
Operator Called as Example
+ Addition 5+3=8
- Subtraction 5–3=2
* Multiplication 5 * 3 = 15
/ Float Division 5 / 3 = 1.66
// Integer Division 5 // 3 = 1
% Modulus 5%3=2
** Exponent 5 ** 3 = 125
2. Relational Operator
It compares 2 or more operands.
It is used in Decision Making.
It returns true or false value.
Operator Called as Example
< less than 5 < 3 false
> greater than 5 > 3 true
<= less than or equal to 5 <= 3 false
>= greater than or equal to 5 >= 3 true
== equals to 5 == 3 false
!=
5 != 3 true
or not equal to
5 <> 3 true
<>
3. Logical Operators
It is used to combine 2 0r more operands.
Its operation is based on truth table.
Operator Called as Explanation
returns true it both the operands returns true otherwise
and Logical AND
false
or Logical OR returns true if any one operand returns true
not Logical NOT reverse the logical state of operand
Truth Table
AND OR EX-OR
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
4. Assignment Operator
It assigns the value in the LHS to a variable in the RHS.
Operator Called as Example
= assignment a = 100
5. Compound Assignment Operator
When assignment operator pairs with some other operator it is called as compound assignment operator.
E.g.
a = a + 5 can be written as a += 5
Here += is called as compound assignment operator.
6. Membership Operator
It specifies whether an operand is present in sequence or not.
E.g.
list = [1, 2, 3, 4, 5]
3 in list true
9 in list false
3 not in list false
9 not in list true
7. Identity Operator
It checks whether 2 objects points to a same memory location or not.
E.g.
8. Bitwise Operator
It operates on bits.
It is used to code electronic appliances
Operator Called as Explanation
& Bitwise AND
Similar to logical operator but it operates on bits
| Bitwise OR
returns true if both operands have different values,
^ Bitwise XOR
otherwise false
~ Bitwise NOT Similar to Logical NOT operator
<< Left Shift Shifts bits towards left up to specified position
>> Right Shift Shifts bits towards right up to specified position
2.Decision Making and Branching
Decision Making is used to specify the order in which statements are executed.
‘if ‘ statements
syntax
if(condition)
statements
statement x
Explanation
If the condition is true, the ’if’ loop will get execute and then statement x will get execute.
If the condition is false, the ‘if’ loop will get skipped and then statement x will get execute.
E.g. Output
a = int(input("enter a value")) enter a value 5
if(a < 10) : a is single digit number
print("a is single digit number")
‘if … else’ statement
syntax
if(condition) :
statements
else :
statements
statement x
Nested if statements
It is used in situation where a condition holds another condition.
E.g.
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
3. Looping
Looping is used to iterate through the sequence.
1. while
Syntax
while(condition) :
statements
else:
statements
statement x
Explanation
Until the condition is true while loop will get execute. When the condition is false while loop will get skipped and
else block will get execute.
E.g.
i=1
while(i <= 10) :
print(i)
i += 1
2. for loop
Syntax Flowchart
for i in sequence : for i in range(limit):
statements statements
else: else:
statements statements
statement x statement x
Explanation
Until the sequence or range has limits the ‘for’ loop will get execute. If not for loop will get skipped and else
block will get execute.
E.g.
for i in range(1,11) :
print(i)
3. Nested loop
Nested loop means a loop exist inside a loop.
The loop which encloses another is called outer loop and the loop inside a loop is called inner loop.
Once we step in to inner loop, it has to be executed fully.
E.g.
Refer matrix program in list
4. break
The break statement terminates the loop (for and while loop) immediately when it is encountered
E.g.
for i in range(1,11) :
if(i == 5) :
break
print(i)
5. continue
The continue statement skips some statements inside the loop and move on to the next iteration.
E.g.
for i in range(1,11) :
if(i == 5):
continue
print(i)
6. pass
The pass statement is null statement. Nothing will happen when it executes.
E.g.
for i in range(1,11) :
pass
print(i)
4. Function
A Function is a set of code which will get execute when we call it.
Advantages of Function
It avoids the repetition of code.
We can modify the code easily.
Modular programming.
Function call
A function is a dormant entity. It will not get execute until we call it.
Call a function by its name.
Parameter
A parameter is a kind of variable which is used to pass a value to a function.
1. Actual Parameters
The parameters appear in the function call is called actual parameter
2. Formal Parameters
The parameters appear in the function definition is called as formal parameter
Scope of variable
It defines the area where variables are accessible.
1. Local Variable
A variable defined inside a block and it is restricted to that particular block only.
2. Global Variable
A variable which is defined outside the blocks and we can access these variables anywhere in a program.
Example for Function
def add(x,y):
c=x+y
print("the addition is : %d" % c)
a = int(input("enter a value \n"))
b = int(input("enter a value \n"))
add(a,b)
Function Composition
If a function calls another function then it is called as function composition.
E.g.
def function_1():
function_2()
def function_2():
print("This is function composition.... ")
function_1()
Output:
This is function composition....
Recursion
A function calling itself is called as recursion.
E.g.
def fact(val):
if(val == 1):
return 1
else:
return val*fact(val-1)
a = int(input("enter a number to find factorial"))
ans = fact(a)
print("The factorial is : %d" % ans)
Output:
enter a number to find factorial
5
The factorial is : 120
Return
Return is a keyword which passes a value to the place where a function call is being made.
fruitful function void function
A function which returns a value is called fruitful A function which does not return a value is called void
function. function.
E.g. E.g.
def add(x,y): def add(x,y):
c=x+y c=x+y
return c print("the addition is : %d" % c)
a = int(input("enter a value \n")) a = int(input("enter a value \n"))
b = int(input("enter a value \n")) b = int(input("enter a value \n"))
ans = add(a,b) add(a,b)
print("the addition is : %d" % ans)
Output: Output:
enter a value enter a value
10 10
enter a value enter a value
20 20
the addition is : 30 the addition is : 30
5. String
String is a sequence of characters.
String values are enclosed within quotes.
E.g
string = “arun”
string = ‘arun’
Accessing Elements
The characters in a string can be accessed by its index. The indices are starts with 0 and ends with n – 1,
where n is number of characters.
The first character in a string can be accessed as string[0], The second character in a string can be
accessed as string[1], The nth character in a string can be accessed as string[n-1].
E.g.
We can use negative values (-) to access characters. Negative values are travel from the end.
List membership
It is used to check whether a character is present in the string or not.
E.g
List Slices
The Slice will return a portion of string which is called as substring.
Syntax
Name_of_the_string[starting_index : ending_index]
The ending_index will end 1 before the given value.
E.g.
String Operations
1. Concatenation (+)
The ‘+’ symbol will joins 2 or more string together and produce a new string.
2. Productivity (*)
The ‘*’ symbol will repeat a string by number of times specified.
E.g.
String Functions
1. len(str)
returns number of characters in a string
E.g.
2. max(str)
return a character which has maximum value.
E.g.
3. min(str)
return a character which has minimum value.
E.g.
String Methods
1. upper()
Converts characters in string to upper case.
E.g.
2. lower()
Converts characters in string to lower case.
E.g.
3. capitalize()
Converts the first characters in string to upper case.
E.g.
5. swapcase()
In a string, it converts lowercase to uppercase and the uppercase to lowercase.
E.g.
6. isdigit()
returns whether the give string has digit or not.
E.g.
7. join(sequence)
joins given characters using separator and returns a string
E.g.
8. strip()
removes space on both ends.
9. lstrip()
removes space on left end.
10. rstrip()
removes space on right end.
E.g.
Mutability
String is immutable. Changing the value of a particular character in the string is not possible.
E.g
Looping in String
We can use loops to iterate strings.
E.g. 1.
Here ‘i’ will have value of elements.
E.g. 2.
Here ‘i’ will have value of index.
Triple Quotes
Triple Quoters is used to enclosed string which span multiple lines.
Triple Quotes can be three single quotes or three double quotes.
E.g.
string = ‘’’ I am XXX
I am doing mechanical \n
I am from YYY’’’
String Module
String functions and methods are created by python developers and shipped in a folder called ‘string’.
To use those do ‘import string’.
E.g.
import string
print(string.upper(‘arun’)) # ARUN
print(string.lower(‘ARUN’)) # arun
print(string.count(‘arun’, ‘n’)) #1
print(string.replace(‘arun’, ‘ru’, ‘ur’)) #aurn
6. List
List is a sequence of values of different data types.
List values are enclosed within square brackets([ ])
E.g
list = [‘arun’, 23, 156.6, [23, 5, 93]]
The values in a list are called as elements.
Accessing Elements
The elements in a list can be accessed by its index. The indices are starts with 0 and ends with n – 1,
where n is number of elements.
The first element in a list can be accessed as list[0], The second element in a list can be accessed as
list[1], The nth element in a list can be accessed as list[n-1].
E.g.
We can use negative values (-) to access elements. Negative values are travel from the end.
List membership
It is used to check whether a particular element is present in the list or not.
E.g
List Slices
The Slice will return a portion of list elements.
Syntax
Name_of_the_list[starting_index : ending_index]
The ending_index will end 1 before the given value.
E.g.
List Operations
1. Concatenation (+)
The ‘+’ symbol will joins 2 or more list together and produce a new list.
2. Productivity (*)
The ‘*’ symbol will repeat a list by the times of number specified.
E.g.
List Methods
1. len( )
The len( ) method will return the number of element in a list.
Syntax:
list.len( )
E.g.
2. append( )
The append( ) method will add an element at the end of list.
Syntax:
list.append(element)
E.g.
3. insert( )
The insert( ) method will add an element in a list at a specified index.
Syntax:
list.insert(index, element)
E.g.
4. extend( )
The extend( ) method will add a new list to the list.
Syntax:
list1.extend(list2) # adds list2 with list1.
E.g.
5. del( )
del( ) is used to remove an element from list
E.g.
6. pop( )
The pop( ) method will return the last element if index is not specified. If index is specified it returns the
particular element.
Syntax:
list.pop( ) # it will pop the last element.
list.pop(2) # it will pop the 2nd element.
E.g.
7. remove( )
When specified the element name, it will remove that particular element from list.
Syntax:
list.remove(element)
E.g.
8. reverse( )
This method will reverse the element in the given list.
Syntax:
list.reverse( )
E.g.
9. sort( )
This method will sort the elements in an ascending order.
Syntax:
list.sort( )
E.g.
10. count( )
When specified an element it will return the number of particular element present in list.
Syntax:
list.count(element)
E.g.
Mutability
List is mutable. Changing the value of a particular element in the list is possible.
We can use slice here.
E.g
Looping in List
We can use loops to iterate list values.
E.g. 1.
Here ‘i’ will have value of elements.
E.g. 2.
Here ‘i’ will have value of index.
List Alias
List Alias is making two lists to refer a single object. If one list alters the object it will reflect in others.
E.g.
List Cloning
List Cloning is copying a list object. If one gets altered it will not reflect in second.
E.g.
List as Parameters
We can pass a list as a parameter but it acts like a reference. A change function definition will reflect in
function call.
E.g.
List as Array
Nested list can act as arrays. The following array can be written as
Tuple Assignment
Python allows a Tuple of values in LHS can be assigned to Tuple of variables in RHS.
E.g.
(a, b, c, d, e) = (1, 2, 3, 4, 5)
Another way of Tuple assignment is Tuple packing / unpacking.
In Tuple packing, the values on the left are ‘packed’ together in a Tuple. In Tuple unpacking, the values
in a Tuple on the right are ‘unpacked’ into the variables/names on the left.
E..g
x = (1, 2, 3, 4, 5) # Packing
(a, b, c, d, e) = x # Unpacking
Tuple as return values
Functions always return a single value, but by making that value as Tuple, we can return as many values
as we like.
E.g.
def fn(r) :
area = 3.14 * r * r
cir = 2 * 3.14 * r
return (area, cir)
radius = 10
(x, y) = fn(radius)
print(“the area is”, x)
print(“the circumference is”, y)
8. Dictionary
Dictionaries are list but its indexes are not only integers.
Dictionary has key, value pair. Each key is separated from values using colon (:).
Creating Dictionary
E.g.
Updating Values
Dictionaries are Mutable. We can change existing value in dictionary. But keys are immutable. We can’t
change them.
E.g.
Deleting Element
E.g.
Membership
‘age’ in D # True
E.g.
9.Files
Files are persistent storage which has sequence of data of similar data types.
File Modes
It defines what for the file is being opened.
r opens file for read
r+ opens file for read and write
rb opens file for read in binary format
rb+ opens file for read and write in binary format
w opens file for write
w+ opens file for read and write
wb opens file to write in binary format
wb+ opens file for read and write in binary format
a opens file for write
a+ opens file for read and write
ab opens file for write in binary format
ab+ opens file for read and write in binary format
Difference between append and write
Append will keep the existing data but write doesn’t.
File Operations
1. Opening a file
Before any operation we have to open the file.
The syntax for opening a file is,
file_object = open(“Filename”, “Filemode”)
2. Closing a file
After completing any operation we have to close the file.
The syntax for closing a file is,
file_object.close( )
3. Writing data into files
The inbuilt method to write data into file is write( )
It writes string alone into the file.
It will not move to next line until we provide ‘\n’ while writing data into files.
The syntax for writing data into file is
file_object.write(“string to write”)
4. Reading data from files
The inbuilt method to read data from file is read( )
It reads data as string.
The different methods to read data from file is
file_object.read( ) # it will read entire file
file_object.read(count ) # it will read the number of characters specified as count
file_object.readline( ) # it will read first line alone
file_object.readlines( ) # it will read the entire file
File Positions
1. tell( )
It will tell the current position of the file pointer.
The syntax is,
file_object.tell( )
2. seek( )
It will move the file pointer to a specified location.
The syntax is
file_object.seek(offset[, from])
‘offset’ specified how many characters to be moved
The ‘from’ has 3 values
‘0’ – move file pointer to the starting of file
‘1’ – place the file pointer where it is
‘2’ – move file pointer to the end of file
Looping files
We can iterate through file using file_object and the syntax is,
for iterate_variable in file_object :
# operations
File Attributes
1. file_object.closed( ) - defines whether file is closed or not
2. file_object.mode( ) - returns file mode
3. file_object.name( ) - returns file name
Directories in Python
Directories are location in our system which has files of same type.
Directories Methods
Before to operate on methods do ‘import os’
getcwd( ) - returns current working directory
mkdir(directory_name) - create new directory
chdir(directory_name) - change the given directory as current directory
rmdir(directory_name) - remove the specified directory from the computer
File methods related to OS
1. rename(oldname, newname) - change the name of file specified
2. remove(filename) - removes the file from the computer
‘with’ Statement
File operations can do with the ‘with’ statements.
The advantage is, it will close the file automatically once the operation is completed
The syntax is,
with open(‘file_name’, ‘file_mode’) as file_object :
# operations
‘split( )’ method
The split( ) will break the file contents into a string using the delimiter specified.
The syntax is,
file_object.split(‘delimiter’)
Format Operator
Python files take only string values. If we want to write values other than string use format operators.
E.g.
E.g. 2
f = open("a.txt", "w")
f.write(str(42)) # converting integer to string using str()
f.write("%d" % 42) # converting integer to string using format operator
print("write operation completed")
Output
write operation completed
Errors and Exception
Errors
Errors are a resultant from bad code
Types of Error
1. Syntax Error
code that not conform to the syntax of programming language
These errors can be recognized by the compiler.
E.g.
2. Logic Errors
misinterpretation of logic is called logic error
3. Runtime Errors
A code which is syntactically correct but fails to run due to certain conditions occurred in our program
Exception
The runtime errors are called as Exception
What happened when Exception occurs?
The program terminates abnormally
How to handle the above situation?
Handle the Exception. The Exception handling will terminates the program normally.
Exception Handling
1. try
place the doubtful code inside try
the syntax is,
try:
# doubtful code
2. except
‘except’ will handle the exception
The syntax is,
except exception_type:
# exception handling code
Every ‘except’ statement have type and it will handle that specified exception alone.
It is possible to write ‘except’ without type. It will handle all kind of exception and the syntax is,
except:
# exception handling code
It is also possible to have multiple exception type in a single except as,
except exception_type1, exception_type2, …., exception_typeN
# exception handling code
‘except’ will have arguments which gives additional information about exception as,
except exception_type, argument:
# exception handling code
We can add as much ‘except’ statements below ‘try’
3. finally
Whether the exception occurs or not, the code inside the finally block will get execute.
The ‘finally’ block will have shut down operations.
The construct to handle exception handling is,
try:
# doubtful code
except exception_type:
# exception handling code
finally:
# shutdown operation
E.g.
PROGRAM OUTPUT
try: write operation completed
f = open("a.txt", "w+") 27
f.write("We are using Python..... \n") We are using Python.....
print("write operation completed") It is easy to learn
print(f.tell()) end of program
f.seek(0,2)
f.write("It is easy to learn")
print(f.read())
except:
print("Some problem occurred while reading the file...")
finally:
f.close()
print("end of program")
try: write operation completed
f = open("a.txt", "w") 27
f.write("We are using Python..... \n") Some problem occurred while reading
print("write operation completed") the file...
print(f.tell()) end of program
f.seek(0,2)
f.write("It is easy to learn")
print(f.read())
except:
print("Some problem occurred while reading the file...")
finally:
f.close()
print("end of program")
Modules
Modules are python files. We can use this file in another python files.
Consider the following file
We can use the above file in another file using import statement as
9. Binary Search
a = [1,2,3,4,5,6,7,8,9,10]
val = int(input("Enter a number to search \n"))
low = 0
high = len(a) - 1
while(low <= high):
mid = (low+high) / 2
if(val < a[mid]):
high = mid - 1
elif(val > a[mid]):
low = mid + 1
else:
print("the search element is at %d position" % (mid+1))
break
if(low > high):
print("The number is not present in list")
Output:
Enter a number to search
5
the search element is at 5 position
10. Selection Sort
def selection_sort(a):
for i in range(len(a)):
for j in range(i+1, len(a)):
if(a[i] > a[j]):
t = a[i]
a[i] = a[j]
a[j] = t
a = [5, 9, 8, 6, 2, 7, 10]
selection_sort(a)
for i in a:
print(i)
Output:
2 5 6 7 8 9 10
11. Insertion Sort
def insertion_sort(a):
for i in range(len(a)):
t = a[i]
j=i-1
while((t < a[j]) and (j >= 0)):
a[j+1] = a[j]
j=j-1
a[j+1] = t
a = [5, 9, 8, 6, 2, 7, 10]
insertion_sort(a)
for i in a:
print(i)
Output:
2 5 6 7 8 9 10
13. Histogram
def pypart(n):
for i in range(0, n):
for j in range(0, i+1):
print("* "),
print("\n")
n=5
pypart(n)
Output:
*
* *
* * *
* * * *
* * * * *