You are on page 1of 30

1.

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

Explanation E.g. Output


if the condition is true a = int(input("enter a value \n")) enter a value
 if loop will get execute if(a % 2 == 0): 10
 else will get skipped print("Given value is EVEN") Given value is EVEN
 then statement x will get execute else: ...end of program...
if the condition is false print("Given value is ODD") enter a value
 if loop will get skipped print("...end of program...") 11
 else loop will get execute Given value is ODD
 then statement x will get execute ...end of program...

Multiple ‘if … else’ statement


syntax
if (condition1) :
statement1
elif (condition2) :
statement2
elif (condition3) :
statement3
else :
statement4
statement x
Explanation
 Here, any one condition may true or all the conditions may false
 If any one condition is true that particular statements will get execute
 If all the conditions are false else part alone will get execute
E.g
mark = int(input("enter a mark \n")) Output
if(mark > 90): enter a mark
print("A Grade") 96
elif(mark > 75 and mark <= 90): A Grade
print("B Grade") ...end of program...
elif(mark >= 50 and mark <= 75): enter a mark
print("C Grade") 36
else: FAIL
print("FAIL") ...end of program...
print("...end of program...")

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.

4. find(string, beg, end)


 returns at what index the specified string is find.
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

To access the first row the code is


To access a single element from a list the code is

Matrix Multiplication Program


X = [[12, 7, 3], [4, 5, 6], [7, 8, 9]]
Y = [[5, 8, 1, 2], [6, 7, 3, 0], [4, 5, 9, 1]]
result = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
for i in range(len(X)):
for j in range(len(Y[0])):
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result: print(r)
List Comprehension
 List Comprehension is creating a list which is similar to set operations in mathematics.
 It will minimize the execution time compared to normal lists.
Syntax:
[expression for item in list if conditional]
The above syntax is similar to,
for item in list:
if conditional:
expression
E.g.
list = []
for i in range(1,11):
if(i%2 == 0):
list.append(i * 10)
print list
The above code can write as list comprehension as,
list = [i*10 for i in range(1,11) if(i%2 == 0)]
print list
7. Tuple
 Tuple is used to group data’s of different data types.
 Tuple values are surrounded by parentheses.
E.g.
a = (‘arun’, 23, 156.6)
A Tuple can write as,
a = ‘arun’, 23, 156.6
A single element Tuple can be written as, a = (25,) # Here, comma is important
Accessing Tuple elements
 As like list we can access Tuple elements using index.
E.g.
a = (‘arun’, 23, 156.6)
a[1] # prints 2nd element in Tuple
Mutability
 Tuple is immutable. We can’t change a value in Tuple.
E.g.

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

D={} # Empty Dictionary

D = {‘name’: ‘tara’, ‘age’: 23}

D = dict({‘name’: ‘tara’, ‘age’: 23}) #creating Dictionary using dict( ).

Accessing Value from Dictionary

 The Values from Dictionary are accessed by its keys.

E.g.

To print age from above dictionary, the code is

print(D[‘age’]) # prints value of ‘age’

Updating Values

 Dictionaries are Mutable. We can change existing value in dictionary. But keys are immutable. We can’t
change them.

E.g.

D[‘age’] = 32 # Now the value of age will change to 32

Deleting Element

 We can delete an element by passing its key to a function called del( ).

E.g.

del D[age] # It will delete a element with key ‘age’.

del D # It will delete entire dictionary.

Membership

 It returns whether an element with specified key value is present or not.


E.g.

‘age’ in D # True

‘name’ not in D # False

Operations and Methods

1. len(dict) returns length of dictionary.


2. type(dict) returns data type.
3. str(dict) returns dictionary as string.
4. dict.clear( ) removes all elements from Dictionary.
5. dict.keys( ) returns the keys from dictionary.
6. dict.values( ) return the values from dictionary.
7. dict.copy( ) copies elements in dictionary to another dictionary.
8. dict.has_key(key ) returns whether dictionary has the key.
9. dict.items( ) returns dictionary as list.
10. dict.update( ) adds a dictionary to another.

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

Importing files using ‘from’


We can import file using ‘from’ as

To import specific portion using ‘from’


Packages
Packages are namespaces which contains multiple packages and modules in it. Packages are simply a
directory. It must contain a special file called __init__.py(which can be empty file).
We can use packages in another python file using import statements as like modules.

10. Illustrative programs:


1. Exchange the values of two variables
a = int(input("enter a's value:"))
b = int(input("enter b's value:"))
(a,b) = (b,a)
print("After swapping... \n")
print("a's value is : %d" % a)
print("b's value is : %d" % b)
Output:
enter a's value:10
enter b's value:20
After swapping...
a's value is : 20
b's value is : 10
2. Circulate the values of n variables
def fn(list, i):
print(list[i:]+list[:i])
list = [1, 2, 3, 4, 5]
for i in range(len(list)):
fn(list, i)
Output:
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 1]
[3, 4, 5, 1, 2]
[4, 5, 1, 2, 3]
[5, 1, 2, 3, 4]
3. Distance between two points
import math
def fn(x1,x2,y1,y2):
print("The distance is %f" %
(math.sqrt((x1-x2)**2+(y1-y2)**2)))
x1 = int(input("enter x1:"))
y1 = int(input("enter y1:"))
x2 = int(input("enter x2:"))
y2 = int(input("enter y2:"))
fn(x1,x2,y1,y2)
Output:
enter x1: 5
enter y1: 10
enter x2: 15
enter y2: 20
The distance is 14.142136
4. Square Root
a = int(input("Enter a number\n"))
print("The square root is: %f" % (a**0.5))
Output:
Enter a number
5
The square root is: 2.236068
5. GCD
def gcd(a,b,small):
for i in range(1, small+1):
if((a%i==0)and(b%i==0)):
gcd = i
print("the gcd is:", gcd)
a = int(input("Enter 1st value\n"))
b = int(input("Enter 2nd value\n"))
if(a>b):
small = b
gcd(a,b,small)
else:
small = a
gcd(a,b,small)
Output:
Enter 1st value
10
Enter 2nd value
56
('the gcd is:', 2)
6. Exponentiation
import math
print(math.exp(100.12))
Output:
3.03084361407e+43
7. Sum of array
sum = 0
list = [34, 56, 23, 87, 43, 12, 28]
for i in list:
sum += i
print("the sum of array is: %d" % sum)
Output:
the sum of array is: 283
8. Linear Search
a = [23, 13, 56, 34, 67, 48, 90, 21, 75, 83]
val = int(input("Enter a number to search \n"))
count = 0
for i in range(len(a)):
if(val == a[i]):
print("The searching element is at %d position" % (i+1))
count += 1
if(count == 0):
print("The number is not present in list")
Output:
Enter a number to search
34
The searching element is at 4 position

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

* *

* * *

* * * *

* * * * *

14. Word Count


with open('input.txt') as f:
for i in f:
count = i.split()
print("The number of words is :", (len(count)))
Output:
The number of words in file is : 31
15. File Copy
with open('input.txt') as f:
with open('output.txt', 'w') as ff:
for i in f:
ff.write(i)
print(“File Copied”)
Output:
File Copied

You might also like