0% found this document useful (0 votes)
4 views

python full notes

Python is a high-level, interpreted, and object-oriented programming language created by Guido van Rossum between 1985 and 1990. It is known for its readability, simplicity, and versatility, making it suitable for beginners and a wide range of applications. Python supports various programming paradigms, including procedural, object-oriented, and functional programming, and features a broad standard library.

Uploaded by

Haa He
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

python full notes

Python is a high-level, interpreted, and object-oriented programming language created by Guido van Rossum between 1985 and 1990. It is known for its readability, simplicity, and versatility, making it suitable for beginners and a wide range of applications. Python supports various programming paradigms, including procedural, object-oriented, and functional programming, and features a broad standard library.

Uploaded by

Haa He
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

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. Like Perl, Python source code is also
available under the GNU General Public License (GPL).

Python is designed to be highly readable. It has fewer syntactical constructions than other languages.

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

• Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.

• Python is Object-Oriented: Python supports Object-Oriented style or technique of programming


that encapsulates code within objects.

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

History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research
Institute for Mathematics and Computer Science in the Netherlands.

Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk,
and Unix shell and other scripting languages.

Python is now maintained by a core development team at the institute, although Guido van Rossum still
holds a vital role in directing its progress.

Python Features
Python's features include:

• Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This
allows the student to pick up the language quickly.

• Easy-to-read: Python code is more clearly defined and visible to the eyes.

1
• Easy-to-maintain: Python's source code is fairly easy-to-maintain.

• A broad standard library: Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.

• Interactive Mode:Python has support for an interactive mode which allows interactive testing and
debugging of snippets of code.

• Portable: Python can run on a wide variety of hardware platforms and has the same interface on
all platforms.

• Extendable: You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.

• Databases: Python provides interfaces to all major commercial databases.

• GUI Programming: Python supports GUI applications that can be created and ported to many
system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X
Window system of Unix.

• Scalable: Python provides a better structure and support for large programs than shell scripting.

Apart from the above-mentioned features, Python has a big list of good features, few are listed below:

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

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

2
Python Basic Syntax
The Python language has many similarities to Perl, C, and Java. However, there are some definite
differences between the languages.

Input and output operations in python

In the python input and output operations will be done by using input() and print() functions

Display Output in Python


Python provides the print() function to display output to the standard output devices.
Syntax

print(“message”) print(‘message’) print(variablename)

ex:

print(“hello”)

a=”raju”

print(“hello”+a)

x=50

print(x)

pirnt(“x =”,x)

a=5 b=6

print(a,b)

Taking input in python

Python provides the input() function to take the input from the standard input devices.
Syntax

input(“prompt”)

ex:

3
name=input(“enter your name”)

a=int(input(“enter a no”))

b=float(input(“enter a real no”))

To know the type of the variable python provided type() method

ex

a=5;

print(type(a)) o/p <class int>

b=1.5

print(type(b)) o/p <class float>

name=”nishitha”

print(type(name)) o/p <class ‘str’>

Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other object. An
identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).

Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case
sensitive programming language. Thus, Manpower and manpower are two different identifiers in
Python.

Here are naming conventions for Python identifiers –

• Class names start with an uppercase letter. All other identifiers start with a lowercase letter.

• Starting an identifier with a single leading underscore indicates that the identifier is private.

• Starting an identifier with two leading underscores indicates a strongly private identifier.

• If the identifier also ends with two trailing underscores, the identifier is a language-defined special
name.

4
Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot use them as
constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.

and Exec not

assert Finally or

break For pass

class From print

continue Global raise

def If return

del Import try

elif In while

else Is with

except Lambda yield

Lines and Indentation


Python provides no braces to indicate blocks of code for class and function definitions or flow control.
Blocks of code are denoted by line indentation.

The number of spaces in the indentation is variable, but all statements within the block must be indented
the same amount. For example –

If True:
print“True”

5
else:
print“False”

However, the following block generates an error –

If True:
print“Answer”
print“True”
else:
print“Answer”
print“False”

Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow the use of the line
continuation character (\) to denote that the line should continue. For example –

total = item_one + \
item_two + \
item_three

Statements contained within the [], {}, or () brackets do not need to use the line continuation character.
For example –

days =[‘Monday’,‘Tuesday’,‘Wednesday’,
‘Thursday’,‘Friday’]

Quotation in Python
Python accepts single (‘), double (“) and triple (‘’’ or “””) quotes to denote string literals, as long as the
same type of quote starts and ends the string.

The triple quotes are used to span the string across multiple lines. For example, all the following are legal

word =‘word’
sentence =“This is a sentence.”
Paragraph =“””This is a paragraph. It is
made up of multiple lines and sentences.”””

6
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the
end of the physical line are part of the comment and the Python interpreter ignores them.

#!/usr/bin/python

# First comment
print“Hello, Python!”# second comment

This produces the following result –

Hello,Python!

Multiple Statement Groups as Suites


A group of individual statements, which make a single code block are called suites in Python. Compound
or complex statements, such as if, while, def, and class require a header line and a suite.

Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by
one or more lines which make up the suite. For example –

if expression :
suite
elif expression :
suite
else:
suite

Python Variable Types


Variables are nothing but reserved memory locations to store values. This means that when you create a
variable you reserve some space in memory.

Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in
the reserved memory. Therefore, by assigning different data types to variables, you can store integers,
decimals or characters in these variables.

7
Assigning Values to Variables
Python variables do not need explicit declaration to reserve memory space. The declaration happens
automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.

The operand to the left of the = operator is the name of the variable and the operand to the right of the =
operator is the value stored in the variable. For example –

counter =100# An integer assignment


miles =1000.0# A floating point
name =“Raju”# A string

print counter
print miles
print name

Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For example –

a = b = c =1

Here, an integer object is created with the value 1, and all three variables are assigned to the same memory
location. You can also assign multiple objects to multiple variables. For example –

a,b,c =1,2,”raju”

Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string
object with the value “john” is assigned to the variable c.

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

8
Python has five standard data types –

• Numbers

• String

• List

• Tuple

• Dictionary

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

Examples
Here are some examples of numbers –

int Long float complex

10 51924361L 15.20 3.14j

• Python allows you to use a lowercase l with long, but it is recommended that you use only an
uppercase L to avoid confusion with the number 1. Python displays long integers with an
uppercase L.

9
• A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj,
where x and y are the real numbers and j is the imaginary unit.

Python 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!’

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

This will produce the following result –

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

Python 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 –

10
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

This produce the following result –

[‘abcd’, 786, 2.23, ‘john’, 70.200000000000003]


abcd
[786, 2.23]
[2.23, ‘john’, 70.200000000000003]
[123, ‘john’, 123, ‘john’]
[‘abcd’, 786, 2.23, ‘john’, 70.200000000000003, 123, ‘john’]

Python 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 –

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

11
print tuple[2:]# Prints elements starting from 3rd element
print tinytuple *2# Prints list two times
print tuple + tinytuple # Prints concatenated lists

This produce the following result –

(‘abcd’, 786, 2.23, ‘john’, 70.200000000000003)


abcd
(786, 2.23)
(2.23, ‘john’, 70.200000000000003)
(123, ‘john’, 123, ‘john’)
(‘abcd’, 786, 2.23, ‘john’, 70.200000000000003, 123, ‘john’)

The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed.
Similar case is possible with lists –

tuple =(‘abcd’,786,2.23,‘john’,70.2)
list =[‘abcd’,786,2.23,‘john’,70.2]
tuple[2]=1000# Invalid syntax with tuple
list[2]=1000# Valid syntax with list

Python 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 –

#!/usr/bin/python

dict ={}
dict[‘one’]=“This is one”
dict[2]=“This is two”

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

12
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’]

Dictionaries have no concept of order among elements. It is incorrect to say that the elements are “out of
order”; they are simply unordered.

Data Type Conversion


Sometimes, you may need to perform conversions between the built-in types. To convert between types,
you simply use the type name as a function.

There are several built-in functions to perform conversion from one data type to another. These functions
return a new object representing the converted value.

Function Description

int(x [,base]) Converts x to an integer. Base specifies the base if x is a string.

Long(x [,base] ) Converts x to a long integer. Base specifies the base if x is a string.

Float(x) Converts x to a floating-point number.

Complex(real [,imag]) Creates a complex number.

13
Str(x) Converts object x to a string representation.

Repr(x) Converts object x to an expression string.

Eval(str) Evaluates a string and returns an object.

Tuple(s) Converts s to a tuple.

List(s) Converts s to a list.

Set(s) Converts s to a set.

Dict(d) Creates a dictionary. D must be a sequence of (key,value) tuples.

Frozenset(s) Converts s to a frozen set.

Chr(x) Converts an integer to a character.

Unichr(x) Converts an integer to a Unicode character.

Ord(x) Converts a single character to its integer value.

Hex(x) Converts an integer to a hexadecimal string.

Oct(x) Converts an integer to an octal string.

Python Basic Operators


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.

14
Types of Operator
Python language supports the following types of operators.

• Arithmetic Operators

• Comparison (Relational) Operators

• Assignment Operators

• Logical Operators

• Bitwise Operators

• Membership Operators

Python Arithmetic Operators


Assume variable a holds 10 and variable b holds 20, then –

Operator Description Example

+ Addition Adds values on either side of the operator. A+b=


30

- Subtraction Subtracts right hand operand from left hand operand. A–b=-
10

* Multiplies values on either side of the operator a*b=


Multiplication 200

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

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

** Exponent Performs exponential (power) calculation on operators a**b =10


to the
power 20

15
// Floor Division – The division of operands where the result is the quotient in 9//2 = 4
which the digits after the decimal point are removed. But if one of the and
operands is negative, the result is floored, i.e., rounded away from zero 9.0//2.0 =
(towards negative infinity): 4.0, -
11//3 = -
4, -
11.0//3 =
-4.0

Python 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, then the condition becomes true. (a == b) is not
true.

!= If values of two operands are not equal, then condition becomes true.

> If the value of left operand is greater than the value of right operand, then (a > b) is not
condition becomes true. true.

< If the value of left operand is less than the value of right operand, then (a < b) is true.
condition becomes true.

>= If the value of left operand is greater than or equal to the value of right (a >= b) is not
operand, then condition becomes true. true.

<= If the value of left operand is less than or equal to the value of right operand, (a <= b) is
then condition becomes true. true.

Python Assignment Operators


Assume variable a holds 10 and variable b holds 20, then –

16
Operator Description Example

= Assigns values from right side operands to left side operand c=a+b
assigns value of
a + b into c

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

-= Subtract AND It subtracts right operand from the left operand and assign the result c -= a is
to left operand equivalent to c
=c–a

*= Multiply It multiplies right operand with the left operand and assign the result c *= a is
AND to left operand equivalent to c
=c*a

/= Divide AND It divides left operand with the right operand and assign the result to c /= a is
left operand equivalent to c
= c / ac /= a is
equivalent to c
=c/a

%= Modulus It takes modulus using two operands and assign the result to left c %= a is
AND operand equivalent to c
=c%a

**= Exponent Performs exponential (power) calculation on operators and assign c **= a is
AND value to the left operand equivalent to c
= c ** a

17
//= Floor It performs floor division on operators and assign value to the left c //= a is
Division operand equivalent to c
= c // a

Python Bitwise Operators


Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in
binary format they will be as follows –

a = 0011 1100

b = 0000 1101

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

There are following Bitwise operators supported by Python language

[ Show Example ]

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in both operands (a & b) (means
0000 1100)

| Binary OR It copies a bit if it exists in either operand. (a | b) = 61


(means 0011
1101)

18
^ Binary XOR It copies the bit if it is set in one operand but not both. (a ^ b) = 49
(means 0011
0001)

~ Binary Ones It is unary and has the effect of ‘flipping’ bits. (~a ) = -61
Complement (means 1100
0011 in 2’s
complement
form due to a
signed binary
number.

<< Binary Left Shift The left operands value is moved left by the number of bits A << = 240
specified by the right operand. (means 1111
0000)

>> Binary Right Shift The left operands value is moved right by the number of bits A >> = 15
specified by the right operand. (means 0000
1111)

Python 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 return true if the both the statements are true a>5 and a<10

or return true if anyone statement is true a>5 or b<10

not reverse the result return false if the result is true not(a>5 and a<10)

Python 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

19
Operator Description Example

in Evaluates to true if it finds a variable in the specified sequence and false X in y, here in
otherwise. results in a 1
if x is a
member of
sequence y.

Not in Evaluates to true if it does not finds a variable in the specified sequence and X not in y,
false otherwise. here not in
results in a 1
if x is not a
member of
sequence y.

Program to accept your name and display that

name=input(“enter your name”)

print(“hello “+name)

Program for addition of two numbers

a=int(input(“enter a no”))

b=int (input (“enter another no”))

c=a+b

print(“sum = “,c)

save the above program as add.py and execute it

20
program to accept maths,physics,computer marks and find out total and avg marks

m=int(input(“enter maths marks”))

p=int(input(“enter physics marks”))

cs=int(input(“enter computers marks”))

total=m+p+cs

avg=total/3

print(“total = “,total)

print(“avg = “,avg)

Python Decision Making


Decision making is anticipation of conditions occurring while execution of the program and specifying
actions taken according to the conditions.

Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need
to determine which action to take and which statements to execute if outcome is TRUE or FALSE
otherwise.

Following is the general form of a typical decision making structure found in most of the programming
languages –

21
Python programming language assumes any non-zero and non-null values as TRUE, and if it is
either zero or null, then it is assumed as FALSE value.

Python programming language provides following types of decision making statements. Click the
following links to check their detail.

Statement Description

if statements An if statement consists of a 22oolean expression followed by


one or more statements.

if...else statements An if statement can be followed by an optional else statement,


which executes when the 22oolean expression is FALSE.

nested if statements You can use one if or else if statement inside another if or else
if statement(s).

Let us go through each decision making briefly –

Syntax of if
if (condition):
statement 1
statement 2

Syntax of if else
if (condition):
statement 1
statement 2
else:
statement 1
statement 2

Nested if

22
Syntax
if (condition1):
if (condition2):
statements

If else ladder

syntax

if (condition):
statement
elif (condition):
statement
.
.
else:
statement

Program to test given number is positive or negative

n=int(input("enter a no"))

if n>0:

print("positive no")

else:

print("negative no")

23
Program to test given number is odd or even

n=int(input("enter a no"))

if n%2==0:

print("even no")

else:

print("odd no")

program for maximum from two nos

a=int(input("ener a no"))

b=int(input("enter another no"))

if a>b:

print("max =",a)

else:

print("max = ",b)

Program to test given number is positive or negative or zero # if else ladder

n=int(input("enter a no"))

if n>0:

print("positive no")

elif n<0:

print("negative no")

24
else:

print("zero")

program to find out the maximum from three nos #nested if

a=int(input("ener a no"))

b=int(input("enter second no"))

c=int(input("enter third no"))

if a>b:

if a>c:

print("max =",a)

else:

print("max =",c)

else:

if b>c:

print("max =",b)

else:

print("max =",c)

25
Python Loops
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. The following
diagram illustrates a loop statement −

Python programming language provides following types of loops to handle looping requirements.

Loop Type Description

while loop Repeats a statement or group of statements while a given condition is


TRUE. It tests the condition before executing the loop body.

for loop Executes a sequence of statements multiple times and abbreviates the
code that manages the loop variable.

nested loops You can use one or more loop inside any another while, for or
do..while loop.

26
Example programs of loops

print 1 to 10 numbers

i=1

while(i<=10):

print(i)

i=i+1

print 10 to 1 numbers

i=10

while(i>1):

print(i)

i=i-1

print mathematical table of given number

n=int(input("enter a no"))

i=1

while(i<=10):

print(n,"*",i,"=",n*i)

i=i+1

27
for loop example

for i in range(5):

print(i)

o/p 0 1 2 3 4

range() is a predifined function which create the sequence of numbers starts from 0

languages = ['C', 'Python', 'C++', 'Java', 'R']

for index in range(len(languages)):

print('Current language:', languages[index])

nested loops

i=1

while i<=5:

j=1

while j<=i:

print(j," ",end="")

j=j+1

print("")

i=i+1

28
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a scope, all
automatic objects that were created in that scope are destroyed.

Python supports the following control statements. Click the following links to check their detail.

Control Statement Description

break statement Terminates the loop statement and transfers execution to the
statement immediately following the loop.

continue statement Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.

pass statement The pass statement in Python is used when a statement is required
syntactically but you do not want any command or code to execute.

Example program for break and continue

# Using break statement

print("Example of break statement:")

for i in range(1, 6):

if i == 4:

break # Exit the loop when i equals 4

print(i)

29
# Using continue statement

print("\nExample of continue statement:")

for j in range(1, 6):

if j == 3:

continue # Skip the current iteration when j equals 3

print(j)

example for pass

1.

# Using pass statement in a for loop

for i in range(5):

pass # Placeholder for future code

2. a=["aa","bb","cc","dd"]

for i in a:

if(i=="bb"):

continue

else:

print(i)

30
Functions
A function is a block of organized, reusable code that is used to perform an action. Functions provide better modularity for

your application and a high degree of code reusing.

As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions.

These functions are called user-defined functions.

Defining a Function

You can define functions to provide the required functionality. Here are simple rules to define a function in 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, optionally passing back an expression to the caller. A return

statement with no arguments is the same as return None.

Syntax

def functionname( parameters):

function_suite

return[expression] #optional

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

De0 fprintme(str):

printstr

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

printme("welcome")

printme("python funcitons")

example program

def printme(str):

print(str)

return

32
# funcion calling

printme("this is a function")

printme("hello")

functions with parameters

program for addition of two nos using funcitons

def add(a,b):

c=a+b

print("sum = ",c)

return

a=int(input("enter a no"))

b=int(input("enete another no"))

add(a,b)

function with return value

def add(a,b):

c=a+b

return c

33
a=int(input("enter a no"))

b=int(input("enete another no"))

c=add(a,b)

print("sum =",c)

Local Variables vs Global Variables

Local Variables

Local variables are those which are initialized inside a function and belongs only to that particular function. It cannot be

accessed anywhere outside the function.

Example program for local variable

Def abc():

s="welcome" #local scope

print("Inside Function", s)

abc()

print("Outside Function", s) # not valid

Global Variables

The global variables are those which are defined outside any function and which are accessible throughout the program i.e.

inside and outside of every function

Example program for global variable

34
defabc():

print("Inside Function", s)

# Global scope

s = "welcome to python"

abc()

print("Outside Function", s)

call by value and call by reference

Python utilizes a system, which is known as “Call by Object Reference” or “Call by assignment”. In the event that you pass

arguments like int,float, strings or tuples to a function, the passing is like call-by-value because you can not change the value of

the immutable objects being passed to the function. Whereas passing mutable objects like list can be considered as call by

reference because when their values are changed inside the function, then it will also be reflected outside the function.

Example of call by value

def change(a):

a=a+1

print("Inside Function a=",a)

a=5

35
change(a)

print("Outside Function: a=", a)

Output

Inside Function a=6

Outside Function a=5

Example of call by reference

De fadd_more(list):

list.append(50)

print("Inside Function", list)

list = [10,20,30,40]

add_more(list)

print("Outside Function:", list)

Output

Inside Function [10, 20, 30, 40, 50]

Outside Function: [10, 20, 30, 40, 50]

36
Note:

A mutable object can be changed after it is created, and an immutable object can't. ... Objects of built-in types like (int, float,

bool, str, tuple) are immutable. Objects of built-in types like (list, set, dict) are mutable.

Random number generation

Python defines a set of functions that are used to generate or manipulate random numbers through the random module.

Functions in the random module rely on a pseudo-random number generator function random(), which generates a random

float number between 0.0 and 1.0. These particular type of functions is used in a lot of games, lotteries, or any application

requiring a random number generation.

random():- This method is used to generate a float random number less than 1 and greater or equal to 0.

Example program

import random

print(random.random())

print(random.randint(1,100)) # print random number bwtween 1 and 100

choice() :- choice() is an inbuilt function in the Python programming language that returns a random item from a list, tuple, or

string.

import random

list1 = [1, 2, 3, 4, 5, 6]

print(random.choice(list1))

37
# prints a random item from the string

string = "welcome"

print(random.choice(string))

randrange(beg, end, step):- The random module offers a function that can generate random numbers from a specified range

and also allowing rooms for steps to be included, called randrange().

randint(beg,end) :- this function can generate random number from a specified range

random.randint(0, 9) Returns any random integer from 0 to 9

random.randrange(2, 20, 2) Returns any random integer from 2 to 20 with step 2

random.randrange(100, 1000, 3) Returns any random integer of specific length 3

math Module

Python has a built-in module that you can use for mathematical tasks.

The math module has a set of methods. They are

fabs(x)

Return the absolute value of x.

factorial(x)

Return x factorial as an integer

ceil(x)

Return the ceiling of x, the smallest integer greater than or equal to x.

38
floor(x)

Return the floor of x, the largest integer less than or equal to x

gcd(*integers)

Return the greatest common divisor of the specified integer arguments

isfinite(x)

Return True if x is neither an infinity nor a NaN, and False otherwise

isnan(x)

Return True if x is a NaN (not a number), and False otherwise.

pow(x, y)

Return x raised to the power y.

sin(x)

Return the sine of x radians.

cos(x)

Return the cosine of x radians.

tan(x)

Return the tangent of x radians.

Modules in python

39
A module is simply a Python file with a .py extension that can be imported inside another Python program. The name of the

Python file becomes the module name. The module contains definitions and implementation of classes, variables, and

functions that can be used inside another program.

Creating a module

defprintme():

print("welcome to printme function")

def add(a,b):

print(a+b)

def sub(a,b):

print(a-b)

name="nishitha"

save the above file as my.py and execute it. Then module name becomes my

Importing a module (using a module)

import my

40
my.printme()

print(my.name)

print(my.add(4,5))

print(my.sub(10,5))

File Handling in Python

Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file

handling options, to operate on files.

Following are some of the built in functions to work with the files

Open()

Before performing any operation on the file like read or write, first we have to open that file. For this, we should use Python’s

inbuilt function open()

But at the time of opening, we have to specify the mode, which represents the purpose of the opening file.

syntax

f = open(filename, mode)

different modes of file operation

r: open an existing file for a read operation.

w: open an existing file for a write operation. If the file already contains some data then it will be overridden.

a: open an existing file for append operation. It won’t override existing data.

r+: To read and write data into the file. The previous data in the file will not be deleted.

41
w+: To write and read data. It will override existing data.

a+: To append and read data from the file. It won’t override existing data.

write()

it is used to write the data in to the file

read()

it is used to read data from the file

append()

it is used to add data to the end of the file

close()

it is used to close the file

# Python code to create a file

file = open('abc.txt','w')

file.write("This is the write command")

file.write("It allows us to write in a particular file")

file.close()

# Python code to read a file

file = open('abc.txt', 'r')

42
print (file.read( )) # read all the contents

file.close()

file=open('abc.txt','r')

print (file.read(6)) #read 6 characters

file.close()

usig loops to process the files

# a file named "abc.txt", will be opened with the reading mode.

file = open('abc.txt', 'r')

# This will print every line one by one in the file

for each in file:

print (each)

excepton handling

exception is an error which will occur while executing the program. The process of handling the exceptions are called as

exception handling. For this python provided try and except statements

try will try the exceptions and except is used to handle the exceptions

# Python program to handle simple runtime error (exception)

a = [1, 2, 3]

43
try:

print ("Second element = ",a[1])

# Throws error since there are only 3 elements in array

print ("Fourth element = " ,a[3])

except:

print ("An error occurred")

Sequences
In Python, sequence is the generic term for an ordered set. There are several types of sequences in Python;
the following three are the most important.

Lists are the most versatile sequence type. The elements of a list can be any object, and lists are mutable -
they can be changed. Elements can be reassigned or removed, and new elements can be inserted.

Tuples are like lists, but they are immutable - they can't be changed.

Strings are a special type of sequence that can only store characters, and they have a special notation.
However, all of the sequence operations described below can also be used on strings.

Sequence Operations

+ combines two sequences in a process called concatenation. For example, [1,2,3]+[4,5] will evaluate to
[1,2,3,4,5].

* repeats a sequence a (positive integral) number of times. For example, [1,11]*3 will evaluate to
[1,11,1,11,1,11].

x in mySeq will return True if x is an element of mySeq, and False otherwise. You can negate this
statement with either not (x in mySeq) or x not in mySeq.

mySeq[i] will return the i'th character of mySeq. Sequences in Python are zero-indexed, so the first
element has index 0, the second has index 1, and so on.

44
mySeq[-i] will return the i'th element from the end of mySeq, so mySeq[-1] is the last element of mySeq,
mySeq[-2] is the second-to-last element, etc.

All sequences can be sliced.

Useful Functions

len(mySeq), short for length, returns the number of elements in the sequence mySeq.

Searching

mySeq.index(x) returns the index of the first occurrence of x in mySeq. Note that if x isn't in mySeq
index will return an error. (Use in with an if statement first to avoid this.)

min(mySeq) and max(mySeq) return the smallest and largest elements of mySeq, respectively. If the
elements are strings this would be the first and last elements in lexicographic order (the order of words in
a dictionary). Note that if any two elements in mySeq are incomparable (a string and a number, for
example), min and max will return errors.

mySeq.count(x) returns the number of occurrences of x in mySeq (that is, the number of elements in
mySeq that are equal to x).

List
Lists are used to store multiple items in a single variable.

Lists are the most versatile sequence type. The elements of a list can be any object, and lists are mutable -
they can be changed. Elements can be reassigned or removed, and new elements can be inserted.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set,
and Dictionary, all with different qualities and usage.

Lists are created using square brackets [ ]:

Example

Create a List:

fruits = ["apple", "banana", "cherry"]

print(fruits)

List items are ordered, changeable, and allow duplicate values.

List items are indexed, the first item has index [0], the second item has index [1] etc.

45
When we say that lists are ordered, it means that the items have a defined order, and that order will not
change.

Note: There are some list methods that will change the order, but in general: the order of the items will
not change.

The list is changeable, meaning that we can change, add, and remove items in a list after it has been
created.

Since lists are indexed, lists can have items with the same value:

Example

fruits = ["apple", "banana", "cherry", "apple", "cherry"]

print(fruits)

List Slicing

In Python, list slicing is a common practice and it is the most used technique for programmers to solve
efficient problems. Consider a python list, In-order to access a range of elements in a list, you need to
slice a list. One way to do this is to use the simple slicing operator i.e. colon(:)

With this operator, one can specify where to start the slicing, where to end, and specify the step. List
slicing returns a new list from the existing list.

Syntax:

Lst[ startl : End : IndexJump ]

a=[1,2,3,4,5,6,7,8]

print(a) # print all the elements

print(a[::]) # print all the elements

print(a[2:]) # print from thid elemt o/p 3 4 5 6 7 8

print(a[:3]) # print first 3 elemts o/p 1 2 3

print(a[: : 2]) o/p 1 3 5 7 # 2 is stop value

print(a[2 : 6 : 2]) o/p 3 5

searching in the list

46
fruits=["apple","banana","orange","mango","cherry","papaya"]

print(fruits)

a=input("enter the fruit name to search")

if a in fruits:

print("found")

else:

print("not found")

List methods

Python has a set of built-in methods that you can use on lists.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position by default last value

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

append(): Used for appending and adding elements to List. It is used to add elements to the last position
of List.

47
Syntax:

list.append (element)

ex: names=["prasad","raju","srinu","venu","madhu"]

names.append(“ramu”)

copy() it is used to copy the list

ex:

a=[5,3,1,8,45,32]

b=a.copy()

print(b)

count():Calculates total occurrence of given element of List.

Syntax:

List.count(element)

extend(): Adds contents of List2 to the end of List1.

Syntax:

List1.extend(List2)

Ex:

a=[1,2,3,4,5]

b=[10,11,12]

a.extend(b)

print(a)

o/p [1, 2, 3, 4, 5, 10, 11, 12]

index(): Returns the index of first occurrence. Start and End index are not necessary parameters.

Syntax:

List.index(element[,start[,end]])

48
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]

print(List.index(2)) o/p 1

print(List.index(2,2)) o/p 4 # search from 2nd index

# will check from index 2 to 4.

print("After checking in index range 2 to 4")

print(List.index(2,2,5))

insert(): Inserts an elements at specified position.

Syntax:

list.insert(position, element)

ex:

names.insert(2,”aaa”)

pop(): Index is not a necessary parameter, if not mentioned takes the last index.

Syntax:

list.pop([index])

remove(): Element to be deleted is mentioned using list name and element.

Syntax:

list.remove(element)

sort(): It is used to sort the list elements

ex:

a=[5,3,1,8,45,32]

a.sort()

print(a)

reverse() : it is used to reverse the elements of the list

a=[5,3,1,8,45,32]

49
a.reverse()

print(a)

sum() : Calculates sum of all the elements of List.

Syntax:

sum(List)

Len():Calculates total length of List.

Syntax:

len(list)

min() : Calculates minimum of all the elements of List.

Syntax:

min(List)

max(): Calculates maximum of all the elements of List.

Syntax:

max(List)

example program of list operations

names=["prasad","raju","srinu","venu","madhu"]

print(names)

print(len(names))

print("the firs name in names is",names[0])

marks=[45,67,43,21,89,43]

print("min marks",min(marks))

print("max marks",max(marks))

50
print("43 repeated ",marks.count(43)," times")

print("concatination of two lists",names+marks)

print("names two times",names*2)

print("venu is in this list ",'venu' in names)

print("50 marks is not in the marks list", 50 not in marks)

print("the 3rd items in the names list is",names[2])

print("the last but item in the list is",names[-2])

print("the index values of prasad is ",names.index('prasad'))

program to print values from list using for loop

list=[1,2,3,4,5,6]

for i in list:

print(i)

for i in range(0,5): # print 0 to 4 nos

print(i)

for i in range(0,len(list)):

print(list[i])

Multi-dimensional lists

There can be more than one additional dimension to lists in Python. Keeping in mind that a list can hold
other lists, that basic principle can be applied over and over. Multi-dimensional lists are the lists within
lists. Usually, a dictionary will be the better choice rather than a multi-dimensional list in Python.

51
a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]

print(a) o/p[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]

Accessing with the help of loop

# Python program to demonstrate printing

# of complete multidimensional list row by row.

a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]

for record in a:

print(record)

o/p [2, 4, 6, 8, 10]

[3, 6, 9, 12, 15]

[4, 8, 12, 16, 20]

# accessing one by one element

a = [ [2, 4, 6, 8 ],

[ 1, 3, 5, 7 ],

[ 8, 6, 4, 2 ],

[ 7, 5, 3, 1 ] ]

for i in range(len(a)) :

for j in range(len(a[i])) :

print(a[i][j], end=" ")

print()

Output:

2468

1357

8642

52
7531

Tuple
Tuples are used to store multiple items in a single variable.

A tuple is a collection which is ordered and unchangeable (immutable).

Tuples are written with round brackets. ( ) (paranthesis)

Ex:

fruits = ("apple", "banana", "cherry")

print(fruits)

Tuple items are ordered, unchangeable, and allow duplicate values.

Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been
created.

Tuple methods

Count()

Index()

Min()

Max()

Len()

Example program for tuple

a=(1,2,3,4,5,6,7,8)

print(a)

print("the first element is ",a[0])

print("the last element is ",a[-1])

print("the 5 is in the tuple ",5 in a)

print("the 9 is not in the tuple",9 not in a)

print("sum of values = ",sum(a))

53
print("min value from tuple is ",min(a))

print("max value from tuple is",max(a))

print("5 is repeated",a.count(5),"times")

print("the index of 7 is ",a.index(7))

print("the length of tuple is ",len(a))

program to display tuple values using for loop

sub=("maths","computers","physics","english","telugu")

print(sub)

for i in sub:

print(i)

Strings
String is nothing but a group of characters. Strings in Python can be created using single quotes or double
quotes or even triple quotes.

Ex:

S1=’welcome to python programming’

S2=”welcome to string operations”

S3='''welcome to python programming'''

Accessing characters from string

In Python, individual characters of a String can be accessed by using the method of Indexing. Index starts
from 0. Indexing allows negative address references to access characters from the back of the String, e.g.
-1 refers to the last character, -2 refers to the second last character, and so on.

While accessing an index out of the range will cause an IndexError. Only Integers are allowed to be
passed as an index, float or other types that will cause a TypeError.

54
0 1 2 3 4 5 6

W e l c o m e

-7 -6 -5 -4 -3 -2 -1

S1=”welcome”

print(“first character in the string is “,s1[0])

print(“last character in the string is “,s1[-1])

String Slicing

To access a range of characters in the String, the method of slicing is used. Slicing in a String is done by
using a Slicing operator (colon).

S1=”welcome to python programming”

s1="welcome to python programming"

print(s1)

print("string from 4th character ",s1[3:]) # disply from 4th character (index 3)

print("string from index 3 to 9",s1[3:10]) # display from index 3 (4th char) to index 9 (10th char)

print("first 3 characters are",s1[:3]) # disply first 3 characters

print("characters from 3 to last but character ",s1[2:-2])

Deleting/Updating from a String

In Python, Updating or deletion of characters from a String is not allowed. This will cause an error because
item assignment or item deletion from a String is not supported. Although deletion of the entire String is
possible with the use of a built-in del keyword. This is because Strings are immutable; hence elements of a
String cannot be changed once it has been assigned. Only new strings can be reassigned to the same name.

String methods

Method Description

capitalize() Converts the first character to upper case

count() Returns the number of times a specified value occurs in a string

55
endswith() Returns true if the string ends with the specified value

index() Searches the string for a specified value and returns the position of where it was found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

lower() Converts a string into lower case

startswith() Returns true if the string starts with the specified value

swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case

upper() Converts a string into upper case

# program for string functions

word="welcome"

rollno="101"

name="Prasad"

print(word.isalnum()) #check if all char are alphanumeric

print( word.isalpha()) #check if all char in the string are alphabetic

print(rollno.isdigit()) #test if string contains digits

56
print(name.istitle()) #test if string contains title words

print(word.isupper()) #test if string contains upper case

print(word.islower()) #test if string contains lower case

print(word.isspace()) #test if string contains spaces

print(word.endswith('e')) #test if string endswith a d

print(word.startswith('we')) #test if string startswith H

sets
Sets are used to store multiple items in a single variable. It is a collection which is unordered, un indexed
and do not allow duplicate values. Sets are created by using { }

Ex:

S1={1,2,3,4,5}

S2={10,20,30,40,50}

Set methods

Method Description

add() Adds an element to the set

clear() Removes all the elements from the set

copy() Returns a copy of the set

pop() Removes an element from the set

remove() Removes the specified element

57
Program for set operations

s1={1,2,3,4,5}

s2={10,20,30,40,50}

# print(s1[0]) invalid sets are not subscriptable because they are unordered

print(s1)

print(len(s1))

s1.add(10) # adding an element to set

print("after adding 10 to set ",s1)

s1.pop()

print("after pop ",s1)

s3=s1.copy()

print("after copying ",s3)

s3.clear()

print("after clear s3 is ",s3)

s2.remove(30)

print("after removing 30 s2 is",s2)

print(s1|s2) # union operator |

print(s1&s2) # insersect operator &

print(s1-s2) #difference operator -

Dictionary
Dictionary in Python is an unordered collection of data values, used to store data values unlike other Data
Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided
in the dictionary to make it more optimized.

In Python, a Dictionary can be created by placing a sequence of elements within curly { } braces, separated
by ‘comma’. Dictionary holds pairs of values, one being the Key and the other corresponding value. Values

58
in a dictionary can be of any data type and can be duplicated, whereas keys can’t be repeated and must be
immutable.

Dictionary methods

Method Description

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

values() Returns a list containing the dictionary’s values

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

Program for dictionary

a={1:70,2:67,3:90,4:44,5:87} # rollnos and marks

print(a)

print(a.keys())

print(a.values())

print(a[2]) # print the value of key 2

59
b=a.copy()

print("after copying",b)

b.clear()

print("after the clear the dictionary ",b)

a.pop(2)

print("after removing key 2 is ",a)

a.popitem()

print("after pop item",a)

stu={"rollno":101,"name":"raju","marks":60}

print(stu)

print("rollno is ",stu["rollno"])

print("name is ",stu["name"])

print("marks = ",stu["marks"])

Recursion

It is a process in which a function calls itself here calling function and called functions are same.

The term Recursion can be defined as the process of defining something in terms of itself

Advantages of using recursion

A complicated function can be split down into smaller sub-problems utilizing recursion.

Sequence creation is simpler through recursion than utilizing any nested iteration.

Recursive functions render the code look simple and effective.

Disadvantages of using recursion

A lot of memory and time is taken through recursive calls which makes it expensive for use.

60
Recursive functions are challenging to debug.

Def abc()

------

------

abc()

Example 1:

A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....

# Program to print the fibonacci series upto n_terms

def fibo(n):

if n <= 1:

return n

else:

return(fibo(n-1) + fibo(n-2))

n = 20

# check if the number of terms is valid

if n <= 0:

print("Invalid input ! Please input a positive value")

else:

print("Fibonacci series:")

for i in range(n):

print(fibo(i))

61
Example 2:

The factorial of 6 is denoted as 6! = 1*2*3*4*5*6 = 720.

# Program to print factorial of a number recursively.

# Recursive function

def recursive_factorial(n):

if n == 1:

return n

else:

return n * recursive_factorial(n-1)

# user input

num = 6

# check if the input is valid or not

if num < 0:

print("Invalid input ! Please enter a positive number.")

elif num == 0:

print("Factorial of number 0 is 1")

else:

print("Factorial of number", num, "=", recursive_factorial(num))

Object Oriented Programming

62
In Python, object-oriented Programming (OOPs) is a programming paradigm that uses objects and
classes in programming. It aims to implement real-world entities . The main concept of OOPs is
to bind the data and the functions that work on that together as a single unit so that no other part
of the code can access this data.

Main Concepts of Object-Oriented Programming (OOPs)

Class

Objects

Polymorphism

Encapsulation

Inheritance

Class
A class is specification of an object where it contain two thing variables and functions.A class is a
collection of objects. A class contains the blueprints or the prototype from which the objects are
being created. It is a logical entity that contains some attributes and methods.

In the python class is created using a keyword called class. Attributes are the variables that belong
to a class.

Syntax:

class ClassName:

# Statement-1

# Statement-N

Object
Instance of a class is called an object. The object is an entity that has a state and behavior associated
with it. It may be any real-world object like a mouse, keyboard, chair, table, pen, etc.

An object consists of :

63
State: It is represented by the attributes of an object. It also reflects the properties of an object.

Behavior: It is represented by the methods of an object. It also reflects the response of an object
to other objects.

Identity: It gives a unique name to an object and enables one object to interact with other objects.

Syntax

Objectname=classname( )

The self

Class methods must have an extra first parameter in the method definition. We do not give a value
for this parameter when we call the method, Python provides it

If we have a method that takes no arguments, then we still have to have one argument.

This is similar to this pointer in C++ and this reference in Java.

The __init__ method

The __init__ method is similar to constructors in C++ and Java. It is run as soon as an object of a
class is instantiated. The method is useful to do any initialization you want to do with your object.

Example program
class stu:

rollno=10

name="abc"

def disp(self):

print("rollno ",self.rollno)

print("name ",self.name);

s1=stu() # creating object

64
s1.disp()

example 2
class stu:

rollno=10

name="abc"

def store(self,r,n):

self.rollno=r

self.name=n

def disp(self):

print("rollno ",self.rollno)

print("name ",self.name);

s1=stu() # creating object

s1.disp()

s2=stu()

s2.store(20,"xyz")

s2.disp()

inheritance
It is a process of creating new class from an existing class. Here existing
class is called as base class(super,parent class) and new class is called as
sub class (derived ,child class).

65
Derived class inherits features from the base class where new features can
be added to it. This results in re-usability of code.
Syntax
class BaseClass:
Body of base class

class DerivedClass(BaseClass):
Body of derived class
Example program for inheritance
class Person: # creating person class

def __init__(self, name, age):

self.name = name

self.age = age

def printperson(self):

print(self.name, self.age)

class Student(Person): #creating student class from person class

def __init__(self, name, age, rollno, marks):

super().__init__(name, age)

self.rollno = rollno

self.marks=marks

def printstudent(self):

print("name ", self.name)

print("age ",self.age)
66
print("rollno ",self.rollno)

print("marks ",self.marks)

x = Student("rajkumar",20,101,80)

x.printstudent()

Polymorphism
The word polymorphism means having many forms i.e Using same entity in many ways. This can
be achieved in many ways in that one way is function overloading

Function overloading means same function name (but different signatures) being used for different
types.

Polymorphism in addition operator

num1 = 1

num2 = 2

print(num1+num2)

str1 = "Python"

str2 = "Programming"

print(str1+" "+str2)

here + operator is used to add two integers and same operator is used to concatenate two strings

Function Polymorphism in Python


print (len("Programing"))

print (len ( ["Python", "Java", "C"] ) )

print (len ( {"Name": "John", "Address": "Nepal"} ) )

67
Polymorphism in Class Methods
class Cat:

def __init__(self, name, age):

self.name = name

self.age = age

def info(self):

print(f"I am a cat. My name is {self.name}. I am {self.age} years old.")

def make_sound(self):

print("Meow")

class Dog:

def __init__(self, name, age):

68
self.name = name

self.age = age

def info(self):

print(f"I am a dog. My name is {self.name}. I am {self.age} years old.")

def make_sound(self):

print("Bark")

cat1 = Cat("Kitty", 2.5)

dog1 = Dog("Fluffy", 4)

for animal in (cat1, dog1):

animal.make_sound()

animal.info()

animal.make_sound()

output

Meow

I am a cat. My name is Kitty. I am 2.5 years old.

Meow

Bark

I am a dog. My name is Fluffy. I am 4 years old.

Bark

69

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy