Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PYTHON NOTES Bca - Final

Download as pdf or txt
Download as pdf or txt
You are on page 1of 67

CP1442: WEB PROGRAMMING & PYTHON

DONBOSCO COLLEGE
Kottiyam,Kollam,Kerala
(Affiliated to the University of Kerala)

CP1442: WEB PROGRAMMING & PYTHON


S4 BCA

Name : ……………………………………………………………………………………………

Reg No: ……………………………………………………………………………..

DONBOSCO COLLEGE Page 1


CP1442: WEB PROGRAMMING & PYTHON

CP1442: WEB PROGRAMMING & PYTHON:-


SYLLABUS

Module III: Introduction to Python- Features of Python - Identifiers -


Reserved Keywords - Variables Comments in Python – Input , Output
and Import Functions - Operators – Data Types and Operations – int,
float, complex, Strings, List, Tuple, Set,Dictionary - Mutable and
Immutable Objects – Data Type Conversion - Illustrative programs:
selection sort,insertion sort, bubble sort

Module IV: Decision Making -conditional (if), alternative (if-else),


if..elif..else -nested if - Loops for,range() while, break, continue, pass;
Functions: return values, parameters, local and global scope, function
composition, recursion; Strings: string slices, immutability, string
functions and methods, string module; Lists as arrays.

DONBOSCO COLLEGE Page 2


CP1442: WEB PROGRAMMING & PYTHON

MODULE III

Module III: Introduction to Python- Features of Python - Identifiers -


Reserved Keywords - Variables Comments in Python – Input , Output
and Import Functions - Operators – Data Types and Operations – int,
float, complex, Strings, List, Tuple, Set,Dictionary - Mutable and
Immutable Objects – Data Type Conversion - Illustrative programs:
selection sort,insertion sort, bubble sort

Introduction to Python

• Python is a general-purpose interpreted, interactive, object-


oriented, and high-level programming language. It was created by
Guido van Rossum during 1985- 1990.
• Python is easy to learn yet powerful and versatile scripting
language, which makes it attractive for Application Development.
• Python's syntax and dynamic typing with its interpreted nature
make it an ideal language for scripting and rapid application
development.

Characteristics of Python

• It supports functional and structured programming methods as


well as OOP.
• It can be used as a scripting language or can be compiled to byte-
code for building large applications.
• It provides very high-level dynamic data types and supports
dynamic type checking.
• It supports automatic garbage collection.

DONBOSCO COLLEGE Page 3


CP1442: WEB PROGRAMMING & PYTHON

• It can be easily integrated with C, C++, COM, ActiveX, CORBA,


and Java.

Advantages of Python

1. Python is Interpreted − Python is processed at runtime by the


interpreter. You do not need to compile your program before
executing it. This is similar to PERL and PHP.
2. Python is Interactive − You can actually sit at a Python prompt
and interact with the interpreter directly to write your programs.
3. Python is Object-Oriented − Python supports Object-Oriented
style or technique of programming that encapsulates code within
objects.
4. Python is a Beginner's Language − Python is a great language for
the beginner-level programmers and supports the development of a
wide range of applications from simple text processing to WWW
browsers to games.

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:

Python language is freely available at official website.Since, it is open-


source, this means that source code is also available to the public.So
you can download it as, use it as well as share it.

DONBOSCO COLLEGE Page 4


CP1442: WEB PROGRAMMING & PYTHON

3.Object-Oriented Language:

One of the key features of python is Object-Oriented


programming.Python supports object oriented language and concepts
of classes, objects encapsulation etc.
4. GUI Programming Support:

Graphical Users interfaces can be made using a module such as PyQt5,


PyQt4, wxPython or Tk in python.PyQt5 is the most popular option for
creating graphical apps with Python.
5. High-Level Language:

Python is a high-level language. When we write programs in python, we


do not need to remember the system architecture, nor do we need to
manage the memory.
6.Extensible feature:
Python is a Extensible language. we can write our some python code into
c or c++ language and also we can compile that code in c/c++ language.
7. Python is Portable language:

Python language is also a portable language.for example, if we have


python code for windows and if we want to run this code on other
platform such as Linux, Unix and Mac then we do not need to change
it, we can run this code on any platform.
8. Python is Integrated language:

Python is also an Integrated language because we can easily integrated


python with other language like c, c++ etc.
9. Interpreted Language:

Python is an Interpreted Language. because python code is executed


line by line at a time. The source code of python is converted into an
immediate form called bytecode.

DONBOSCO COLLEGE Page 5


CP1442: WEB PROGRAMMING & PYTHON

10. Large Standard Library


Python has a large standard library which provides rich set of module
and functions so you do not have to write your own code for every
single thing.There are many libraries present in python for such as
regular expressions, unit-testing, web browsers etc.
11. Dynamically Typed Language:

Python is dynamically-typed language. That means the type (for


example- int, double, long etc) for a variable is decided at run time not
in advance.because of this feature we don’t need to specify the type of
variable.
Python Identifiers
An identifier is a name given to entities like class, functions,
variables, etc. It helps to differentiate one entity from another.
Example: a=10

Rules for writing identifiers

1. Identifiers can be a combination of letters in lowercase (a to z) or


uppercase (A to Z) or digits (0 to 9) or an underscore _. Names like
myClass, var_1 and print_this_to_screen, all are valid example.
2. An identifier cannot start with a digit. 1variable is invalid, but
variable1 is a valid name.
3. Keywords cannot be used as identifiers.
4. We cannot use special symbols like !, @, #, $, % etc. in our
identifier.
5. An identifier can be of any length.

Keywords in Python

• A python keyword is a reserved word which you can’t use as a


name of your variable, class, function etc.

DONBOSCO COLLEGE Page 6


CP1442: WEB PROGRAMMING & 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

• Comments can be used to explain Python code.


• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing code.
• Comments starts with a #, and Python will ignore them:

Example
#This is a comment
print("Hello, World!")

Multi Line Comments

DONBOSCO COLLEGE Page 7


CP1442: WEB PROGRAMMING & PYTHON

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!")

Or, not quite as intended, you can use a multiline string.


Since Python will ignore string literals that are not assigned to a
variable, you can add a multiline string (triple quotes) in your code,
and place your comment inside it:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

Python Output Function

• In python, if you want to show something on screen as an output,


there we use the print() function. Using the print() function you
can show the output data on your standard screen.
• Normally print() function is used to show the output data of
variables and strings.

Example:
print(“Welcome to
Python”)
print(a)

DONBOSCO COLLEGE Page 8


CP1442: WEB PROGRAMMING & PYTHON

String Formatting:

• There is a special function called format() which is used with a


string, that gives you more flexibility over the print() function.
format() function is used with a string and you can insert variables
in specific places of that particular string.
• We use {} curly brackets to hold the places of variables or string
that pass in the format() function.
• Example

s= "Kiran"

age=25

print("My name is {} and I am {} years old ". format(s,age))

Output: My name is Kiran and I am 25 years old

Python Input Function

• 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()

DONBOSCO COLLEGE Page 9


CP1442: WEB PROGRAMMING & PYTHON

Syntax2: variable = input(“Prompt”)


Example:
a=input(“Enter the value”)

The prompt is a string which is used as a message that displays on the


screen

Import in Python:

• Import is a keyword which is used to import the definitions of the


module (modules are the python files which contain the
prewritten code or function) in the current file. Import keyword is
used along with another keyword from which is used to import the
module
• Suppose you want a programme which accepts an integer and
give the square root of the integer. For this, you can make a
program or you can use a predefined function sqrt() which is a
part of module math. So to use the sqrt() function you need to
import it on your current file by using the import keyword.

Let’s understand it with an example

from math import sqrt


var = int(input("Enter a
Number: "))
sqt = sqrt(var)
print(sqt)

Output:
Enter a Number:25
5

DONBOSCO COLLEGE Page 10


CP1442: WEB PROGRAMMING & PYTHON

Operators in Python

• Operators are the constructs which can manipulate the value of


operands.
• Consider the expression 4 + 5 = 9. Here, 4 and 5 are called
operands and + is called operator.

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 –

Operator Description Example

+ Addition Adds values on either side of the a + b = 30


operator.

- Subtraction Subtracts right hand operand from a – b = -10


left hand operand.

* Multiplies values on either side of a * b = 200


Multiplication the operator

DONBOSCO COLLEGE Page 11


CP1442: WEB PROGRAMMING & PYTHON

/ Division Divides left hand operand by right b/a=2


hand operand

% Modulus Divides left hand operand by right b%a=0


hand operand and returns
remainder

** Exponent Performs exponential (power) a**b =10 to the


calculation on operators power 20

// Floor Division - The division of 9//2 = 4 and


operands where the result is the 9.0//2.0 = 4.0,
quotient in which the digits after -11//3 = -4, -
the decimal point are removed. But 11.0//3 = -4.0
if one of the operands is negative,
the result is floored, i.e., rounded
away from zero (towards negative
infinity) −
2.Comparison Operators
These operators compare the values on either sides of them and
decide the relation among them. They are also called Relational
operators.
Assume variable a holds 10 and variable b holds 20, then −
Operator Description Example

== If the values of two operands are equal, (a == b) is not


then the condition becomes true. true.

!= If values of two operands are not equal, (a != b) is true.


then condition becomes true.

DONBOSCO COLLEGE Page 12


CP1442: WEB PROGRAMMING & PYTHON

<> If values of two operands are not equal, (a <> b) is true.


then condition becomes true. This is similar to
!= operator.

> If the value of left operand is greater than (a > b) is not


the value of right operand, then condition true.
becomes true.

< If the value of left operand is less than (a < b) is true.


the value of right operand, then condition
becomes true.

>= If the value of left operand is greater than (a >= b) is not


or equal to the value of right operand, true.
then condition becomes true.

<= If the value of left operand is less than or (a <= b) is true.


equal to the value of right operand, then
condition becomes true.
3.Assignment Operators
Assume variable a holds 10 and variable b holds 20, then −
Operator Description Example

= Assigns values from right side c = a + b assigns


operands to left side operand value of a + b into c

+= Add AND It adds right operand to the left c += a is equivalent


operand and assign the result to to c = c + a
left operand

-= Subtract It subtracts right operand from the c -= a is equivalent


AND left operand and assign the result to c = c - a
to left operand

DONBOSCO COLLEGE Page 13


CP1442: WEB PROGRAMMING & PYTHON

*= Multiply It multiplies right operand with the c *= a is equivalent


AND left operand and assign the result to c = c * a
to left operand

/= Divide It divides left operand with the c /= a is equivalent


AND right operand and assign the to c = c / a
result to left operand

%= It takes modulus using two c %= a is equivalent


Modulus operands and assign the result to to c = c % a
AND left operand

**= Performs exponential (power) c **= a is equivalent


Exponent calculation on operators and to c = c ** a
AND assign value to the left operand

//= Floor It performs floor division on c //= a is


Division operators and assign value to the equivalent to c = c
left operand // a
4.Logical Operators
There are following logical operators supported by Python language.
Assume variable a holds 10 and variable b holds 20 then
Operator Description Example

and If both the operands are true then condition (a and b) is


Logical becomes true. true.
AND
or Logical If any of the two operands are non-zero then (a or b) is
OR condition becomes true. true.

not Logical Used to reverse the logical state of its Not(a and
NOT operand. b) is false.

DONBOSCO COLLEGE Page 14


CP1442: WEB PROGRAMMING & PYTHON

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

in Evaluates to true if it finds a x in y, here in results in


variable in the specified a 1 if x is a member of
sequence and false otherwise. sequence y.

not in Evaluates to true if it does not x not in y, here not in


finds a variable in the specified results in a 1 if x is not a
sequence and false otherwise. member of sequence y.
6.Identity Operators
Identity operators compare the memory locations of two objects.
There are two Identity operators explained below −
Operator Description Example

is Evaluates to true if the variables on x is y, here is


either side of the operator point to the results in 1 if id(x)
same object and false otherwise. equals id(y).

is not Evaluates to false if the variables on x is not y, here is


either side of the operator point to the not results in 1 if
same object and true otherwise. id(x) is not equal to
id(y).

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

DONBOSCO COLLEGE Page 15


CP1442: WEB PROGRAMMING & PYTHON

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 −

• int (signed integers)


• long (long integers, they can also be represented in octal and
hexadecimal)
• float (floating point real values)

• complex (complex numbers)


2.Strings
Strings in Python are identified as a contiguous set of characters
represented in the quotation marks. Python allows for either pairs of
single or double quotes. Subsets of strings can be taken using the
slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning
of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk
(*) is the repetition operator. For example −

str = 'Hello World!'

DONBOSCO COLLEGE Page 16


CP1442: WEB PROGRAMMING & PYTHON

print str # Prints complete string


print str[0] # Prints first character of the string print
str[2:5] # Prints characters starting from 3rd to 5th print
str[2:] # Prints string starting from 3rd character print str *
2 # Prints string two times print str + "TEST" # Prints
concatenated string

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

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist =


[123, 'john']

print list # Prints complete list


print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times print list + tinylist #
Prints concatenated lists
4.Tuples
A tuple is another sequence data type that is similar to the list. A
tuple consists of a number of values separated by commas. Unlike
lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed
in brackets ( [ ] ) and their elements and size can be changed, while
tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
Tuples can be thought of as read-only lists. For example −

DONBOSCO COLLEGE Page 17


CP1442: WEB PROGRAMMING & PYTHON

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) tinytuple =


(123, 'john')

print tuple # Prints complete list


print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times print tuple + tinytuple
# Prints concatenated lists
5.Dictionary
Python's dictionaries are kind of hash table type. They work like
associative arrays or hashes found in Perl and consist of key-value
pairs. A dictionary key can be almost any Python type, but are
usually numbers or strings. Values, on the other hand, can be any
arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be
assigned and accessed using square braces ([]). For example −
dict = {}
dict['one'] = "This is one" dict[2]
= "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print dict['one'] # Prints value for 'one' key print


dict[2] # Prints value for 2 key print tinydict
# Prints complete dictionary print tinydict.keys() #
Prints all the keys print tinydict.values() # Prints all
the values
This produce the following result −
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']

DONBOSCO COLLEGE Page 18


CP1442: WEB PROGRAMMING & PYTHON

Mutable vs Immutable Objects in Python

• Every variable in python holds an instance of an object. There


are two types of objects in python i.e. Mutable and Immutable
objects.
• Whenever an object is instantiated, it is assigned a unique
object id. The type of the object is defined at the runtime and it
can’t be changed afterwards. However, it’s state can be changed
if it is a mutable object.
• To summarise the difference, mutable objects can change their
state or contents and immutable objects can’t change their
state or content.
• Immutable Objects : These are of in-built types like int, float,
bool, string, unicode, tuple. In simple words, an immutable
object can’t be changed after it is created.
• Mutable Objects : These are of type list, dict, set . Custom
classes are generally mutable.

Type Conversion in Python

Python defines type conversion functions to directly convert one data


type to another which is useful in day to day and competitive
programming. The following are type conversion functions in python.
1.int(a,base) : This function converts any data type to integer. ‘Base’
specifies the base in which string is if data type is string.

2. float() : This function is used to convert any data type to a


floating point number

DONBOSCO COLLEGE Page 19


CP1442: WEB PROGRAMMING & PYTHON

Example
s=
"10010"

# printing string converting to int base


2 c = int(s,2)
print ("After converting to integer base 2 : ")
print (c)

# printing string converting to


float e = float(s)
print ("After converting to float : ")
print (e)

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)

DONBOSCO COLLEGE Page 20


CP1442: WEB PROGRAMMING & PYTHON

# printing integer converting to hexadecimal


string c = hex(56)
print ("After converting 56 to hexadecimal string : “)
print (c)

# printing integer converting to octal


string c = oct(56)
print ("After converting 56 to octal string : ")
print (c)

Output:
After converting character to integer : 52
After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70

6. tuple() : This function is used to convert to a tuple.


7. set() : This function returns the type after converting to set.
8. list() : This function is used to convert any data type to a list type.

Exampl
e:

# initializing string
s = 'geeks'

# printing string converting to


tuple c = tuple(s)
print ("After converting string to tuple : ")
print (c)

# printing string converting to


set c = set(s)
print ("After converting string to set : ")
print (c)

DONBOSCO COLLEGE Page 21


CP1442: WEB PROGRAMMING & PYTHON

# printing string converting to list


c = list(s)
print ("After converting string to list : ")
print (c) Output:
After converting string to tuple : ('g', 'e', 'e', 'k', 's')
After converting string to set : {'k', 'e', 's', 'g'}
After converting string to list : ['g', 'e', 'e', 'k', 's']

9. dict() : This function is used to convert a tuple of order (key,value)


into a dictionary.
10. str() : Used to convert integer into a string.
11. complex(real,imag) : : This function converts real numbers to
complex(real,imag) number.

Examp
le

# initializing integers
a = 1
b = 2

# initializing tuple tup = (('a',


1) ,('f', 2), ('g', 3))

# printing integer converting to complex


number c = complex(1,2)
print ("After converting integer to complex number :
") print (c)

# printing integer converting to


string c = str(a)
print ("After converting integer to string : ")
print (c)
DONBOSCO COLLEGE Page 22
CP1442: WEB PROGRAMMING & PYTHON

# printing tuple converting to expression


dictionary c = dict(tup)
print ("After converting tuple to dictionary :
") print (c) Output:
After converting integer to complex number : (1+2j)
After converting integer to string : 1
After converting tuple to dictionary : {'a': 1, 'f': 2, 'g': 3}

12. chr(number) : : This function converts number to its


corresponding ASCII character.

Example:

# Convert ASCII value to


characters a = chr(76) b =
chr(77)

print(a)
print(b)
Output:
L
M

Selection sort in Python


In the selection sort algorithm, an array is sorted by recursively
finding the minimum element from the unsorted part and inserting
it at the beginning. Two subarrays are formed during the execution
of Selection sort on a given array.

The subarray, which is


already sorted The
subarray, which is unsorted.
DONBOSCO COLLEGE Page 23
CP1442: WEB PROGRAMMING & PYTHON

During every iteration of selection sort, the minimum element from


the unsorted subarray is popped and inserted into the sorted
subarray.

DONBOSCO COLLEGE Page 24


CP1442: WEB PROGRAMMING & PYTHON

A = ['t','u','t','o','r','i','a','l'] for i in

range(len(A)):

min_= i for j in range(i+1,

len(A)): if A[min_] > A[j]:

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

Insertion Sort in Python


• Iterate over the input elements by growing the sorted array at
each iteration.
• Compare the current element with the largest value available in
the sorted array.
• If the current element is greater, then it leaves the element in
its place and moves on to the next element else it finds its
correct position in the sorted array and moves it to that position
in the array.

DONBOSCO COLLEGE Page 25


CP1442: WEB PROGRAMMING & PYTHON

• This is achieved by shifting all the elements towards the right,


which are larger than the current element, in the sorted array
to one position ahead.
Now let’s see the visual representation of the algorithm

DONBOSCO COLLEGE Page 26


CP1442: WEB PROGRAMMING & PYTHON

def insertionSort(arr): for i in

range(1, len(arr)):

key = arr[i]
# Move elements of arr[0..i-1], that are greater

than key,

# to one position ahead of their current position

j = i-1 while j >=0 and key < arr[j] :

arr[j+1] = arr[j] j
-= 1 arr[j+1] = key

# main arr = ['t','u','t','o','r','i','a','l'] insertionSort(arr)

print ("The sorted array is:") for i in range(len(arr)):

print (arr[i])

Output
The sorted array is:
a
i
l
o
r
t
t
u

DONBOSCO COLLEGE Page 27


CP1442: WEB PROGRAMMING & PYTHON

Bubble Sort in Python


Step0: Starting from the first index, compare the first and the second elements.If the first
element is greater than the second element, they are swapped.
Now, compare the second and the third elements. Swap them if they are not in order.

The above process goes on until the last element.

Compare the adjacent elements

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.

Compare the adjacent elements

Compare the adjacent Elements

DONBOSCO COLLEGE Page 29


CP1442: WEB PROGRAMMING & PYTHON

DONBOSCO COLLEGE Page 30


CP1442: WEB PROGRAMMING & PYTHON

MODULE IV

Module II: Decision Making -conditional (if), alternative (if-else),


if..elif..else -nested if - Loops for,range() while, break, continue, pass;
Functions: return values, parameters, local and global scope,
function composition, recursion; Strings: string slices, immutability,
string functions and methods, string module; Lists as arrays.

DONBOSCO COLLEGE Page 31


CP1442: WEB PROGRAMMING & PYTHON

Decision Making in Python


Decisions in a program are used when the program has conditional
choices to execute a code block. It is the prediction of conditions that
occur while executing a program to specify actions. Multiple
expressions get evaluated with an outcome of either TRUE or FALSE.

Python provides various types of conditional statements:


1. if Statement
2. if_else Statement
3. elif Statement

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

DONBOSCO COLLEGE Page 32


CP1442: WEB PROGRAMMING & PYTHON

Output:
a is greater

2.if else Statements

It also contains a Boolean expression. The if the statement is


followed by an optional else statement & if the expression results in
FALSE, then else statement gets executed. It is also called
alternative execution in which there are two possibilities of the
condition determined in which any one of them will get executed.

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

DONBOSCO COLLEGE Page 33


CP1442: WEB PROGRAMMING & PYTHON

• We can implement if statement and or if-else statement inside


another if or if - else statement. Here more than one if
conditions are applied & there can be more than one if within
elif.
• elif - is a keyword used in Python replacement of else if to place
another condition in the program. This is called chained
conditional.

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:

DONBOSCO COLLEGE Page 34


CP1442: WEB PROGRAMMING & PYTHON

print("b is greater")
Output:
both are equal

looping in Python

• In general, statements are executed sequentially: The first


statement in a function is executed first, followed by the
second, and so on. There may be a situation when you need to
execute a block of code several number of times.
• Programming languages provide various control structures
that allow for more complicated execution paths.A loop
statement allows us to execute a statement or group of
statements multiple times.
• Python programming language provides following types of loops
to handle looping requirements.
Sr.No. Loop Type & Description

1 while loop : Repeats a statement or group of statements while


a given condition is TRUE. It tests the condition before
executing the loop body.

2 for loop :-Executes a sequence of statements multiple times


and abbreviates the code that manages the loop variable.

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

• Here, statement(s) may be a single statement


or a block of statements. The condition may be
any expression, and true is any non-zero value. The loop
iterates while the condition is true.
• When the condition becomes false, program control passes to
the line immediately following the loop.

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

as a list or a string. Syntax

for iterating_var in sequence:


statements(s)

DONBOSCO COLLEGE Page 36


CP1442: WEB PROGRAMMING & PYTHON

If a sequence contains an expression list, it is evaluated first. Then,


the first item in the sequence is assigned to the iterating variable
iterating_var. Next, the statements block is executed. Each item in
the list is assigned to iterating_var, and the statement(s) block is
executed until the entire sequence is exhausted.
Example : for x in range
(0,3) : print (x)
Output:
0
1
2

3.Nested Loop

Python programming language allows to use one loop inside another


loop. Following section shows few examples to illustrate the concept.
Syntax of nested for loop
for iterating_var in sequence: for
iterating_var in sequence:
statements(s) statements(s)
The syntax for a nested while loop
while expression:
while expression:
statement(s)
statement(s)

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

DONBOSCO COLLEGE Page 37


CP1442: WEB PROGRAMMING & PYTHON

2* 1=2
2* 2=4
3* 1=3
3* 2=6
4* 1=4
4* 2=8
5* 1=5
5 * 2 = 10

Loop control Statements in Python


• These statements are used to change execution from its normal
sequence.
• Python supports three types of loop control statements:
1.Break statement:-It is used to exit a while loop or a for a loop. It
terminates the looping & transfers execution to the statement next to
the loop.

Sytanx:
break

Example:
i=0
while i <= 10:
print (i)
i++ if i
== 3:
break
Output:
0
1
2

2.Continue statement:- It causes the looping to skip the rest part


of its body & start re-testing its condition. The continue statement
in Python returns the control to the beginning of the current loop.

DONBOSCO COLLEGE Page 38


CP1442: WEB PROGRAMMING & PYTHON

When encountered, the loop starts next iteration without executing


the remaining statements in the current iteration.

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

DONBOSCO COLLEGE Page 39


CP1442: WEB PROGRAMMING & PYTHON

Example
for i in 'Python': if i
== 'h':
pass print ('This is pass
block') print ('Current Letter :', i)

print ("Good bye!")


Output
When the above code is executed, it produces the following result −
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

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.

DONBOSCO COLLEGE Page 40


CP1442: WEB PROGRAMMING & PYTHON

• Function blocks begin with the keyword def followed by the


function name and parentheses.
• Any input parameters or arguments should be placed within
these parentheses.
• The code block within every function starts with a colon (:) and
is indented.
• The statement return [expression] exits a function
• . A return statement with no arguments is the same as return
None.

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 −

DONBOSCO COLLEGE Page 41


CP1442: WEB PROGRAMMING & PYTHON

def printme(a):
print a
return;

# Now you can call printme


function printme(21) printme(‘x’)
printme(“hai”
Output: 21 x hai
The return Statement
The statement return [expression] exits a function, optionally
passing back an expression to the caller. A return statement with no
arguments is the same as return None.
All the above examples are not returning any value. You can return
a value from a function as follows −
# Function definition is here def
sum( a, b):
# Add both the parameters and return
them." total = a + b print "Inside the
function : ", total return total;

# Now you can call sum function total


= sum( 10, 20 ); print "Outside the
function : ", total

When the above code is executed, it produces the following result −


Inside the function : 30
Outside the function : 30

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 −

DONBOSCO COLLEGE Page 42


CP1442: WEB PROGRAMMING & PYTHON

• Global variables
• Local variables

Global vs. Local variables


Variables that are defined inside a function body have a local scope,
and those defined outside have a global scope.
This means that local variables can be accessed only inside the
function in which they are declared, whereas global variables can be
accessed throughout the program body by all functions. When you
call a function, the variables declared inside it are brought into
scope. Following is a simple example –

total = 0; # This is global variable.


# Function definition is here def
sum( a, b ):
# Add both the parameters and return them."
total = a + b; # Here total is local variable. print
"Inside the function local total : ", total return
total;

# Now you can call sum function sum( 10, 20 ); print


"Outside the function global total : ", total
When the above code is executed, it produces the following result −
Inside the function local total : 30
Outside the function global total : 0 Parameters
in Python Functions
Paremeters are also known as arguments,they are values passed to
the fuctions.You can call a function by using the following types of
formal arguments −

1. Required arguments
2. Keyword arguments

DONBOSCO COLLEGE Page 43


CP1442: WEB PROGRAMMING & PYTHON

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;

# Now you can call printme function


printme()
When the above code is executed, it produces the following result −
Traceback (most recent call last): File
"test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
2.Keyword arguments
Keyword arguments are related to the function calls. When you use
keyword arguments in a function call, the caller identifies the
arguments by the parameter name.
This allows you to skip arguments or place them out of order because
the Python interpreter is able to use the keywords provided to match
the values with parameters. You can also make keyword calls to the
printinfo() function in the following ways −

# Function definition is here def


printinfo( name, age ):
print "Name: ", name
print "Age: ", age
return;

DONBOSCO COLLEGE Page 44


CP1442: WEB PROGRAMMING & PYTHON

# Now you can call printinfo function


printinfo( age=50, name="lal" )

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;

# Now you can call printinfo function


printinfo( age=50, name="lal" ) printinfo(
name="lal" )
When the above code is executed, it produces the following result −
Name: lal
Age 50
Name: lal
Age 35
4.Variable-length arguments
You may need to process a function for more arguments than you
specified while defining the function. These arguments are called
variable-length arguments and are not named in the function
definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this −
DONBOSCO COLLEGE Page 45
CP1442: WEB PROGRAMMING & PYTHON

def functionname([formal_args,] *var_args_tuple ):


example: def printinfo(a,*var_argument)
An asterisk (*) is placed before the variable name that holds the
values of all nonkeyword variable arguments. This tuple remains
empty if no additional arguments are specified during the function
call. Following is a simple example −
def printinfo( arg1, *vartuple ):
print "Output is: "
print arg1 for var in
vartuple:
print var return;

# Now you can call printinfo function


printinfo( 10 ) printinfo( 70, 60, 50 )
When the above code is executed, it produces the following result −
Output is:
10
Output is:
70
60
50

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.

DONBOSCO COLLEGE Page 46


CP1442: WEB PROGRAMMING & PYTHON

• Although it appears that lambda's are a one-line version of a


function, they are not equivalent to inline statements in C or
C++, whose purpose is by passing function stack allocation
during invocation for performance reasons.

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;

# Now you can call sum as a function


print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
When the above code is executed, it produces the following result −
Value of total : 30
Value of total : 40
Recursion in Python
• Python also accepts function recursion, which means a defined
function can call itself.
• Recursion is a common mathematical and programming
concept. It means that a function calls itself. This has the
benefit of meaning that you can loop through data to reach a
result.
• In this example, fact() is a function that we have defined to
call itself ("recurse"). The
factorial of a number is the product of all the integers from 1
to that number.
• For example, the 1*2*3*4*5*6 factorial of 6 is . Factorial
is not defined for = 720 negative numbers and the
factorial of zero is one, 0! = 1.
DONBOSCO COLLEGE Page 47
CP1442: WEB PROGRAMMING & PYTHON

def fact (x):


if x == 1:
return 1
else:
return (x * fact (x-1))
num = 3 print("The factorial of", num,
"is", fact (num))

Output

The factorial of 3 is 6
String in Python

A string is a sequence of characters.


A character is simply a symbol. For example, the English
language has 26 characters.
• Strings are amongst the most popular types in Python. We can
create them simply by enclosing characters in quotes. Python
treats single quotes the same as double quotes. Creating strings
is as simple as assigning a value to a variable.
• For example –
var1 = 'Hello
World!' var2 =
"Python
Programming"

Accessing Values in Strings


Python does not support a character type; these are treated as
strings of length one, thus also considered a substring.
To access substrings, use the square brackets for slicing along with
the index or indices to obtain your substring.
For example −
DONBOSCO COLLEGE Page 48
CP1442: WEB PROGRAMMING & PYTHON

var1 = 'Hello World!' var2 =


"Python Programming"

print "var1[0]: ", var1[0] print


"var2[1:5]: ", var2[1:5]
When the above code is executed, it produces the following result −
var1[0]: H var2[1:5]:
ytho
Multiline Strings

You can assign a multiline string to a variable by using three quotes:

Example

You can use three double quotes:

a = """Lorem ipsum dolor sit


amet, consectetur adipiscing elit,
sed do eiusmod tempor
incididunt ut labore et dolore
magna aliqua.""" print(a)
String Slicing in Python

Python slicing is about obtaining a sub-string from the given string


by slicing it respectively from start to end.Python slicing can be done
in two ways.
1. slice() Constructor
2. Extending Indexing

1.slice() Constructor :The slice() constructor creates a slice object


representing the set of indices specified by range(start, stop, step).

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

DONBOSCO COLLEGE Page 50


CP1442: WEB PROGRAMMING & PYTHON

2.Extending indexing

In Python, indexing syntax can be used as a substitute for the slice


object. This is an easy and convenient way to slice a string both
syntax wise and execution wise.
Syntax string[start:end:step] start, end and step
have the same mechanism as slice()
constructor.

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

DONBOSCO COLLEGE Page 51


CP1442: WEB PROGRAMMING & PYTHON

String Immutability

In python, the string data types are immutable. Which means a


string value cannot be updated. We can verify this by trying to update
a part of the string which will led us to an error.
Example t=
"Tutorialspoi
nt" print
type(t) t[0] =
"M"
When we run the above program, we get the following output –

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

capitalize() Returns a copy of


the string with its
>>> mystring = "hello python"
first character
>>> print(mystring.capitalize())
capitalized and the
Hello python
rest lowercased.

Casefold() Returns a casefolded


copy of the string.
>>> mystring = "hello
Casefolded strings PYTHON" >>>
may be used for print(mystring.casefold())
caseless matching. hello python

DONBOSCO COLLEGE Page 52


CP1442: WEB PROGRAMMING & PYTHON

Center(width, Returns the string >>> mystring = "Hello"


[fillchar]) centered in a string >>> x = mystring.center(12,"-")
of length width. >>> print(x)
---Hello----

Count(sub, Returns the number


[start], of nonoverlapping >>> mystr = "Hello Python"
[end]) occurrences of >>> print(mystr.count("o"))
substring 2
(sub) in the range >>>
[start, end]. Optional print(mystr.count("th"))
arguments startand 1
end are

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

endswith(suffix, Returns True


[start], [end]) if the string >>> mystr = "Python"
ends with the >>>print(mystr.endswith("y"))
specified False
suffix, >>>print(mystr.endswith("hon"))
otherwise it True
returns False.

DONBOSCO COLLEGE Page 53


CP1442: WEB PROGRAMMING & PYTHON

Find(sub, Returns the >>> mystring = "Python"


[start], lowest index >>>print(mystring.find("P"))
[end]) in the string 0
where >>>print(mystring.find("on"))
substring sub 4
is found
within the
slice
s[start:end].
Index(sub, Searches the
[start], string for a >>> mystr = "HelloPython"
[end]) specified >>> print(mystr.index("P"))
value and 5
returns the >>>print(mystr.index("hon"))
8
position of
>>> print(mystr.index("o"))
where it was 4
found
isalnum Returns True
if all >>> mystr = "HelloPython"
characters in >>> print(mystr.isalnum())
the string are True
alphanumeric >>> a = "123"
>>> print(a.isalnum())
True
>>> a= "$*%!!!"
>>> print(a.isalnum())
False

Isalpha() Returns True


if all >>> mystr = "HelloPython"
characters in >>> print(mystr.isalpha())
the string are True
in the >>> a = "123"
alphabet

DONBOSCO COLLEGE Page 54


CP1442: WEB PROGRAMMING & PYTHON

>>> print(a.isalpha())
False
>>> a= "$*%!!!"
>>> print(a.isalpha())
False

Isdecimal() Returns True if all


characters in the string >>> mystr = "HelloPython"
are decimals >>> print(mystr.isdecimal())
False
>>> a="1.23"
>>> print(a.isdecimal())
False
>>> c = u"\u00B2"
>>> print(c.isdecimal())
False
>>> c="133"
>>> print(c.isdecimal())
True

Isdigit() Returns True if all


characters in the string >>> c="133"
are digits >>> print(c.isdigit())
True
>>> c = u"\u00B2"
>>> print(c.isdigit())
True
>>> a="1.23"
>>> print(a.isdigit())
False

Islower()

DONBOSCO COLLEGE Page 55


CP1442: WEB PROGRAMMING & PYTHON

Returns True if all >>> c="Python"


characters in the string >>> print(c.islower())
are lower case False
>>> c="_user_123"
>>> print(c.islower())
True
>>> print(c.islower())
False

Isnumeric() Returns True if all


characters in the string >>> c="133"
are numeric >>> print(c.isnumeric())
True
>>> c="_user_123"
>>> print(c.isnumeric())
False

>>> c="Python"
>>> print(c.isnumeric())
False

isprintable() Returns True if all


characters in the string >>> c="133"
are printable >>> print(c.isprintable())
True
>>> c="_user_123"
>>> print(c.isprintable())
True
>>> c="\t"
>>> print(c.isprintable())
False

isspace()

DONBOSCO COLLEGE Page 56


CP1442: WEB PROGRAMMING & PYTHON

Returns True if all >>> c="133"


characters in the string >>> print(c.isspace())
are whitespaces False
>>> c="Hello Python"
>>> print(c.isspace())
False
73
>>> c="Hello"
>>> print(c.isspace())
False
>>> c="\t"
>>> print(c.isspace())
True

isupper() Returns True if all


characters in the string >>> c="Python"
are upper case >>> print(c.isupper())
False
>>> c="PYHTON"
>>> print(c.isupper())
True
>>> c="\t"
>>> print(c.isupper())
False

join(iterable) Joins the elements of an


iterable to the end of the >>> a ="-"
string >>> print(a.join("123"))
1-2-3
>>> a="Hello Python"
>>> a="**"
>>> print(a.join("Hello

DONBOSCO COLLEGE Page 57


CP1442: WEB PROGRAMMING & PYTHON

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

replace(old, Returns a string


new[,c where a >>> mystr = "Hello Python.Hello Java.
ount]) specified value is Hello
replaced with a C++."
specified value >>>print(mystr.replace("Hello","Bye"))
Bye Python. Bye Java. ByeC++.

swapcase() Swaps cases,


lower case >>> mystr = "Hello PYthon"
becomes upper >>> print(mystr.swapcase())
case and vice hELLO python
versa
title() Converts the
first character of >>> mystr = "Hello PYthon"
each word to >>> print(mystr.title())
upper case Hello Python
>>> mystr = "HELLO JAVA"
>>> print(mystr.title())
Hello Java

upper() Converts a
string into upper >>> mystr = "hello Python"
case >>> print(mystr.upper())
HELLO PYTHON

DONBOSCO COLLEGE Page 58


CP1442: WEB PROGRAMMING & 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:

from string import


Formatter

formatter = Formatter()
print(formatter.format('{website}',
website='JournalDev')) print(formatter.format('{}
{website}', 'Welcome to', website='JournalDev'))

# format() behaves in similar manner


print('{} {website}'.format('Welcome to',
website='JournalDev')) Output:
Welcome to JournalDev Welcome to JournalDev 2.Template
This class is used to create a string template for simpler string
substitutions as described in PEP 292. It’s useful in implementing
internationalization (i18n) in an application where we don’t need
complex formatting rules.

DONBOSCO COLLEGE Page 59


CP1442: WEB PROGRAMMING & PYTHON

Example:

from string import Template t = Template('$name is


the $title of $company') s =
t.substitute(name='Pankaj', title='Founder',
company='JournalDev.') print(s)
Output: Pankaj is the Founder of JournalDev.

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

In Python programming, a list is created by placing all the items


(elements) inside square brackets [], separated by commas.
It can have any number of items and they may be of different
types (integer, float, string etc.).
Lists can be converted to arrays using the built-in
functions in the Python numpy library.
• numpy provides us with two functions to use when converting
a list into an array:
1. numpy.array()
2.
numpy.asarray()
1. Using numpy.array()
This numpy library takes a list as an argument and returns
function of an array that contains all the
the
elements of the list. See the example below:
Example:
import numpy as np
my_list =
[2,4,6,8,10]
my_array =

DONBOSCO COLLEGE Page 60


CP1442: WEB PROGRAMMING & PYTHON

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'>

The mainnp.array() np.asarray() is copy false in


difference and that flag the
between the is case

DONBOSCO COLLEGE Page 61


CP1442: WEB PROGRAMMING & PYTHON

ofnp.asarray(), true (by np.array() .


and default)
in the
Illustrative Programs:
case of
1.Python program to find
square root of a number
Python number method sqrt() returns the square root of x for x > 0.
import math # This will import math
module a=100 b=7 c=81
print "Square root of a is : ", math.sqrt(a)
print " Square root of b is ", math.sqrt(b)
print " Square root of c is ", math.sqrt(c)

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

2.Python program to find gcd of two numbers

Greatest common divisor or gcd is a mathematical expression to find


the highest number which can divide both the numbers whose gcd
has to be found with the resulting remainder as zero. It has many
mathematical applications. Python has a inbuilt gcd function in the
math module which can be used for this purpose.
gcd():-It accepts two integers as parameter and returns the
integer which is the gcd value.
Syntax

Syntax: gcd(x,y)

Where x and y are positive integers.

Example of gcd()
In the below example we print the result of gcd of a pair of integers.

DONBOSCO COLLEGE Page 62


CP1442: WEB PROGRAMMING & PYTHON

import math print ("GCD of 75 and 30 is

",math.gcd(75, 30)) print ("GCD of 0 and 12 is

",math.gcd(0, 12)) print ("GCD of 0 and 0 is

",math.gcd(0, 0)) print ("GCD of -24 and -18 is

",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

3.Python program for exponentiation


a= 3 b= 4 print
"Exponential Value is: ",
pow(a, b)

output:
Exponential value is
81

4.Python program to find sum of elements in an array

arr = [1, 2, 3, 4, 5];


sum = 0;
for i in range(0, len(arr)):

DONBOSCO COLLEGE Page 63


CP1442: WEB PROGRAMMING & PYTHON

sum = sum + arr[i];


print("Sum of all the elements of an array: " + str(sum));

output

Sum of all the elements of an array: 15

5.Python program to perform linear search


Algorithm
• Start from the leftmost element of given arr[] and one by one
compare element x with each element of arr[]
• If x matches with any of the element, return the index value.
• If x doesn’t match with any of elements in arr[] , return -1 or
element not found.
Now let’s see the visual representation of the given approach −

DONBOSCO COLLEGE Page 64


CP1442: WEB PROGRAMMING & PYTHON

def linearsearch(arr, x): for

i in range(len(arr)): if

arr[i] == x:

return i return -1 arr = ['t','u','t','o','r','i','a','l'] x =


'a' print("element found at index
"+str(linearsearch(arr,x)))

Here we linearly scan the list with the


help of for loop. Output
element found at index 6

6.Python program to perform binary search


Problem statement − We will be given a sorted list and we need to find
an element with the help of a binary search.
Algorithm
• Compare x with the middle element.
• If x matches with the middle element, we return the mid index.
• Else If x is greater than the mid element, then x can only lie in
right half subarray after the mid element. So we recur for the
right half.
• Else (x is smaller) recur for the left half
DONBOSCO COLLEGE Page 65
CP1442: WEB PROGRAMMING & PYTHON

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

Output: Element is present at index 4

DONBOSCO COLLEGE Page 66


CP1442: WEB PROGRAMMING & PYTHON

DONBOSCO COLLEGE Page 67

You might also like