0% found this document useful (0 votes)
60 views91 pages

Core Python Notes - Reference For Teachers Eshwar Computers

This document provides an overview of the Python programming language. It discusses that Python is a high-level, interpreted language useful for many applications like desktop apps, web apps, databases, games, networking, data analysis, machine learning, AI, IoT, and cloud computing. The document outlines Python's history and key features, including being object-oriented, portable, having a large standard library, and being easy to learn. It also notes some drawbacks like performance and limited mobile use. Different Python versions and software flavors are described. The document concludes with definitions of identifiers in Python.

Uploaded by

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

Core Python Notes - Reference For Teachers Eshwar Computers

This document provides an overview of the Python programming language. It discusses that Python is a high-level, interpreted language useful for many applications like desktop apps, web apps, databases, games, networking, data analysis, machine learning, AI, IoT, and cloud computing. The document outlines Python's history and key features, including being object-oriented, portable, having a large standard library, and being easy to learn. It also notes some drawbacks like performance and limited mobile use. Different Python versions and software flavors are described. The document concludes with definitions of identifiers in Python.

Uploaded by

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

core python notes – Reference

For teachers
eshwar computers
CORE

Eshwar K 4/24/20
CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

About language
Depends on the programming style the computer languages are mainly
classified into 3 major categories
They are like: -
A. High level language
B. Low level language
C. Middle level language
High - level language: -
This type of language developed foe humans. It is also called as
business-oriented language. The format of this language is universal English
language.
Now a days we are having so many high-level languages.
They are like: -
1. C-language
2. Basic
They are not using from 2000 because they not work in
main frame computers
3. Cobol
4. Python & other languages
Low level language: -
It is developed for the computer the format of this language is [0,1]. In this
reason it is also called binary language (or) machine level language
Middle level language: -It is the combination of high level and low-level
languages it is also called assembled languages.

Types of execution methods (Translators): -


Depends on the execution style the languages are mainly classified
into two major categories
They are like: -
a. Compiler’s oriented
b. Interpreted oriented
1. Compilers: -it is one of the famous translators. Now a days most of the
languages are compiler-oriented languages
By using compiler, we can perform following operations before
execution of program

They are like: -


i. To check all types of syntax and grammatical errors.

CREATED AT TECHNOSOFT TENALI 1


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

ii. It converts high level to low level format (0,1). After this
process we can run our program.
Note: - it is very fastest translator because at the time of execution it
never stops the process
Now a days we are having so many compilers-oriented languages
they are like c, c++, java etc.,
2. Interpreter: -it is another famous translator using this translator we can
perform following operations at the time of program execution.

They are like: -


i. To check all types of syntax and grammatical errors.
ii. It converts high level to low level format (0,1). After this
process we can run our program.
Note: -in this translator the program execution is very slow and it is
interpreted ‘n’ number of times.
Ex: - Python

ABOUT
PYTHON
Python is general purpose of high-level language with interpreter
technology.

CREATED AT TECHNOSOFT TENALI 2


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Python was developed by “Guido Van Rossum” in 1989 while,


working at national research institute at Netherlands.

But officially python was made available to public in 1991. The


official date of birth for python is: -20/February/1991.

Python is recommended as first programming language for


beginners (recommended for only C learners).

Applications of Python
Where we can use python?
We can use everywhere. The most common important application areas
are: -

1. For developing desktop applications


2. For Web applications
3. For database application
4. For games

CREATED AT TECHNOSOFT TENALI 3


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

5. For networking applications


6. For data analysis application
7. For machine learning
8. For Artificial Intelligence
9. For Internet of Things (IOT)
10.Cloud Computing.
Note: Google and you tube uses python coding NASA and Network Stocks
exchange applications development by python. Top software companies like
GOOGLE, IBM, YAHOO by using python.
Features of Python
Basically, it is a hundred percent object-oriented programming language
having the following important operations.
1) Simple and easy to learn

2) Free ware and open source

3) High level Programming language

4) Platform independent
Once we write a python program it can run on any platform without
rewriting again. Initially python virtually machine is responsible to convert
into machine understandable form. Python programs can migrate.

5) Portability
It is migrated easily

6) Dynamically Typed
In python we are not required to declare any type for variables.
Whenever we are assigning the value, based on value type will be located
automatically. Hence python is considered as dynamically typed language.
But JAVA, C,C++ are statically typed languages because we have to
provide type at beginning only.
7) Both procedure oriented and object oriented
Python supports both procedures oriented like C, PASCAL etc…. and
object oriented like C++, JAVA features. Hence, we can get benefits of both
like security and reusability.
8) Interpreted

CREATED AT TECHNOSOFT TENALI 4


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

We are not required to compile python programming explicitly,


internally python interpreter will take care that compilation.
If complication fails interpreter raises syntax bugs (errors). Once
compilation success then PVM (python virtual machine) responsible to
execute
9) Extensible
we can use other language programs in python. The main
advantages of this approach
 We can use already existing legacy non-python code.
 We can improve performance of the application.

10) Embedded
We can use python programs in any other language’s . We can
embed python programs anywhere.

11) Extensive Library


Python has a strong inbuilt library. Being a programming, we can use
this library directly and we are not responsible to implement the
functionality, etc...,

Drawbacks of Python
1. Performance wise it is not up to the mark because it is interpreted
language
2. Not using mainly for mobile applications.

Available software’s for Python:


The original software of python is python and we are having so many other
customized software’s.
They are like: -
1) C python
It is the standard flavour of python. it can be used to work with C
language application.
2) J python
It is used for java applications can run on Java virtual machines.
3) PY python
The main advantage of py is performance will be improved
because its compiler is available inside python virtual machine.

CREATED AT TECHNOSOFT TENALI 5


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

4) Ruby Python
It is used mainly for the ruby platforms.
5) Anaconda python
It is specially designed for handling large volume of data
processing.

Available Versions
The first official version of python is python 1.0 in January 1994. Later it
contains so many other versions. It is mainly divided into two versions like,
 Python 2.0 and python 3.0
The python- 2.0 is limited version it is not continued after 2020. The
current version is python 3.10.0
Python 3.10.0 – OCT-4th, 2021
Note that Python 3.10.0 cannot be used on Windows XP or earlier

Identifiers: -
A name in python program is called identifiers. It can be a class
name or function name or modules name or a variable name
Rules to define identifiers in python
1. The only allowed characters in python are
I. Alphabet symbols (either lower case and upper case)
II. Digits (0 to 9)
III. Underscore symbol (_)

By mistake if we are using any other symbol like $ then we will get

syntax error
 Cash = 20 (write)
 Ca$h = 20 (wrong)
2. Identifiers should not start with digits
 123total=100 (wrong)
 Total123=100 (write)
3. Identifiers are case sensitive. Of course, python language is case sensitive
language

CREATED AT TECHNOSOFT TENALI 6


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

 total=10
 TOTAL = 999
Print (total) #10
Print (TOTAL) #999
4. We cannot use reserved words as identifiers
Eg: - def = 10 (wrong)
5. There is no length limit for python identifiers
6. If identifiers are start with underscore (_) then it indicates it is private
7. If identifiers start with __ (two underscore symbols) indicates that
strongly private identifiers
8. If the identifiers start and ends with two underscore symbols then the
identifier is language defined special name, which is also known as magical
method or constructor method
Ex: __ abc __

Python available data types


1) Int
2) Float
3) Complex
4) Bool
5) Str
6) Bytes
7) Byte array
8) Range
9) List
10) Tuple
11) Set
12) Frozen set
13) Dict
14) None
Steps for programming: -
 We have to install any one of the python software
 To check python existence
 Goto command prompt
 Then type python
 It will display python interphase (>>>)
 We have to create one folder into any one of the drives
 By using any one of the editors create a file and save the file with
extinction of .py

CREATED AT TECHNOSOFT TENALI 7


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

 To run our program, we can use python keyword or py keyword


under command prompt
Ex: - py filename.py or python filename.py
Programming operations
Print (): - it is standard output function by using this function we can perform all
types of printing operations.
Syntax: -
Print (var_ name) ex: print(a)
Print (“message”) ex: print(“hello”)
Print (‘message’) ex: print(‘hello’)
Print (var_ name, “message”) ex: print (“A Value Is”, a)
Escape characters: -
1. \n  new line
2. \t  Horizontal line
3. \r  Carriage return
4. \b  Back space
5. \f  form feed
6. \v  vertical tab
7. \’  single quote
8. \”  double quote
9. \\  back slash symbol

Ex: - 1
>>> s = “Lakshman \n Kumar”
>>> print (s)
>>> Lakshman
>>> Kumar
Ex: - 2
>>> s = “This is symbol \” Lakshman\””
>>> print (s)
>>> This is symbol “Lakshman”
Ex: - 3
>>> a = 10
>>> b = 3
>>> print (“A is: “, a,” \n”,” b is:”, b,” \n”,” the sum is”, (a + b),” \n”)
13
1) Write a program to print a message called “Welcome to Python”?
Print ("\”Welcome to python\”")

CREATED AT TECHNOSOFT TENALI 8


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

2) Write a program to display sum of the given numbers like 10 and 13


a=10
b=3
print("A value is:",a)
print("B value is:",b)
print("The sum is:",(a+b))

Type (): -By using this function we can display data type of particular variable
sno=1
sname="Lakshman"
avg=85.666
print ("stuno is:", sno)
print ("stu name is:", sname)
print ("stu Avg is:", avg)
print ("stu No data type is:", type(sno))
print ("stu Name data type is:", type(sname))
print ("stu Avg data type is:", type(avg))
output: -
stuno is: 1
stu name is: Lakshman
stu Avg is: 85.666
stuno data type is: <class 'int'>
stu data type name is: <class 'str'>
stu data type Avg is: <class 'float'>

Compound assignment: - in this concept in a single statement we can assign


different values into different variables.

CREATED AT TECHNOSOFT TENALI 9


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

a, b, c=10,20,30
print ("A is ", a)
print ("B is ", b)
print ("C is ", c)
output: -
A is 10
B is 20
C is 30
Program for variables swapping
By using third variable concept
a, b=10,20
print ("Values Before swapping")
print ("A value is:", a)
print ("B value is:", b)
c=a
a=b
b=c
print ("Values After swapping")
print ("A value is:", a)
print ("B value is:", b)

Python program for swapping


a, b=10,20
print ("Values Before swapping")
print ("A value is:", a)
print ("B value is:", b)
a, b=b, a
print ("Values After swapping")
print ("A value is:", a)
print ("B value is:", b)

CREATED AT TECHNOSOFT TENALI 10


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

del: - by using this keyword we can delete particular memory variable


permanently
a=10
print ("A value is:", a)
del a
print ("A value is", a)
output: -
A value is: 10
Traceback (most recent call last):
File "L7.py", line 4, in <module>
print ("A value is", a)
Name Error: name 'a' is not defined
sep (): -with the help of this keyword we can specify value separator depends
on the given symbol.
example: -
print(1,2,3,4,sep(*))
print(1,2,3,4,sep($))
print(1,2,3,4,sep(-))

ord (): -By using this function we can display ASCII value of particular letter
ASCII: - American standard code information interchange
Example: -
ch='A'
print("The ASCII value of A letter is:",ord(ch))

CREATED AT TECHNOSOFT TENALI 11


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Input (): - it is one of the data input function. By using this function, we can
enter any type of information through keyboard. The complete data treated
as string format means unable to perform mathematical operations
To ratify this problem, we have to convert data into numerical
format by using conversation functions like: -
 Int
 Eval
Syntax: -
Var _ name= input(“message”)
3) Write a program enter any two integer values then display the sum of two
numbers.
num1=input("Enter first number:")
num2=input("Enter second number:")
add=num1+num2
print("Addition=",add)

Example 2: -
num1=input("Enter first number:")
num2=input("Enter second number:")
add=int(num1)+int(num2)
print("Addition=",add)

Example 3: -
num1=input("Enter first number:")
num2=input("Enter second number:")
add=eval(num1)+eval(num2)
print("Addition=",add)

CREATED AT TECHNOSOFT TENALI 12


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Try This: -
1) Write a program enter any two integer values then perform all arithmetical
operations?
2) Write a program enter student number, name and address then display the
accepted data?
3) Write a program enter student number, name and Three subjects’ marks then
find total and average marks?
By using compound Assignment concept to print employee number, name &
salary
empno,empname,salary=1,"BL",50000
print("Emp number:",empno,"\nEmp name:",empname,"\nEmp salary:",salary)

Percentage operations: -
In print function we can apply C language percentage operators
for printing information. the available operators are
1. % d to print integer values
2. % g to print floating values
3. % s to print string values
4. % c to print single letter
Example: -
empno,empname,salary=1,"Deva",5000.65
print ("Emp number: %d\n Emp name: %s\n Emp salary: %g"% (empno, empname,
salary))

CREATED AT TECHNOSOFT TENALI 13


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Print with format{}: -


It is one of sub option of print function by using this function we can
print any type of data . Basically, it is used for unexpected output.
Ex: -
empno, empname, esal=101,"lucky",50000.45
print ("Emp no: {} \n Emp name: {} \n Emp sal: {}". format (empno, empname,
esal))

Example 2: -
empno, empname, esal=101,"lucky",50000.45
print ("Emp no: {0} \n Emp name: {1} \n Emp sal: {2}". Format (empno, empname, esal))

FUNCTIONS
User defined functions: -

CREATED AT TECHNOSOFT TENALI 14


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

In this concept we can develop our own functions these functions are
accessible anywhere of the program to create UDFs function we have to use a
keyword called def (definition).
Syntax: -
def fun_name():
pro state 1
Types of UDFs:
Depends on the programming style the UDFs are mainly classified
into followings categories
1. Function without parameters and without return value
2. Function with parameters
3. Function with return values
4. Function with parameters and with return values
5. Function with default arguments
6. Function with named arguments
7. Function overloading (no need to implement)
8. Function With “N” of arguments
9. Return More Than 1 Value.
10.Call By Value
11.Call By Ref

Function without parameters and without return value: -


In this concept the UDFs implement input operations processing and
output operations means the function controls entire logic

Syntax: -
def disc ():
print (“Hi BL”)
print (“Hi Lucky”)
disc () # function calling
output: -
Hi BL
Hi Lucky
Example: -
def show():
sname="Lakshman"
sno="4"
addr="tenalli"

CREATED AT TECHNOSOFT TENALI 15


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

print("Student name:",sname)
print("student numner:",sno)
print("Address:",addr)
show()

Try This: -
4) Create a function called emp in this function enter employee number,
name, salary, total days and present days then display net salary?
net salary= (salary/total days) * present days
5) Create a function called emp in this function enter employee number,
name, department, salary and address then display the expected
information with format option?
6) Create a function called stu in this function enter student number, name,
course, and three subject marks then find total and average marks (display
complete information with in percentage mode)?

Function with parameters: -


In this concept we have to accept values in the main program these
values we have to give at the time of function calling these values are called
parameters or arguments
Syntax:
Def fun _ name (var list):
Pro state 1
Pro state 2
Pro state 3
Example: -
def my (a, b):
print ("A value is:”, a)
print ("B value is:", b)
print (“The sum is:”,a+b)
my (12,16)

CREATED AT TECHNOSOFT TENALI 16


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Try This: -
7) In the main program enter two integers to pass these two values into a
function called swap this function performs swapping by using compound
assignment?
8) In the main program enter student number, name, course, to pass these
three values into a function called show the function will display all values?
9) In the main program enter employee number, name, salary, allowances,
deductions to pass salary, allowances and deductions into a function called
show and find out following things?
I. Gross  salary + allowances
II. Net salary  gross – deductions
Named arguments: -
It is one of the new concepts of python in this concept we can pass
function parameters values by using variables and the parameters order is not
important
Example: -
def mgs (id, name):
print ("Emp id is", id)
print ("Emp name is”, name)
mgs (1,'lucky')
mgs (name='BL', id=2) # named arguments

Function with return value: -


In this concept the function performs input and process operation
only means it returns output into main program.
To implement this concept, we have to use return statements.

Syntax: -

CREATED AT TECHNOSOFT TENALI 17


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

def fun _ name ():


input statement
process statement
return (output)
calling function: -
var = fun _ name ()
Example: -
def add():
a=10
b=20
c=a+b
print("A value is:",a)
print("B Value is:",b)
return(c)
x=add()
print("The sum is:",x)

Example 2: -
def emp():
eno=input("enter emp number:")
ename=input("Enter emp name:")
sal=input("Enter salary:")
td=input("Enter total days:")
pd=input("Enter present days:")
print("emp no:",eno)
print("emo name",ename)
print("emp sal",sal)
print("emp td",td)
print("emp pd",pd)
net=int(sal)/int(td)*int(pd)
return(net)
net=emp()
print("Net salary is:",net)

CREATED AT TECHNOSOFT TENALI 18


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Function with multiple return values: -


It is a new concept of python environment .in generally every
programming language the function returns single value only. But in python we
can return more than one value.
Example: -
def stu ():
sno=int (input ("Enter stu no:"))
sname=input ("Enter Stu name:")
cou=input ("Enter course:")
s1=int (input ("Enter sub 1 marks:"))
s2=int (input ("Enter sub 2 marks:"))
s3=int (input ("Enter sub 3 marks:"))
tot=s1+s2+s3
avg=tot/3.0
return (tot, avg)
tot, avg=stu ()
print ("Total marks:", tot)
print ("Average:", avg)

Try This: -
10) Create a function called info in this function Enter any two integer values then find out
sum, subtraction, multiplication, division return all values and display the function out
put?
Function with parameters and with return value: -

CREATED AT TECHNOSOFT TENALI 19


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

In this concept the function performs only calculation part means


the input and output operations will controlled by main program.
Syntax: -
def fun _ name(var list):
process stat
return(output)
Example: -
def sum(a,b):
c=a+b
return(c)
a=10
b=20
print("A is :",a)
print("B is :",b)
c=sum(a,b)
print("The sum is:",c)

Example 2: -
def sum(a,b):
c=a+b
return(c)
a=int(input("Enter A number:"))
b=int(input("Enter B number:"))
print("A is :",a)
print("B is :",b)
c=sum(a,b)
print("The sum is:",c)

Try This: -
11) In the main program enter Employee number, name, salary, total days, present days
into a function called info this function return net salary?

CREATED AT TECHNOSOFT TENALI 20


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

12) In the main program Enter student number, name and three subject marks to pass
three subject marks into a function called info it returns total, average marks and
grade?

Function with default arguments: -


It is one of the oops concept in this concept we have to specify
parameters values at the time of function declaration. These values are called
default arguments these are activated whenever we call a function with less
values

Example: -
def show (a=1, b=25):
print ("a is:", a)
print ("b is:", b)
show (12,16)
show (12)
show ()

Function overloading: -
The meaning of function overloading is redeclaration of existing
function. Because in other languages the function performs single task. Means
unable to perform more than one option. To implement this function
overloading concept, but in python we are not having this concept because by
default python supports multiple operation.
Example: -
def sum (a, b):
c=a + b
return(c)
a=eval (input ("Enter A value:"))
b=eval (input ("Enter B value:"))
c=sum (a, b)
print ("The sum is:", c)

CREATED AT TECHNOSOFT TENALI 21


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Function with ‘n’ number of arguments: -


It is one of the beautiful concepts in python. By using this concept we can
pass n number of arguments [mixed data type] at the time of function calling.it is
not supported by other Lang’s.
Example: -
def disp(*var):
for i in var:
print("var arg:",i)
disp(1,2)
disp(10,20,30)
disp(20,20.33,'lucky')

Conditional operations
By using python, we can implement all types of conditional
operations. To implement this concept, we are having following statements
1. If

CREATED AT TECHNOSOFT TENALI 22


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

2. If…. else
3. If… elif... else
If: - it is also called simple if statement by using this statement we can check only
true condition.
Syntax: -
If Cond:
Stat 1
Q: Write a program enter an integer value check whether it positive only?
a=int(input("Enter A number"))
if a>0:
print("A is Positive")

If…else: -it is extinction of simple if statement. By using this statement, we can


check the given expr is true or false.
Syntax: -
If Cond:
Stat 1
else:
Stat 2
(or)
Output_ var= T _ value if Cond else F _ value
(or)
Print (“T_ value” if Cond else “F _ value”)
Q: Enter one integer value then check weather if is positive or negative?
Model 1:
a=int(input("Enter A number"))
if a>0:
print("A is Positive")
else:
print("A is negitive")

Model2:
a=int(input(“Enter A number:”))
out=“A is positive” if (a>0) else “A is Negitive”
print(out)

CREATED AT TECHNOSOFT TENALI 23


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Model3:
a=int(input(“Enter A number:”))
print(“A is positive” if (a>0) else “A is Negitive”)

Try This: -
1) Enter one integer check weather even or odd?
2) Enter any two integer values then find out highest value?
3) Enter student number, name and three subject marks then find out total,avg
and check student is pass or fail? (avg >=35 then pass)

If…elif…if: -by using this statement we can check n number of conditions it is


also called multiple if statement.
Using this statement, we can also implement nested if operation.
Syntax: -
if Cond1:
Stat 1
elif Cond 2:
Stat 2
elif Cond 3:
Stat 3
---
----
else:
Final statement
Enter student number, name and three subject marks then find out total, average and
grade?
Grade as follows
average grade
>= 60 A
>= 50 B
>= 35 C sno=input("Enter Student number")
else: F

CREATED AT TECHNOSOFT TENALI 24


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

sname=input("Enter student name")


s1=eval(input("enter S1 marks:"))
s2=eval(input("enter S2 marks:"))
s3=eval(input("enter S3 marks:"))
tot=s1+s2+s3
avg=tot/3.0
print("total marksks:",tot)
print("average marks:",avg)
if (avg>=60):
print("grade is A")
elif (avg>=50):
print("Grade is B")
elif (avg>=35):
print("Grade is C")
else:
print("Student is FAIL")

Note: - In the above program we are generating grade without checking of subject wise
pass or fail to ratify this problem we nested if
sno=input("Enter Student number")
sname=input("Enter student name")
s1=eval(input("enter S1 marks:"))
s2=eval(input("enter S2 marks:"))
s3=eval(input("enter S3 marks:"))
tot=s1+s2+s3
avg=tot/3.0
print("total marksks:",tot)
print("average marks:",avg)
if (s1>=35 and s2>=35 and s3>=35):
if (avg>=60):
print("grade is A")
elif (avg>=50):
print("Grade is B")
elif (avg>=35):

CREATED AT TECHNOSOFT TENALI 25


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

print("Grade is C")
else:
print("Student is FAIL")

Enter any two integers values and also enter choice depends in the choice perform
Arithmetical operations the program output as follows
Enter A no: 10
Enter B no: 3
Menu
1. Sum
2. Sub
3. Mul
4. Div
Enter choice [1…4]: 1
Sum is: 13
a=int(input("Enter A no:"))
b=int(input("Enter B no:"))
print("Menu \n ----- \n 1.Sum \n 2.Sub \n 3.Div \n 4.Mul")
c=int(input("Enter Choice[1..4]:"))
if c==1:
print("The sum is:",a+b)
elif c==2:
print("The sub is:",a-b)
elif c==3:
print("The sum is:",a/b)
elif c==4:
print("The sum is:",a*b)
else:
print("Error choice")

CREATED AT TECHNOSOFT TENALI 26


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Try This: -
15) Enter Employee number, name and experience depends on experience find salary and
remaining?
experience salary
1–5 5000
6 - 10 10000
11 – 15 15000 Allowances 20% on salary
else 25000 Gross salary + allowances
Deductions 5% on gross
Net salary gross - deductions

16) In the main block enter student number, name and three subject marks into a function
called total it returns total marks to pass total marks into a function called average it
returns Average marks to pass average marks into a function called grade it returns
student grade?

Looping controls
The concept of looping is re-execution particular statement
into specified times to implement this concept we are having the following
statement
1. Single looping statements
2. Multiple looping statements
Single looping statements: -

CREATED AT TECHNOSOFT TENALI 27


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

By using this concept, we can print the information in the format of


either row wise or column wise to do this concept we are having the following
statement
They are like: -
1. For loop
2. While loop
For loop: - it is also called sequential looping. Because By using this looping
statement we can re execute particular block into n number of times
To implement for loop, we have a function called Range
Syntax: -
For var in range (exp):
Pro statement
Example: -
For x in range (10):
Print(x)

Example 2: -
For x in range (1,10):
print(x)

Write a program to print first 10 Even numbers?


for x in range (0,21,2):
print(x)

CREATED AT TECHNOSOFT TENALI 28


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Write a program enter your name then display specified times?


sname=input("Enter your name:")
i=int(input("Enter no of times:"))
for x in range (i):
print(sname)

Try This: -
17) Write a program to print 1 to 10 numbers and sum of 10 numbers?
18) Enter a number then display corresponding factorial value?
For…else: - the else part is executed whenever the for loop is closed without any
interruption.
Example 1: -
for i in range (1,5):
print(i)
else:
print("The loop is over")

Example 2: -
for i in range (1,10):

CREATED AT TECHNOSOFT TENALI 29


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

print(i)
if i==5:
break
else:
print ("The loop is over")

Note: - the above program loop cycle is 10 numbers but we are closing for loop
in the middle of the process. In this reason the else part will not be executed.
Write a program to identify even and odd numbers from 1 to 10?
for i in range (1,11):
if i%2==0:
print("Even numbers:",i)
else:
print("odd numbers:",i)

String Iteration: -
In python we can perform all types of string related operations. To
implement this concept, we have to use for in statement. By using this concept,
we can access letter by letter .
Ex: -
s='Lakshman Kumar'
for i in s:
print(i)

CREATED AT TECHNOSOFT TENALI 30


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Write a program enter a string then display the unexpected information?


s=input("Enter A string:")
for i in s:
print(i)

Write a program Enter a string then count number of upper case and lower case?
s=input ("Enter a string:")
l=0
u=0
for i in s:
if i>'Z':
l=l+1
else:
u=u+1
print("Lower Letters Are:",l)
print("upper Letters are:”,u)

Try This: -

CREATED AT TECHNOSOFT TENALI 31


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

19)Write a program enter a string then count no of vowels?


20)Enter a string then count number of words?
21)Enter a string then count number of letters with and without spaces?

string functions (): -


In python we can perform all types of string related operations. By
using string function.
The available functions are: -
1. Len (): -By using this function we can display length of the string including
spaces.
Example: -
s=" Lucky “
n=len(s)
print ("the string is:", s)
print ("The string length is:", n)

2. Strip (): -By using this function we can remove un necessary spaces of a string
(left side and right side)
Example: -
s=" Lucky "
n=len (s)
print ("the string is:", s)
print ("The string length is:", n)
n=len (s. strip ())
print ("The string without spaces on both side:", n)

CREATED AT TECHNOSOFT TENALI 32


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

3. lstrip: - By using this function we can remove left side spaces of a string
Example: -
s=" Lucky"
n=len(s)
print ("the string is:", s)
print ("The string length is:", n)
n=len (s. lstrip ())
print ("The string without spaces on left side:", n)

4. rstrip: - By using this function we can remove right side spaces of a string

Example: -
s="Lucky "
n=len(s)
print ("the string is:", s)
print ("The string length is:", n)
n=len (s. rstrip ())
print ("The string without spaces on Right side:", n)

Note: - By using lstrip () and rstrip () function we can remove unnecessary data
also
Example: -

CREATED AT TECHNOSOFT TENALI 33


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

s="1216Lucky"
print ("String is:", s)
print ("String length is:", s. lstrip ("1216"))

s="Lucky 121"
print ("String is:", s)
print ("String length is:", s. rstrip ("121”))

Program for searching: -


s=input("Enter A string:")
ch=input("Enter search letter:")
c=0
for x in s:
if x==ch:
c=c+1
print("Serch letter",ch,"found in ",c," times")

5. id (): - By using this function we can Display address information of given


object
Example: -
s1=input ("Enter A Sting1:")
s2=input ("Enter A Sting2:")
print ("String1 Id is:", id (s1))
print ("String2 Id is:", id (s2))

CREATED AT TECHNOSOFT TENALI 34


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Note: - In python language every value having one identification number


(memory member) if we assign to different variable having similar location
number.
Example: -
s1=input ("Enter A Sting1:")
s2=s1
print ("String1 Id is:", id (s1))
print ("String2 Id is:", id (s2))

is: - With the help of this keyword we can compare two memory location are
similar or not.
Example: -
s1=input ("Enter A Sting1:")
s2=input ("Enter A Sting2:")
If s1 is s2:
print ("String1 and string2 memory location same")
else:
print ("String1 and string2 memory location NOT same")

is not: -It is revers keyword of is


Example: -
s1=input ("Enter A Sting1:")
s2=input ("Enter A Sting2:")
If s1 is not s2:

CREATED AT TECHNOSOFT TENALI 35


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

print ("String1 and string2 memory location NOT same")


else:
print ("String1 and string2 memory location same")

equals (==): -By using this operator, we can compare data between two
memory variables

Example: -
s1=input ("Enter A string:")
s2=input ("Enter A string:")
if s1==s2:
print ("They Are Equal")
else:
print ("They Are Not Equal")

Not equals (! =): -It will perform revers operation of equals to operater.
Example: -
s1=input ("Enter A string:")
s2=input ("Enter A string:")
if s1! =s2:
print ("S1 and S2 are not same")
else:
print ("S1 and S2 are same ")

CREATED AT TECHNOSOFT TENALI 36


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

in: - By using this keyword we can perform data searching operation, In the
format of letter by letter.
Example: -
s1=input ("Enter string1:")
s2=input ("Enter string2:")
if s2 in s1:
print ("s2 is available in s1")
else:
print ("s2 is not available in s1")

Not in: -This is reverse statement of ‘in’ keyword


Example: -
s1=input ("Enter A string:")
s2=input ("Enter A string:")
if s2 not in s1:
print ("s2 is not available in s1")
else:
print ("s2 is available in s1")

6. upper (): - It converts given data into upper case format


Example: -
s1=input ("Enter String in Lower Case:")
print ("Old Str is:", s1)
print ("Upper str is:", s1. upper ())

CREATED AT TECHNOSOFT TENALI 37


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

7. lower (): - It converts given data into lower case format


Example: -
s1=input ("Enter String in Upper Case:")
print ("Old Str is:", s1)
print ("Lower str is:", s1. lower ())

8. capitalize (): - It converts given data into capitalization format means it


converts the given string first letter into upper case format.
Example: -
s1=input ("Enter A String:")
print ("Old Str is:", s1)
print ("New capitalize string:", s1. capitalize ())

9. replace (): - We can replace particular string information into another


string.
Example: -
s1="java is oops language"
print ("Old string is:", s1)
s2=s1.replace("java”, “python")
print ("New string is:", s2)

10. enumerate (): - To display the given string information in the format of an
array with index number.

CREATED AT TECHNOSOFT TENALI 38


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Example: -
s1="python"
print ("old string is:", s1)
print (enumerate (s1))

11. Split (): -With the help of this function we can split the given string based
on given separator, by default the string will be separate by using spaces.
Example: -
s1="my name is Lakshman"
print("old string is:",s1)
print(s1.split())
print()
s1="my-name-is-Lakshman kumar"
print("old string is:",s1)
print(s1.split("-"))
print()
s1="my*name*is*Lakshman*kumar"
print("old string is:",s1)
print(s1.split("*"))
print()

12. Count (): - By using this function we can count particular data, it supports
two options.
I. Count from beginning
II. Count from specific index
Example: -
s1="My name is Lakshman"
print ("Old string is:", s1)

CREATED AT TECHNOSOFT TENALI 39


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

print (s1. Count ("a"))


print (s1. Count ("a",5))
print (s1. Count ("is"))

13. startswith (): - it checks the given string starts with particular data or not
Example: -
s1="my name is Lakshman Kumar"
print ("old string is:", s1)
print (s1. startswith ("my"))
print (s1. startswith ("ravi”) )

14.endswith (): - it checks the given string ends with particular data or not
Example: -
s1="my name is Lakshman Kumar and"
print ("old string is:", s1)
print (s1. endswith ("and"))
print (s1. endswith ("my"))

15.find (): - By using this function we can search particular data and it will
display location index number otherwise it will display -1.
Example: -
s1="my name is Lakshman and my friend name is arjun"
print ("old string is:", s1)

CREATED AT TECHNOSOFT TENALI 40


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

print (s1. Find ('my'))


print (s1. Find ('my',1))
print (s1. Find ('my',25))

16.index (): - It is similar to find function


Example: -
s1="my name is Lakshman and my friend name is arjun"
print ("old string is:", s1)
print (s1. index ('my'))
print (s1. Index ('my',1))

17. swapcase (): - By using this function we can convert upper case data into
lowercase and lower case to upper case
Example: -
s1="Lakshman Kumar"
print ("old string is:", s1)
print ("New string is:", s1. Swapcase ())

18.Isalpha (): - to check the given variable contains Alphabets or not


Example: -

s1="LakshmanKumar"

CREATED AT TECHNOSOFT TENALI 41


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

print("old string is:",s1)


print("New string is:",s1.isalpha())
print()
s1="Lakshman Kumar"
print("old string is:",s1)
print("New string is:",s1.isalpha())

19.Isalnum (): - By using this function to check the given variable contains
Alphabets And Number
Example: -
s1="Lakshman Kumar"
print("old string is:",s1)
print("New string is:",s1.isalnum())
print()
s1="Lakshman1216"
print("old string is:",s1)
print("New string is:",s1.isalnum())

20.Isdigit (): - to check the given variable contains only numbers


Example: -
s1="Lakshman Kumar"
print("old string is:",s1)
print("New string is:",s1.isdigit())
print()

CREATED AT TECHNOSOFT TENALI 42


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

s1=1234
print("old string is:",s1)
print("New string is:",s1.isdigit())

21.Islower (): - to check the given variable contains only lowercase data or
not
Example: -
s1="Lakshman Kumar"
print("old string is:",s1)
print("New string is:",s1.islower())
print()
s1="lucky"
print("old string is:",s1)
print("New string is:",s1.islower())

22.Isupper (): - to check the given variable contains only uppercase or not
Example: -
s1="Lakshman Kumar"
print("old string is:",s1)
print("New string is:",s1.isupper())
print()
s1="LUCKY"
print("old string is:",s1)
print("New string is:",s1.isupper())

CREATED AT TECHNOSOFT TENALI 43


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

23.Isspace (): - to check the given variable is empty or not


Ex: -
s1="Lakshman Kumar"
print("old string is:",s1)
print("New string is:",s1.isspace())
print()
s1=" "
print("old string is:",s1)
print("New string is:",s1.isspace())

While loop: - it is another important looping control. By using this looping, we


can perform sequential looping and conditional looping operation
Syntax: -
Exp 1
While (exp2):
Pro statement
Exp 3
Write a program to print 1 to 10 numbers?
a=1
while(a<=10):
print(a)
a=a+1

CREATED AT TECHNOSOFT TENALI 44


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Try This: -
22) Write a program to print 1 to 10 numbers and their sum?
23) Write a program to print A to Z alphabets in any case?
24) Enter a number then display its factorial value?
25) Enter a number then display arithmetical table?
26) To display first Fibonacci number means 1,1,2,3, 5, ……………55?

While with else: - The else part is executed whenever the while loop is closed
without any abnormal termination.
Ex: -
a=1
while a<=10:
Print (a)
a=a+1
else:
Print (“process done”)

Continue: - By using this key we can skip unnecessary looping value. We can use
this keyword in for loop and while loop.
Ex: -
For I in range (1, 11):
If (I == 4):
Continue
Print (I)

CREATED AT TECHNOSOFT TENALI 45


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Example 2: -
for l in "Lakshman":
if l=='a' or l=='h':
continue
elif l=="s":
break
print("current letter:",l)

Multi loops: - Using python we can generate information in the form of rows
and columns. To implement this concept, we have to specify minimum of two for
loops or while loop in sub for loop we have to use end statement under print
function
Ex: -
For x in range (1, 4):
For y in range (1, 7):
Print (“INDIA”, end=” “)
Print ()

Enter your name then display into 3*6 format?


a=input("Enter a your name:")

CREATED AT TECHNOSOFT TENALI 46


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

i=1
while(i<=3):
j=1
while(j<=6):
print(a,end=" ")
j=j+1
print()
i=i+1

Example 2: -
a=1
for i in range(1,4):
for j in range(1,i+1):
print(a,end=" ")
print()

Try This: -
27) Write necessary programs to print following series?

CREATED AT TECHNOSOFT TENALI 47


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Slicing: - In python it is very important concept of data retrieving. To


implement this concept we have to use indexing concept.
It is mainly classified in two categories
1. Positive index [left to right approach]
2. Negative index [right to left]

Example: -
S= “LAKSHMAN”

-8 -7 -6 -5 -4 -3 -2 -1
L A k S H M A N
0 1 2 3 4 5 6 7

Note: - The following are fundamental rules of slicing.


Slice notation (:)
 <string _ name> [starting index: end index -1/+1] start to end
 <string _ name> [: end index]  No start so it will start from 0 index
 <string _ name> [start index:]  No end so it will take up to end
Ex: -
positive
Str = “Lakshman”
Print (str [3]) # s
Print (str [1:3]) # ak
Print (str [1:4]) # aks
Print (str [1:4:2]) # as
Print (str [3:]) # shman
Print (str [:4]) # Laks
Print (str [:]) # Lakshman
Print (str [: : -1]) # namhskal
Print (str [30]) # Indexing Error: - string index out of range

Negative

Str = “Lakshman”
Print (str [-3]) # m

CREATED AT TECHNOSOFT TENALI 48


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Print (str [-6: -4]) # ks


Print (str [-3:]) # man
Print (str [: -4]) # laks
Print (str [:]) # Lakshman
Print (str [-20]) # Indexing Error: - string index out of range

DATA TYPES IN PYTHON


Numbers:
 Int /float/complex: type
 Describes the numeric value & decimal value
 These are immutable, modification is not allowed
Boolean:
 Bool: type
 Represent true/false values
 0 = false & 1 = true

CREATED AT TECHNOSOFT TENALI 49


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

 Logical operator or not


 Return value is Boolean
Strings:
 Str: type
 Represent group of characters declare with in single or double or triple
quotations
 it is immutable, modification is not allowed
Lists:
 list: type
 group of heterogeneous and homogeneous objects in sequences
 sequencing means indexing important
 it supports all types of index and slicing objects
 it is mutable data type means all types of modifications are allowed
 To declare list values, we have to use []
 We can enter duplicates.
Tuples
 It is another data type it is similar to list data
 Tuple can store both homogeneous & heterogeneous data
 Insertion order in preserved it means in which order we inserted data
same order output is printed
 With one change that is immutable means modifications are not allowed
 Tuple allows duplicate objects
 The tuple contains forward indexing and backword indexing
 To create this data type, we have to use parenthesis ()
Note: - the list and tuple data types allow the user to store duplicate values
Sets:
 It is another heterogeneous and homogeneous objects
 Set is used to store the group of unique objects
 In this data type we are unable to store duplicate information
 It is mutable data type means all types of modifications are allowed
 It contains one limitation that is indexing is not important means unable to
perform slicing
 Set insertion order in not preserved. indexing not supports
 To create this data type, we have to use brasses {}
Dictionaries
 dict: type
 it stores the data in key value pairs format
 keys must be unique & values
 it is mutable means modifications are allowed
 To create this data type, we have to us curly brasses {key: value}

CREATED AT TECHNOSOFT TENALI 50


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

not to

List change
(immutabl
e)

not to
Tuple create
duplicate

By us this
sets we losed
Indexing

It does all
Dictionaries but i need
keys for
every value

List Data Type:


 group of heterogeneous and homogeneous objects in sequences
 sequencing means indexing important
 it supports all types of index and slicing objects
 it is mutable data type means all types of modifications are allowed
 To declare list values, we have to use []
 We can enter duplicates.

OPERATION’s ON LIST DATA TYPE’s


-----------------------------------------------
a=[1,2.33,3,'lucky',1]
print(a)
print(type(a))

l1=[10,20,30]

CREATED AT TECHNOSOFT TENALI 51


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

l2=[10,20,30]
print("list1 is:",l1)
print("list2 is:",l2)
print(id(l1))
print(id(l2))

l1=[10,20,30]
l2=l1
print("list1 is:",l1)
print("list2 is:",l2)
print(l1 is l2)
print(l1==l2)

n=[10,20,30,40]
print(“List Values Are:”,n)
print(len(n))

n=[1,2,2,2,3,3,3,4]
print(n.count(1))
print(n.count(2))
print(n.count(3))
print(n.count(4))

CREATED AT TECHNOSOFT TENALI 52


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

24. index (): - This function will display location number of first occurrence
of given value. If it is un available it will displays error message.
example: -
n=[1,2,2,7,8,2,3,4,5,3]
print(n.index(1))
print(n.index(2))
print(n.index(2,2))
print(n.index(2,3))
print(n.index(3))
print(n.index(3,7))
print(n.index(4))

25. append (): - With the help of this function we can append particular
data into a specified list object
Example: -
list=[“vinay”]
list.append("A")
print(list)
list.append(12.45)
print(list)
list.append(25)
print(list)
list.append(True)
print(list)

CREATED AT TECHNOSOFT TENALI 53


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Try This: -
28) Write a program to append following series into list object by using for loop
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]?
26. insert (): - By using this option we can insert particular value into
specific index.
Example: -
n=[1,2,3,4,5]
print("Values Before insert")
print(n)
n.insert(1,1216)
print("Values After insert")
print(n)

27.extend (): - With the help of this function we can add or append N
number of values into existing list object
Example: -
n=['chicken','Motton','Fish']
n1=['Pappu','sambar','Rasam']
print("Values Before extend")
print("first Values")
print(n)
print("second Values")
print(n1)
n.extend(n1)
print("Values After extend")
print(n)

CREATED AT TECHNOSOFT TENALI 54


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

28. remove (): - we can Remove particular element of a list permanently


Example: -
n=[10,20,10,30,40]
print("Values Before remove")
print(n)
n.remove(10)
print("Values After Remove")
print(n)

29. pop (): - it removes last element of current list object


Example: -
n=[10,20,10,30,40]
print("Values Before pop")
print(n)
n.pop()
print("Values After pop")
print(n)

CREATED AT TECHNOSOFT TENALI 55


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Remove particular value by using index:


n=[10,20,10,30,40]
print("Values Before pop")
print(n)
n.pop()
print("Values After pop")
print(n)
n.pop(2)
print("Values After pop(2)")
print(n)

30. reverse (): - It will display given list values in the order of reverse
without any modifications
Example: -
n=[10,20,10,30,40]
print("Values Before Reverse")
print(n)
n.reverse()
print("Values After Reverse")
print(n)

31. Sort (): - it will sort the particular list values in the format of ascending
order the list values should be homogeneous only[similar data type
values only].
Example: -
n=[20,5,10,0,15]
print("Before Sort")
print(n)
n.sort()
print("After Sort")
print(n)

CREATED AT TECHNOSOFT TENALI 56


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

print("Ater revers Sort")


n.reverse()
print(n)

Nested List data type: -


0,1,2 0 1 2 3
bl=["monkey",[1,2,3],['a','b',12,16],"Lucky"]
0 1 2 3
print(bl)
print(bl[0])
print(bl[1])
print(bl[2])
print(bl[3])
print(bl[1][0])
print(bl[1][0:2])
print(bl[1][0:])
print(bl[1][:2])
print(bl[2])
print(bl[2][0])
print(bl[2][0:2])
print(bl[2][0:])
print(bl[2][:3])
print(bl[3])

CREATED AT TECHNOSOFT TENALI 57


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Unpacking list values: -


In this concept we can copy all list variable values into
particular variables. the values and variables must be similar.
Example: -
bl=[10,12.45,True,”Techno”]
a,b,c,d=bl
print(a)
print(b)
print(c)
print(d)
print(type(a),type(b),type(c),type(d))
ex2:
lb=[[1,2,3],[4,5,6],[7,8,9]]
a,b,c=lb
print(a)
print(b)
print(c)

CREATED AT TECHNOSOFT TENALI 58


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

copy (): - by using this function we can create Xerox object means after creation
there is no data communication between original and duplicate object
Example: -
a=[1,2,3]
a1=a
print(a) 1 2 3
print(a1) 1 2 3
a[1]=200
print(a) 1 200 3
print(a1) 1 200 3

l1=[1,2,3,4,5]
l2=l1.copy()
print("L1 Data:")
print(l1)
print("L2 Data:")
print(l2)
l1[1]=100
print("Values After modification")
print("L1 Data:")
print(l1)
print("L2 Data:")
print(l2)

CREATED AT TECHNOSOFT TENALI 59


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

del (): -It is similar to remove function by using this function we can remove
values depends on indexing and slicing
Example: -
Ex1:
a=[10,20,30,40,50]
print(a)
del a[0]
print(a)
del a[2:4]
print(a)
ex2:
a=[10,20,30,40,50]
print(a)
del a[:1]
print(a)
ex3:
a=[10,20,30,40,50]
print(a)
del a[1:]
print(a)
ex4:
a=[10,20,30,40,50]
print(a)
del a[:]
print(a)

CREATED AT TECHNOSOFT TENALI 60


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Clear (): - By using this function we can clear all elements of particular list object
means object is available but it is empty.
Example: -
fruits=["Apple","Orange","Mango","bananna"]
print(fruits)
fruits.clear()
print(fruits)

Tuple data type: - (tuple)


 It is another data type, it is similar to list data
 Tuple can store both homogeneous & heterogeneous data
 Insertion order in preserved it means in which order we inserted data
same order output is printed
 With one change that is immutable means modifications are not allowed
 Tuple allows duplicate objects
 The tuple contains forward indexing and backword indexing
 To create this data type, we have to use parenthesis ()
Operation’s on tuple: -
t1=(10,20.5,"Lucky")
print(t1)

CREATED AT TECHNOSOFT TENALI 61


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

t1=(10,)
print(type(t1))

t8=tuple("Lakshman")
print(t8)

Example for indexing: -


t1=(10,20,30,40,50,10,11,22,10)
print(t1[0])
print(t1[2:4])
print(t1[1:4:2])
print(t1[:4])
print(t1[2:])
print(t1[:])
print(t1[2:10])
print(t1[::-1])
print(t1[10])

Unpacking: -
t=(10,20.5,"Lucky")
a,b,c=t
print(a)

CREATED AT TECHNOSOFT TENALI 62


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

print(b)
print(c)
print(type(a),type(b),type(c))

Nested Tuple: -
t=((10,20),(30,40,50))
print(t[0])
print(t[1])
print(t[1][1])
print(t[0][1])
print(t[1][2])
print()
print("UN PACKING NESTED TUPLE")
t=((10,20),(30,40,50))
a,b=t
print(a)
print(type(a))
print(b)
print(type(b))

Comparison operations: -
i. Printing memory address by using id () function
ii. is, is not used for memory comparison
iii. ==, != used for data comparison
iv. in, not in checks data is available or not
Example: -

t1=(10,20,30)

CREATED AT TECHNOSOFT TENALI 63


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

t2=(40,50,60)
t3=t1
t4=(10,20,30)
print("T1 Data is:",t1)
print("T2 Data is:",t2)
print("T3 Data is:",t3)
print("T4 Data is:",t4)
print("id's are:")
print(id(t1))
print(id(t2))
print(id(t3))
print(id(t4))
print("Memory comparison")
print(t1 is t2)
print(t1 is t3)
print(t1 is not t2)
print(t1 is not t3)
print("Data comparison")
print(t1 == t2)
print(t1 == t3)
print(t1 == t4)
print(t1 != t2)
print(t1 != t3)
print(t1 != t4)
print("checking data ")
print(10 in t1)
print(100 in t1)
print(10 not in t2)
print(100 not in t3)

CREATED AT TECHNOSOFT TENALI 64


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Tuple with list: -


t=("Hello",5,[],"true")
print(t)
t[2].append(100)
print(t)

t=(10,10,10,20,30,40)
print(t.count(10))
print(t.index(10))
print(t.index(10,1))
print(t.index(10,2))
print(len(t))

CREATED AT TECHNOSOFT TENALI 65


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

sorted (): - This function works only tuple by using this function we can sort the
values at the time of printing only means original data cannot be affected
Example: -
t=(10,4,5,100)
print("Before sort:",t)
print(sorted(t))
print("After sorting:",t)

Tuple to list conversion:


t=(30,1,5,98)
print("Before conv:",t)
l=list(t)
print("After conv:",l)
l.sort()
print("After sort:",l)
t1=tuple(l)
print("After conv:",t1)

Set data type: -


 It is another heterogeneous and homogeneous objects
 Set is used to store the group of unique objects
 In this data type we are unable to store duplicate information

CREATED AT TECHNOSOFT TENALI 66


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

 It is mutable data type means all types of modifications are allowed


 It contains one limitation that is indexing is not important means unable
to perform slicing
 Set insertion order is not preserved, means indexing not supports
 To create this data type, we have to use brasses {}

Operation’s on sets: -
set={1,2,5,4,3,8,7,6,"Arjun","lucky",1,2,3}
print(set)
print(type(set))

Example for mixed data: -


set={1.0,(1,2,5,4),6,"Lucky”,22,44,[1,2,3]}
print(set)

Duplicates are not allowed: -


set={"sri",1,4,1,2,3,2,3,"ram"}
print(set)

Creation of empty set: -


To create empty set object we have to use set function set (), means we
can not specify curly brasses because by default curly brasses are treated as
dictionary (dect)

Example: -
s={}
print(s)
print(type(s))

CREATED AT TECHNOSOFT TENALI 67


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

x=set()
print(type(x))

32.add (): - basically, set is a mutable object, to perform data adding


operation we have a function called add ()

Example: -
s={1,2,3}
print(s)
s.add(4)
print(s)

33. update (): - With the help of this function we can append other data type
values
Example: -
s={1,2,3}
print(s)
s.update([4,5],{1,6,8},(11,22))
print(s)

34.copy (): - by using this function we can create Xerox object means after
creation there is no data communication between original and duplicate
object
Example: -
s={1,2,3}

CREATED AT TECHNOSOFT TENALI 68


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

print(s)
a=s.copy()
print("copy set")
print(a)
s.add(200)
print(s)
print(a)

35. discard () and remove (): -


by using these two functions we can remove particular value of set,
with one difference if the given value is unavailable the
discard () will never display error it displays NONE and the
remove () will display KEY error
Example for discard (): -
s={1,2,3,4,5}
print(s)
s.discard(4)
print(s)
s.discard(7)
print(s)

Example for remove (): -


s={1,2,3,4,5}
print(s)
s.remove(4)
print(s)
s.remove(7)
print(s)

CREATED AT TECHNOSOFT TENALI 69


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Pop (): - By using this function we can remove random element


Example: -
s={1,2,3,4,5}
print(s)
print(s.pop())
print(s)
print(s.pop())
print(s)

Clear (): - By using this function we can clear all elements of particular set object
means ,the object is available but it is empty.
Example: -
s={1,2,3,4,5}
print(s)
s.clear()
print(s)

Member ship operations: -


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

CREATED AT TECHNOSOFT TENALI 70


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

s3={"vinay","kumar"}
s4=s3
print(id(s1))
print(id(s2))
print(id(s3))
print(id(s4))
print(s1 is s2)
print(s1 is not s2)
print(s1 == s2)
print(s1 != s2)
print(s1 in s2)
print(s1 not in s2)

Unpacking of set: -
s1={10,"Lucky",(10,20)}
a,b,c=s1
print("s1 data is:")
print(s1)
print(id(s1))
print("data from A:")
print(a)
print(id(a))
print("data from B:")
print(b)

CREATED AT TECHNOSOFT TENALI 71


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

print(id(b))
print("data from C:")
print(c)
print(id(c))
print(type(a),type(b),type(c))

Eliminating duplicates from list: -


l1=["chinnu",10,20,20,10,"chinnu",10,20,"kumar"]
print(l1)
s1=set(l1)
print(s1)
l2=list(s1)
print(l2)

Creating set by passing more than one list using + operator: -


l1=["Lucky","Arjun","kumar"]
l2=["Lakshman","Lavyana","sri"]
l3=["BL","sri","Chinnu"]
print(l1)

CREATED AT TECHNOSOFT TENALI 72


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

print(l2)
print(l3)
eng=set(l1+l2+l3)
print(eng)

Mathematical operations on sets


I. Union (): by using this function we can display all elements of
two given sets without duplicates we can use pipe (|) symbol
also.
Example: -
x={10,20,30,40}
y={30,40,50,60}
print(x.union(y))
print(x|y)

II. Intersection (): By using this function it will display common


elements of two given set components. By using ‘&’ also we
can implement intersection concept

Example: -
x={10,20,30,40}
y={30,40,50,60}
print(x.intersection(y))
print(x&y)

CREATED AT TECHNOSOFT TENALI 73


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

III. Difference (): It will display all elements of first object which
is not available in second object. By using “- “ also we can
perform this concept
Example: -
x={10,20,30,40}
y={30,40,50,60}
print(x.difference(y))
print(y.difference(x))
print(x-y)
print(y-x)

IV. ^: - it is called non equal operator. By using this operation, it


will display non equal values or non-existing values of given
two components
Example: -
x={10,20,30,40}
y={30,40,50,60}
print(x^y)

Example: -
a=set("vinay_techno")
print(a)
b=set("techosoft")
print(b)
print(b-a)
print(a|b)
print(a&b)
print(a^b)
print()
b1={"Orange","Apple","Pear","banana"}
b2={"Pear","Orange","banana"}

CREATED AT TECHNOSOFT TENALI 74


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

print(b1-b2)
print(b1|b2)
print(b1&b2)
print(b1^b2)

DICTIONARY DATA TYPE: -


 List, Tuple, set data type are used to represent individual objects as a
single entry
 To store the group of objects as a key-value pairs use dictionary
 Declare the dictionary data within the curly braces, each key separated
with value by using: (colon) & each elements are separated with comma
 A dictionary is a data type similar to arrays, but works with keys & values
instead of index
 The keys must be unique but value can be duplicated
 The values in the dictionary can be of any type while the keys must be
immutable like numbers
 Dictionary keys are case sensitive same key name but with the different
case are treated as different keys in python
Example: -
phonebook={}
phonebook["vinay"]=9912499126
phonebook["VINAY"]=9912809666
print(phonebook)
print()
phonebook1={"vinay":9912499126,"techno":9912809666}
print(phonebook1)

CREATED AT TECHNOSOFT TENALI 75


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

print(phonebook1["vinay"])
print()
stu={1:'sai',2:'Harsha',3:'Lakshman'}
print("student Data")
print(stu)
print(stu[1])
stu[1]="Lucky"
print(stu)
print()
stu={1:'sai',2:'Harsha',3:'Lakshman'}
print("stu Data")
print(stu)

Creating empty dictionary’s: -


To implement this concept, we can use empty curly braces {} or dict
()
Example: -
print("Creating Empty Dectionary")
x={}
print(x)
print()
l=dict()
print(l)
print()
p={'Arjun':12,'Lucky':16}
print(p)
print()
b={'name':'Lucky',1:[1,2,3]}
print(b)

CREATED AT TECHNOSOFT TENALI 76


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

We can read the data from dictionary in two ways


a. By using key: - if the key is not present generate key error
b. By using get method: - it key not present return NONE
Example: -
p={'Arjun':'111-222-333','Lucky':'666-33-111'}
print(p)
print(p['Arjun'])
print(p['Lucky'])
print("Using gets")
print(p.get('Arjun'))
print(p.get('Lucky'))
print(p.get('mani'))
print(p['mani'])

38. Keys (): - To get all keys from dictionary


39. Values (): - To get all the values from dictionary
40.sorted (): - This function works only tuple by using this function we can
store the values at the time of printing only means original data cannot
be affected
Example: -
d1={1:'Vinay',2:'Mani',4:'tarun',3:'kumar',5:’Sadhiya’}

CREATED AT TECHNOSOFT TENALI 77


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

print(d1.keys())
print(d1.values())

Data conversions:
d1={1:'Vinay',2:'Mani',4:'tarun',3:'kumar',5:’Sadhiya’}
print("lists")
print(list(d1.keys()))
print(list(d1.values()))
print("tuple")
print(tuple(d1.keys()))
print(tuple(d1.values()))
print("sets")
print(set(d1.keys()))
print(set(d1.values()))
Data Sorting:
d1={1:'Vinay',2:'Mani',4:'tarun',3:'kumar'}
print("sorted")
print(sorted(d1.keys()))
print(sorted(d1.values()))

Member ship operations: -


Example: -
d1={1:'Vinay',2:'Kumar'}
d2={3:'aaa',4:'bbb'}
d3=d1
d4={1:'Vinay',2:'Kumar'}

CREATED AT TECHNOSOFT TENALI 78


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

print(id(d1))
print(id(d2))
print(id(d3))
print(id(d4))
print()
print(d1 is d2)
print(d1 is d3)
print(d1 is not d2)
print(d1 is not d3)
print()
print(d1 == d2)
print(d1 == d3)
print(d1 != d2)
print(d1 != d3)
print()
print(1 in d2)
print('ratan' not in d2)

41. items (): - By using this function the dict information will display in the
format of list and tuple concept
example: -
d1={1:'Lakshman',2:'Kumar',3:'Lucky'}
print(d1.items())

CREATED AT TECHNOSOFT TENALI 79


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

42. Del[key]: - It removes the item based on input key


By using this keyword, we can remove particular key value depends
on given numbers. If the key is not available it will display Key Error
43. Pop[key]: - By using this key word we can remove particular key value
depends on given number. If the key is not available it will not display
Key Error
44. popitem (): - By using this function we can remove last element of the
given dictionary
45. clear (): - We can remove all elements of particular dict object
example: -
print("DEL,POP,POP ITEM,CLEAR programs")
ph={"a1":938477566,"a2":938377264,"a3":947662781,"a4":909090
909}
print(ph)
del ph["a1"]
print(ph)
print("PoP")
pd={"a1":938477566,"a2":938377264,"a3":947662781,"a4":909090
909}
print(pd)
pd.pop("a3")
print(pd)
print("Pop item")
pd.popitem()
print(pd)
print("clear")
pd.clear()
print(pd)

CREATED AT TECHNOSOFT TENALI 80


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

46.Update: - It is similar to extend key word, means we can append all data
from second dict object into first dict object.
Example 1: -
print("UPDATING")
mydict={"mani":28,"tarun":25,"durga":30}
print(mydict)
mydict["durga"]=35
print(mydict)

Example 2: -
d1={1:"vinay",2:"Kumar"}
d2={3:"Mani",4:"Turan"}
print(d1)
print(d2)
d1.update(d2)
print(d1)

CREATED AT TECHNOSOFT TENALI 81


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Copy (): - it is a common copy () of all data types the advantage of this function is
we can create xerox object means there is no internal proportion between two
objects
Example: -
d1={1:"vinay",2:"Kumar",3:"Mani",4:"Turan"}
print("data fron d1 to d2")
print(d1)
d2=d1
print(d2)
print("After updating")
d1[4]="Lucky"
print(d1)
print(d2)
d3={1:"vinay",2:"Kumar",3:"Mani",4:"Turan"}
print("data fron d3 to d4")
print(d3)
d4=d3.copy()
print(d4)
print("After updating by using copy")
d3[4]="Lucky"
print(d3)
print(d4)

Creating dictionary by using list, tuple and set data: -


To implement this concept, we have to use following functions

CREATED AT TECHNOSOFT TENALI 82


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

47. zip (): - By using this function we can convert given two list components
into zipped format. To implement zip operations, we need two list
components and the list object having similar length values
48. dict (): - This function converts zipped data into dict format

converting two lists to dict: -


l1=[10,20,30,40]
l2=["sri ram","arjun","Lucky","sri"]
x=zip(l1,l2)
d=dict(x)
print(d)

converting two tuple to dict: -


l1=(10,20,30,40)
l2=("sri ram","Lucky","Arjun","Lavyana")
x=zip(l1,l2)
d=dict(x)
print(d)

converting two sets to dict: -


l1={10,20,30,40}
l2={"sri ram","anu","durga","sasi"}
x=zip(l1,l2)
d=dict(x)
print(d)

Creating dict using swapping technology: -


print("creating dict using swapping technology")
d1={12:"Lavyana",16:"Lucky"}
d2={1:"Lakshman",25:"Lakshmi"}

CREATED AT TECHNOSOFT TENALI 83


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

print("d1 data is:",d1)


print("d2 data is:",d2)
l1=list(d1.keys())
print("L1 keys are:",l1)
l2=list(d2.values())
print("L2 keys are:",l2)
x=zip(l1,l2)
d=dict(x)
print(d)

TYPES OF VARIABLES
In every programming language the memory variables are mainly
classified into two major categories
They are like
1) Local variables
2) Global variables
Local variables: - These variables are also called private variables because it is
restricted within the functions only means we are unable to access outside of the
function
Example: -
def show ():
name=’Lucky’
print (“sname is:”, name)
show ()

Example 2: -
def show():
name="vinay"
print("Stuname is:",name)

CREATED AT TECHNOSOFT TENALI 84


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

show()
print("Stuname is:",name)

Global variables: - it is also knowing as public variables because we can access


this variable any were of the application. Basically, this variable declared at top
of the function

Example: - -
name="Lucky"
def show ():
print ("Stu name is:", name)
show ()
print ("Stu name is:", name)

Variable over riding


In this concept we can declare same variable as local and global
variable
Example 1: -
name="Lucky"
def show ():
name="Lakshman"
print ("Stu name is:", name)
show ()
print ("Stu name is:", name)

CREATED AT TECHNOSOFT TENALI 85


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Example 2: -
cname="python"
def show():
name="Lakshman"
print("Stuname is:",name)
print("course name is:",cname)
def show1():
name="Kumar"
print("Stuname is:",name)
print("course name is:",cname)
show()
show1()

global: -
basically, the life time of local variables within the function means we are
unable to access outside of the function
to rectify this problem, we can declare a variable as global under function
level
example: -
def show ():
global name
name="Kumar"
print ("Stu name with in the function:", name)
show ()
print ("Stu name outside the function:", name)

CREATED AT TECHNOSOFT TENALI 86


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

Example 2: -
name="lakshman"
def show():
global name
name="Kumar"
print("Stu name with in the function:",name)
show()
print("Stu name out side the function:",name)

Multi-function accessing using function level global declaration: -


def show():
global name
name="Kumar"
print("Stu name with in Show function:",name)
def show1():
print("Stu name with in Show1 function:",name)
show()
show1()

Function with in function: -


def show():
global name
name="Kumar"
print("Stu name with in the function:",name)
def show1():
name="Lakshman"
print("Stu name with in the function 1:",name)

CREATED AT TECHNOSOFT TENALI 87


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

show1()
print("Stu name with in the function :",name)
show()

non local: - with the help of this keyword we can override function level global
variable. We have to specify this key word within the sub function only
Example: -
def show():
name="Kumar"
print("Stu name with in the function:",name)
def show1():
nonlocal name
name="Lakshman"
print("Stu name with in the function 1:",name)
show1()
print("Stu name with in the function :",name)
show()

Call by value [:]: -


In python we are having the concept of call by value it is similar to function
with para concept. In this concept we are having one technical problem that is
the function modification cannot affect to the main program.
Example: -
def f1(x):
print ("The values in the given list:", x)
print ("Total no of elements is:", len(x))
x [1] =2000
x [2] =3000
x. append (4000)
print(x)
a= [10,20,30]

CREATED AT TECHNOSOFT TENALI 88


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

f1(a [:])
print ("outside function a=", a)

Call by reference: -
To ratify call by value problem we are implementing this concept
To perform this concept, we have to pass only object name(variable name).
Example: -
def f1(x):
print ("The values in the given list:", x)
print ("Total no of elements is:", len(x))
x [1] =2000
x [2] =3000
x.append (4000)
print(x)
a= [10,20,30]
f1(a)
print ("outside function a=", a)

Recursive function: -
It is also similar concept of other languages, in the concept The
function calls same function it self
Example: -
def sum(n):
if n==0:
res=0

CREATED AT TECHNOSOFT TENALI 89


CORE PYTHON NOTES – REFERENCE FOR TEACHERS ESHWAR COMPUTERS

else:
res=n+ sum (n-1)
return res
i=10
print ("sum of 1 to {} numbers is {}.". format (i, sum (i)))

END OF CORE PYTHON

CREATED AT TECHNOSOFT TENALI 90

You might also like