PYTHON NOTES Bca - Final
PYTHON NOTES Bca - Final
PYTHON NOTES Bca - Final
DONBOSCO COLLEGE
Kottiyam,Kollam,Kerala
(Affiliated to the University of Kerala)
Name : ……………………………………………………………………………………………
MODULE III
Introduction to Python
Characteristics of Python
Advantages of Python
Features in Python
There are many features in Python, some of which are discussed below
–
1.Easy to code:
Python is high level programming language.Python is very easy to learn
language as compared to other language like c, c#, java script, java
etc.It is very easy to code in python language and anybody can learn
python basic in few hours or days.It is also developer-friendly
language.
2. Free and Open Source:
3.Object-Oriented Language:
Keywords in Python
• These keywords have a special meaning and they are used for
special purposes in Python programming language.
• For example – Python keyword “while” is used for while loop thus
you can’t name a variable with the name “while” else it may cause
compilation error.
• There are total 33 keywords in Python
Python Comments
Example
#This is a comment
print("Hello, World!")
Python does not really have a syntax for multi line comments.To add
a multiline comment you could insert a # for each line or make the
comments inside three quotes.
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Example:
print(“Welcome to
Python”)
print(a)
String Formatting:
s= "Kiran"
age=25
• Here we use the input() function which allows the user to input
the values in the programme.
• Whenever you input a value in the programme with the help of
input() function the value is treated as a string and what if you
want to enter an integer or float for that you need to convert it
into corresponding data type
Syntax1: variable =
input()
Example:
a=input()
Import in Python:
Output:
Enter a Number:25
5
Operators in Python
Types of Operator
Python language supports the following types of operators.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Membership Operators
6. Identity Operators
1.Arithmetic Operators
Assume variable a holds 10 and variable b holds 20, then –
not Logical Used to reverse the logical state of its Not(a and
NOT operand. b) is false.
5.Membership Operators
Python’s membership operators test for membership in a sequence,
such as strings, lists, or tuples. There are two membership operators
as explained below −
Operator Description Example
Data Types
The data stored in memory can be of many types. For example, a
person's age is stored as a numeric value and his or her address is
stored as alphanumeric characters. Python has various standard
data types that are used to define the operations possible on them
and the storage method for each of them.
Python has five standard data types −
• Numbers
• String
• List
• Tuple
• Dictionary
1.Numbers
Number data types store numeric values. Number objects are created
when you assign a value to them. For example −
var1 = 1
var2 =
10
Python supports four different numerical types −
3.Lists
Lists are the most versatile of Python's compound data types. A list
contains items separated by commas and enclosed within square
brackets ([]). To some extent, lists are similar to arrays in C. One
difference between them is that all the items belonging to a list can
be of different data type.
The values stored in a list can be accessed using the slice operator ([
] and [:]) with indexes starting at 0 in the beginning of the list and
working their way to end -1. The plus (+) sign is the list concatenation
operator, and the asterisk (*) is the repetition operator. For example
−
Example
s=
"10010"
Output:
After converting to integer base 2 : 18
After converting to float : 10010.0
3. ord() : This function is used to convert a character to integer.
4. hex() : This function is to convert integer to hexadecimal string.
5. oct() : This function is to convert integer to octal string.
Exampl
e:
# initializing integer
s = '4'
c = ord(s)
print ("After converting character to integer : ")
print (c)
Output:
After converting character to integer : 52
After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70
Exampl
e:
# initializing string
s = 'geeks'
Examp
le
# initializing integers
a = 1
b = 2
Example:
print(a)
print(b)
Output:
L
M
A = ['t','u','t','o','r','i','a','l'] for i in
range(len(A)):
min_ = j
#swap
A[i], A[min_] = A[min_], A[i]
# main for i in
range(len(A)):
print(A[i])
Output
ai
lo
rt
tu
range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are greater
than key,
arr[j+1] = arr[j] j
-= 1 arr[j+1] = key
print (arr[i])
Output
The sorted array is:
a
i
l
o
r
t
t
u
Step1:
The same process goes on for the remaining iterations. After each
iteration, the largest element among the unsorted elements is placed
at the end.
In each iteration, the comparison takes place up to the last unsorted
element.
DONBOSCO COLLEGE Page 28
CP1442: WEB PROGRAMMING & PYTHON
The array is sorted when all the unsorted elements are placed at
their correct positions.
MODULE IV
1.if Statements
It consists of a Boolean expression which results are either TRUE or
FALSE, followed by one or more statements.
Synatx:
if expression:
#execute your code
Example:
a = 15 if
a > 10:
print("a is greater")
Output:
a is greater
Synatx:
if expression:
#execute your code
else:
#execute your code
Example:
a = 15 b = 20
if a > b:
print("a is greater")
else:
print("b is greater")
Output:
b is greater
3.elif Statements
Example: if expression:
#execute your code
elif expression:
#execute your code
else:
#execute your code
Example:
a = 15
b = 15
if a > b:
print("a is greater")
elif a == b:
print("both are equal")
else:
print("b is greater")
Output:
both are equal
looping in Python
3 nested loops
You can use one or more loop inside any another while, for or
do..while loop.
1.While Loop
• A while loop statement in Python programming language
repeatedly executes a target statement as long as a given
condition is true.
DONBOSCO COLLEGE Page 35
CP1442: WEB PROGRAMMING & PYTHON
Synatx:
while expression:
#execute your code
Example:
count =1 while
count < 6 :
print (count)
count+=1
Output:
1
2
3
4
5
2.for loop
It has the ability to iterate over the items of any sequence, such
3.Nested Loop
Example:
for g in range(1, 6):
for k in range(1, 3):
print ("%d * %d = %d" % ( g, k, g*k))
Output:
1*1=1
1* 2 = 2
2* 1=2
2* 2=4
3* 1=3
3* 2=6
4* 1=4
4* 2=8
5* 1=5
5 * 2 = 10
Sytanx:
break
Example:
i=0
while i <= 10:
print (i)
i++ if i
== 3:
break
Output:
0
1
2
Sytanx:
continue
Example:
i=0
while i <= 10:
print (i)
i++ if i
== 3:
continue
Output:
0
1
2
4
5
6
7
8
9
10
3.Pass statement:-
It is used in Python to when a statement is required syntactically,
and the programmer does not want to execute any code block or
command.
It is used when a statement is required syntactically but you do not
want any command or code to execute.
The pass statement is a null operation; nothing happens when it
executes. The pass statement is also useful in places where your
code will eventually go, but has not been written yet i.e. in stubs.
Syntax:
pass
Example
for i in 'Python': if i
== 'h':
pass print ('This is pass
block') print ('Current Letter :', i)
Python functions
A function is a block of organized, reusable code that is used to
perform a single, related action. Functions provide better modularity
for your application and a high degree of code reusing.
You can define functions to provide the required functionality. Here
are simple rules to define a function in Python.
Syntax
def functionname( parameters
): “function body” return
[expression]
By default, parameters have a positional behavior and you need to
inform them in the same order that they were defined.
Example
The following function takes a string as input parameter and prints
it on standard screen.
def printme( str ):
print str return
Calling a Function
Defining a function only gives it a name, specifies the parameters
that are to be included in the function and structures the blocks of
code.
Once the basic structure of a function is finalized, you can execute
it by calling it from another function or directly from the Python
prompt. Following is the example to call printme() function −
def printme(a):
print a
return;
Scope of Variables
All variables in a program may not be accessible at all locations in
that program. This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where
you can access a particular variable. There are two basic scopes of
variables in Python −
• Global variables
• Local variables
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
1.Required arguments
Required arguments are the arguments passed to a function in
correct positional order. Here, the number of arguments in the
function call should match exactly with the function definition.
To call the function printme(), you definitely need to pass one
argument, otherwise it gives a syntax error as follows −
# Function definition is here
def printme( a ): print(a)
return;
Output:
Name: lal Age:
50
2.Default arguments
A default argument is an argument that assumes a default value if a
value is not provided in the function call for that argument. The
following example gives an idea on default arguments, it prints
default age if it is not passed −
# Function definition is here def
printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name print "Age ", age return;
Anonymous Functions
These functions are called anonymous because they are not declared
in the standard manner by using the def keyword. You can use the
lambda keyword to create small anonymous functions.
• Lambda forms can take any number of arguments but return
just one value in the form of an expression. They cannot contain
commands or multiple expressions.
• An anonymous function cannot be a direct call to print because
lambda requires an expression
• Lambda functions have their own local namespace and cannot
access variables other than those in their parameter list and
those in the global namespace.
Syntax
The syntax of lambda functions contains only a single statement,
which is as follows −
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works
−
# Function definition is here sum =
lambda arg1, arg2: arg1 + arg2;
Output
The factorial of 3 is 6
String in Python
Example
Syntax:
• slice(stop)
• slice(start, stop, step)
Parameters:
DONBOSCO COLLEGE Page 49
CP1442: WEB PROGRAMMING & PYTHON
start: Starting index where the slicing of object starts. stop: Ending
index where the slicing of object stops. step: It is an optional
argument that determines the increment between each index for
slicing.
Example:
String
='ASTRING' s1
= slice(3) s2 =
slice(1, 5)
s3 = slice(-1, -7, -3)
print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])
Output:
String slicing
AST
STRI
GR
2.Extending indexing
Example
String ='ASTRING' #
Using indexing
sequence
print(String[:3])
print(String[1:5:2])
print(String[-1:-12:-2])
# Prints string in
reverse
print("\nReverse
String")
print(String[::-1])
Output:
AST
SR
GITA
Reverse String
GNIRTSA
String Immutability
t[0] = "M"
TypeError: 'str' object does not support item
assignment String Functions in Python
Python provides lots of built-in methods which we can use on
strings.Below are the list of string methods available in Python 3.
Method Description Examples
interpreted
as in slice >>> print(mystr.count("l"))
notation. 2
>>> print(mystr.count("h"))
1
>>> print(mystr.count("H"))
1
>>>
print(mystr.count("hH")) 0
>>> print(a.isalpha())
False
>>> a= "$*%!!!"
>>> print(a.isalpha())
False
Islower()
>>> c="Python"
>>> print(c.isnumeric())
False
isspace()
Python"))
H**e**l**l**o**
**P**y**t**h**o**n
lower() Converts a
string into lower >>> a = "Python"
case >>> print(a.lower())
Python
upper() Converts a
string into upper >>> mystr = "hello Python"
case >>> print(mystr.upper())
HELLO PYTHON
String Module
• The string module provides additional tools to manipulate
strings.
• It’s a built-in module and we have to import it before using
any of its constants and classes. Python String Module
Classes-Python string module contains two classes – 1.
Formatter 2. Template.
1.Formatter
It behaves exactly same as str.format() function. This class become
useful if you want to subclass it and define your own format string
syntax
Example:
formatter = Formatter()
print(formatter.format('{website}',
website='JournalDev')) print(formatter.format('{}
{website}', 'Welcome to', website='JournalDev'))
Example:
List as Arrays
• During programming, there will be instances when you will
need to convert existing lists to arrays in order to perform
certain operations on them (arrays enable mathematical
operations to be performed on them in ways that lists do not).
np.array(my_list) #
printing my_array
print my_array
# printing the type of
my_array print
type(my_array) Output:
[ 2 4 6 8 10]
<type 'numpy.ndarray'>
2. Using numpy.asarray()
This function calls the numpy.array() function inside itself. See the
definition below
import numpy as np
my_list =
[2,4,6,8,10]
my_array =
np.asarray(my_list)
# printing
my_array print
my_array
# printing the type of
my_array print
type(my_array)
Output:
[2 4 6 8
10]
<type
'numpy.ndarray'>
Output
Square root of a is 10
Square root of b is 2.645
Square root of c is 9
Python program to find gsd of two numbers
Syntax: gcd(x,y)
Example of gcd()
In the below example we print the result of gcd of a pair of integers.
",math.gcd(-24, -18))
Output
Running the above code gives us the following result −
GCD of 75 and 30 is 15
GCD of 0 and 12 is 12
GCD of 0 and 0 is 0
GCD of -24 and -18 is 6
output:
Exponential value is
81
output
i in range(len(arr)): if
arr[i] == x:
Recursive
Algorithm Example
def binarySearchAppr (arr, start, end, x):
# check condition if
end >= start:
mid = start + (end- start)//2 # If
element is present at the middle if
arr[mid] == x:
return mid
# If element is smaller than mid elif
arr[mid] > x:
return binarySearchAppr(arr, start, mid-1, x)
# Else the element greator than mid
else:
return binarySearchAppr(arr, mid+1, end, x) else:
# Element is not found in the array
return -1
arr = sorted(['t','u','t','o','r','i','a','l']) x ='r' result =
binarySearchAppr(arr, 0, len(arr)-1, x) if result
!= -1:
print ("Element is present at index "+str(result)) else:
print ("Element is not present in array")