Corepythonnew PDF
Corepythonnew PDF
Introduction:
Python is a general-purpose high-level programming language.
Python was developed by Guido Van Rossam in 1989 while working in National Research
Institute at Netherlands.
But officially Python was made available to public in 1991. The Official Data Of Birth for Python
is: Feb 20th 1991.
Python is recommended as first programming Language for beginners.
Eg-1:To Print Hello world
Java:
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
C:
#include <stdio.h>
#include <conio.h>
void main()
{clrscr();
printf("Hello, world\n");
getch();
}
Python:
print("Hello World")
Eg-2: To print the sum of 2 numbers
Java:
public class Add
{
public static void main(String[] args)
{int a,b;
a=10;
b=20;
System.out.println("The Sum:"+(a+b));
}
}
C:
#include <stdio.h>
#include <conio.h>
void main()
{int a,b;clrscr();
a=10;
b=20;
printf("The Sum:%d",(a+b));
getch();
}
Python:
a=10
b=20
print("The sum=",(a+b))
Guido developed Python Language by taking almost all Programming Features from different
Languages
Notes:
Internally Google and Youtube use Python Coding.
NASA and Network Stock Exchange Applications developed by Python.
Top Software companies like Google, Microsoft, IBM, Yahoo using Python.
Features of Python:
4) Platform Independent:
Once we write a Python program, It can run on any platform without rewriting once again
Internally PVM is responsible to convert into machine understandable form.
5) Portability:
Python programs are portable. Ie we can migrate from one platform to another platform very
easily. Python programs will provide same result on any platform.
6) Dynamically Typed:
In Python we are not required to declared type of variables. Whenever we are assigning the
value, based on value, type will be allocated automatically. Hence Python is considered as
dynamically typed Language.
But Java, C etc are Statistically Typed Languages b’z we have to provide type at the
beginning only.
This dynamic typing nature will provide more flexibility to the programmer.
8) Interpreted:
We are not required to compile Python Programs Explicitly. Internally Python Interpreter will
take care that compilation.
If compilation fails interpreter raised syntax errors. Once compilation success then PVM
(Python Virtual Machine) is responsible to execute.
9) Extensible:
We can use other language programs in Python.
The main advantages of this approach are:
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 Programs.
i.e. we can embed Python programs anywhere.
Limitations of Python:
1) Performance wise not up to the mark because it is interpreted language.
2) Not using for mobile Applications
3) Not using for Enterprises Applications(Banking and Telecom Applications)
4) To develop the Machine Learning Application Python is the best choice
Numpy(mathematics library),pandas(import dataset library), mat plot library(for import graph
chart....) all these modules are developing the ML, Python Library are available.
5) Performance is low because Python is a interpreted Application.Overtake this problem JIT
Compiler is added to PVM
JITCOMPILER+PVM---PYPY Flavour (Python for speed)
Flavours of Python:
1) CPython:It is the standard version of Python. It can be used to work with c-language
Applications.
2) Jython OR JPython: It is for Java Applications. It can run on JVM
3) IronPython: It is for C#.Net platform.
4) PyPy: The main advantage of PyPy is performance will be improved because JIT compiler is
available inside PVM.
5) RubyPython: For Ruby Platforms.
6) AnacondsPython: It is specially designed for handling large volume of data processing.
Python Flavours:
Note: Python 3 won’t provide backward compatibility to Python2 i.e. there is no guarantee that
Python2 programs will run in Python3.
IDENTIFIERS
A Name in Python Program is called Identifier.
It can be class Name OR Function Name OR Module Name OR Variable Name
Eg: a=10
Identifier:
1) Alphabet Symbols (Either Upper case OR Lower case)
2) If Identifier is start with Underscore ( _ ) then it indicates it is private.
3) Identifier should not start with Digits.
4) Identifiers are case sensitive.
5) We cannot use reserved words as Identifiers
Eg: def =10 (invalid)
6) There is no length limit for Python Identifiers. But not recommended to use too lengthy
identifiers.
7) Dollor ($) Symbol is not allowed in Python.
Note:
1) If Identifier starts with _ symbol then it indicates that it is private
2) If Identifier starts with __ (two underscore symbols) indicating that strongly private Identifier.
3) If the identifier starts and ends with two underscore symbols then the identifier is language
defined special name, which is also known as magic methods.
x = normal variable
_x = protected variable
__ x = private variable
__ x __= magic variable
Eg: __ add __
RESERVED WORDS
In Python some words are reserved to represent some meaning or functionality. Such type of words
are called reserved words.
Note:
1) All Reserved words Python contains only alphabet symbols.
2) Except the following 3 reserved words, all contain only lower case alphabet symbols.
True
False
None
Eg:
a=true (invalid)
a=True (valid)
DATA TYPES
Note:
In Python2 we have long data type to represent very large integral values.
But in Python3 there is no long type explicitly and we can represent long values also by
using int type only.
The allowed digits are: 0 to 9, a-f (both lower and upper case are allowed)
Literal value should be prefixed with 0x or 0X
Eg: a = 0XFACE
a = 0XBeef
a = 0XBeer(Invalid)
Note: Being a Programmer we can specify literal values in decimal, binary, octal and hexa decimal
forms. But PVM will always provide values only in decimal form.
a=10
b=0o10
c=0x10
d=0B10
print(a) #10
print(b) #8
print(c) #16
print(d) #2
Base Conversions:
1) bin():
We can use bin() to convert from any base to binary.
>>>bin(15)
'0b1111'
>>> bin(0o11)
'0b1001'
>>> bin(0X10)
'0b10000'
2) oct():
We can use oct() to convert from any base to octal.
>>>oct(10)
'0o12'
>>> oct(0B1111)
'0o17'
>>> oct(0X123)
'0o443'
3) hex():
We can use hex () to convert from any base to hexa decimal.
>>>hex(100)
'0x64'
>>> hex(0B111111)
'0x3f'
>>> hex(0o12345)
'0x14e5'
The main advantage of exponential form is we can represent big values in less memory.
***Note:
We can represent int values in decimal, binary, octal and hexa decimal forms. But we can
represent float values only by using decimal form.
>>> f=0B11.01
SyntaxError: invalid syntax
>>> f=0o123.456
SyntaxError: invalid syntax
>>> f=0X123.456
SyntaxError: invalid syntax
In the real part if we use int value then we can specify that either by decimal, octal, binary or
hexa decimal form.
But Imaginary part should be specified only by using decimal form.
>>> a=0B11+5j
>>> a
(3+5j)
>>> a=3+0B11j
SyntaxError: invalid syntax
>>> a=10+1.5j
>>> b=20+2.5j
>>> c=a+b
>>> print(c)
(30+4j)
>>> type(c)
<class 'complex'>
Note: Complex data type has some inbuilt attributes to retrieve the real part and imaginary part
>>> c=10.5+3.6j
>>>c.real
10.5
>>>c.imag
3.6
We can use complex type generally in scientific Applications and electrical engineering Applications.
True + True 2
True – False 1
S1=”Nice
Computers”
For this requirement we should for triple single quotes (''') or triple double quotes ( " " " )
s1='''nice
computer
education'''
We can also use triple quotes to use single quotes or double quotes in our string.
Slicing of Strings:
1) >>> s="navya"
2) >>>s[0]
3) 'n'
4) >>>s[1]
5) 'a'
6) >>>s[-1]
7) 'a'
8) >>>s[40]
9) IndexError: string index out of range
1) >>>s[1:40]
2) 'avya'
3) >>>s[1:]
4) 'avya'
5) >>>s[:4]
6) 'navy'
7) >>>s[:]
8) 'navya'
9) >>> s*3
10) 'navyanavyanavya'
11) >>>len(s)
12) 5
Note:
1) In python the following data types are considered as Fundamental Data types
int
float
complex
bool
str
2) In Python, we can represent char values also by using str type and explicitly char type is not
available.
>>> c='a'
>>> type(c)
<class 'str'>
3 ) Long Data type is available in Python2 but not in Python3. In Python3 long values also we can
represent by using int type only.
In Python we can present char values also by using str Type and explicitly char Type is not
available.
TYPE CASTING
We can convert one type value to another type. This conversion is called Typecasting or Type
coersion.
The following are various inbuilt functions for type casting.
1) int()
2) float()
3) complex()
4) bool()
5) srt()
1. int():
We can use this function to convert values from other types to int
>>>int(123.987)
123
>>> int(10+5j)
TypeError: can't convert complex to int
>>>int(True)
1
>>>int(False)
0
>>>int("10")
10
>>>int("10.5")
ValueError: invalid literal for int() with base 10: '10.5'
>>> int("ten")
ValueError: invalid literal for int() with base 10: 'ten'
>>> int("0B1111")
ValueError: invalid literal for int() with base 10: '0B1111'
>>>
Note:
2. float():
We can use float() function to convert values from other type values to float type.
>>>float(10)
10.0
>>> float(10+5j)
TypeError: can't convert complex to float
>>>float(True)
1.0
>>>float(False)
0.0
>>>float("10")
10.0
>>>float("10.5")
10.5
>>> float("ten")
ValueError: could not convert string to float: 'ten'
>>> float("0B1111")
ValueError: could not convert string to float: '0B1111'
>>>
Note:
1) We can convert any type value to float type except complex type
2) Whenever we are trying to convert str type to float type compulsory str should be either integral
or floating point literal and should be specified only in base-10.
3. complex():
We can use complex() function to convert values from other type values to complex type.
Form-1: complex(x)
We can use this function to convert x into complex number with real part x and imaginary part 0.
Eg:
>>>complex(10)
(10+0j)
>>>complex(10.5)
(10.5+0j)
>>>complex(True)
(1+0j)
>>>complex(False)
0j
>>>complex("10")
(10+0j)
>>>complex("10.5")
(10.5+0j)
>>> complex("ten")
ValueError: complex() arg is a malformed string
>>>
Form-2: complex(x,y)
We can use this method to convert x and y into complex number such that x will be real part y will
be imaginary part.
Eg:
>>>complex(10,-2)
(10-2j)
>>>complex(True,False)
(1+0j)
>>>
4. bool():
We can use this function to convert from other type values to bool type.
>>>bool(0)
False
>>>bool(1)
True
>>>bool(10)
True
>>>bool(10.5)
True
>>>bool(0.178)
True
>>>bool(0.0)
False
>>> bool(10-2j)
True
>>> bool(0+1.5j)
True
>>> bool(0+0j)
False
>>> bool("True")
True
>>> bool("False")
True
>>>bool("")
False
>>>
5. str():
We can use this function to convert from other type values to str type.
>>>str(10)
'10'
>>>str(10.5)
'10.5'
>>> str(10+5j)
'(10+5j)'
>>>str(True)
'True'
>>>
All Fundamental data types are Immutable. i.e once we creates an object, we cannot perform
any changes in that object. If we are trying to change then with those changes a new object will
be created. This non-changeable behaviour is called immutability.
In Python if a new object is required, the PVM won’t create object immediately. First it will check
is any object available with the required content or not. If available then existing object will be
reused. If it is not available then only a new object will be created. The advantages of this
approach is memory utilization and performance will be improved.
But the problem in this approach is, several references pointing to the same object, by using
one reference if we are allowed to change the content in the existing object then the remaining
references will be effected. To prevent this immutability concept is required. According to this
once creates an object we are not allowed to change content. If we are trying to change with
those changes a new object will be created.
>>> a=10
>>> b=10
>>> a is b
True
>>> id(a)
2132213328464
>>> id(b)
2132213328464
>>>
1) >>> x=[10,20,30,40]
2) >>> b=bytes(x)
3) >>> type(b)
4) <class 'bytes'>
5) >>> print(b[0])
6) 10
7) >>> print(b[-1])
8) 40
9) >>> for i in b:
10) print(i)
output:
10
20
30
40
Conclusion 1:
The only allowed values for byte data type are 0 to 256. By mistake if we are trying to provide any
other values then we will get value error.
Conclusion 2:
Once we create bytes data type value, we cannot change its value, otherwise we will get TypeError.
>>> x=[10,20,30,40]
>>> b=bytes(x)
>>>b[0]=100
TypeError: 'bytes' object does not support item assignment
>>>
Eg:1
>>> x=[10,20,30,40]
>>> b=bytearray(x)
>>> for i in b:
print(i)
10
20
30
40
>>>b[0]
10
>>>b[0]=100
>>> for i in b:
print(i)
100
20
30
40
>>>
Eg:2
>>> x=[10,256]
>>> b=bytearray(x)
ValueError: byte must be in range(0, 256)
8. List Data Type():
If we want to represent a group of values as a single entity where insertion order required to
preserve and duplicates are allowed then we should go for list data type.
Eg:
>>> list=[10,10.5,'naresh',True,10]
>>> print(list)
[10, 10.5, 'naresh', True, 10]
>>>
>>> list=[10,20,30,40]
>>>list[0]
10
>>>list[-1]
40
>>>list[1:3]
[20, 30]
>>>list[0]=100
>>> for i in list:
print(i)
100
20
30
40
>>>
List is growable in nature, i.e based on our requirement we can increase or decrease the size.
>>> list=[10,20,30]
>>>list.append('naresh')
>>> list
[10, 20, 30, 'naresh']
>>>list.remove(20)
>>> list
[10, 30, 'naresh']
>>> list2=list*2
>>> list2
[10, 30, 'naresh', 10, 30, 'naresh']
>>>
Eg:
>>> t=(10,20,30,40)
>>> type(t)
<class 'tuple'>
>>>t[0]
10
>>>t[0]=100
TypeError: 'tuple' object does not support item assignment
>>>t.remove(10)
AttributeError: 'tuple' object has no attribute 'remove'
>>>t.append('naresh')
AttributeError: 'tuple' object has no attribute 'append'
Form-1:range(10)
Generate numbers from 0 to 9
Eg:
r= range(10)
for i in r:print(i)-->0 to 9
Form-2:range(10,20)
generates numbers from 10 to 19
Eg:
r=range(10,20)
for i in r:print(i)-->10 to 19
Form-3:range(10,20,2)
2 means increment value
Eg:
r=range(10,20,2)
for i in r:print(i)-->10,12,14,16,18.
We can access elements present in the range Data Type by using index.
Eg:
r=range(10,20)
r[0] 10
r[15] Index error: range object index out of range
Eg:
r[0] =100
Type error: ‘range’ object does not support item assignment
We can create a list of values with range data type
Eg:
l=list(range(10))
print(l)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Set is growable in nature, based on our requirement we can increase or decrease the size.
>>>s.add(60)
>>> s
{0, 100, 'naresh', 200, 10, 60}
>>>s.remove(100)
>>> s
{0, 'naresh', 200, 10, 60}
>>>
>>> s={10,20,30,40}
>>> fs=frozenset(s)
>>> type(s)
<class 'set'>
>>>type(fs)
<class 'frozenset'>
>>> fs
frozenset({40, 10, 20, 30})
>>> for i in fs:
print(i)
40
10
20
30
>>>fs.add(70)
AttributeError: 'frozenset' object has no attribute 'add'
>>>fs.remove(10)
AttributeError: 'frozenset' object has no attribute 'remove'
>>>
13. dict Data Type():
If we want to represent a group of values as key-value pairs then we should go for dict data
type.
Eg:d={101:'naresh',102:'ravi',103:'shiva'}
Duplicate keys are not allowed but values can be duplicated. If we are trying to insert an entry
with duplicate key then old value will be replaced with new value.
Eg:
>>> d={101:'naresh',102:'ravi',103:'shiva'}
>>>d[101]='sunny'
>>> d
{101: 'sunny', 102: 'ravi', 103: 'shiva'}
>>> We can create empty dictionary as follows
>>> d={}
>>> We can add key-value pairs as follows
>>> d['a']='apple'
>>> d['b']='banana'
>>> print(d)
{'a': 'apple', 'b': 'banana'}
>>>
Note:dict is mutable and order won’t be preserved.
Note:
1) In general we can use bytes and bytearray data types to represent binary information like
images, video files etc
2) In python2 long data type is available. But is Python3 it is not available and we can represent
long values are also by using int type only.
3) In python there is no char data type. Hence we can represent char values also by using str
type.
Escape Characters:
In string literals we can use escape characters to associate a special meaning.
>>> s="nice\nsoftware"
>>> print(s)
nice
software
>>> s="nice\tsoftware"
>>> print(s)
nice software
>>> s="This is " symbol"
SyntaxError: invalid syntax
>>> s="This is \" symbol "
>>> print(s)
This is " symbol
1) \n New Line
2) \t Horizontal Tab
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
…
Constants:
Constant concept is not applicable in Python.
But it is convention to use only uppercase characters if we don’t want to change value.
MAX_VALUE =10
It is just convention but we can change the value.
OPERATORS
+ ->plus (addition)
- ->minus (subtraction)
* ->star (multiplication)
/ ->forward slash (division)
% ->percentage (modulo operator)
// ->floor division (floor division)
** -> power (Exponent operator or power operator)
a=10
b=2
print("a+b=",a+b)
print("a-b=",a-b)
print("a*b=",a*b)
print("a/b=",a/b)
print("a//b=",a//b)
print("a%b=",a%b)
print("a**b=",a**b)
floor(before int)
12.3--12
13.6--13
15.7--15
ceil(next int)
ceil(12.3)--13
13.6--------14
15.7--------16
+ *
+ (addition + concatenation)
* (multiplication +repitation )
"naga" + "naresh"=naganaresh
"THOPULA"+"NARESH"=THOPULANARESH
"naga"+3--error
*
"naga"* 3==naganaganaga
"naga"*"naga"-error
RELATIONAL OPERATIORS:-
> =GREATER THAN
< =LESSTHAN
>= =GREATERTHAN OR EQUAL TO
<= =LESSTHAN OR EQUAL TO
a=10
b=20
print("a>b =",a>b) -false
print("a>=b=",a>=b) -false
print("a<b=",a<b) -True
print("a<=b=",a<=b) -True
print(True>True) -False
print(True>=True) -TRUE
print(10>True) -True
print(False>True) -False
eg:
a=10
b=20
if(a>b):
print("a is greater than b")
else:
print("a is not greaetr than b")
Note:
Chaining of relational operators is possible or not. IN the chaining, if all
comparisions returns True then only result is true.
if atleast one comparision returns false then the result is False.
10<20 -True
10<20<30 -True
10<20<30<40 -True
10<20<30<40>50 -False
-----------------------
Equality Operators: == , !=
we can apply these operators for any type even for incompatible type also
10==20 -False
10!=20 -True
10==True -False
Flase==False -True
'naresh'=='naresh' -True
10=='naresh' -False
Note: CHaining concepts is applicable or not for equality operators.
if atleast one comparision returns False then the result is False.
otherwise the resut is True
10==20==30==40 -False
10==10==10==10 -True
10 and 20 -20
0 and 20 -0
10 and 0 -0
if first argument is zero then result is zero otherwise result is y
X or Y:
if x evaluates to true result is x otherwise result is y
10 or 20 -10
0 or 20 -20
not x:
if x evaluates to False result is true otherwise result is false
not 10 -False
not 0 -True
eg:
'naresh' and 'nicecompuetrs' =’nicecomputers’
"" and "naresh" =
"naresh" and "" =
"naresh" or "" =
"" or "naresh" =
not "" =
not "naresh" =
| => bitwise or
if atleast one bit is 1 then only result is 1 other wise result is 0.
shift operators:
-------------------
<< => bitwise left shift
>> => bitwise right shift
practice exercise:
boolean
eg:
x=10
x+=20 #x=x+20
print(x)
Syntax:
x= firstvalue if condition else secondvalue
eg:1
a,b=10,20
eg:2
a,b=20,10
big= 40 if a>b else 30
print(big)
eg: read two numbers from the keyboard and print minimum value
#read two numbers from the keyboard and print minimum value
a=int(input("Enter First no:"))
b=int(input("Enter second no:"))
min=a if a<b else b
print("Minimum value=",min)
1.identity operators:
is
is not
is operator:
r1 is r2 it returns True if both r1 and r2 are pointing to the same object
r1 is not r2 it retuens True if both r1 and r2 are not pointing to same object
eg:
a=10
b=10
print(a is b)
True
a="naresh"
b="naresh"
print(id(a))
print(id(b))
print(a is b)
#true
print( a is not b)
#false
2.membership operators
in
not in
we can use membershift operators to check wheather the given object present
in the given collection.(it may be string,list,set,Tuple or dict)
eg:
eg:
list1=["sunny","bunny","chinny","pinny"]
print("sunny" in list1) =>True
print("tunny" on list1) => False
print("tunny" not in list1) => True
Operator Precedence:
If multiple operators present then which operator
will be evaluted first is decided by operator precedence
print(3+10*2)->23
print((3+10)*2)->26
BRADMAS
a=30
b=20
c=10
d=5
print((a+b)*c/d)=> 100.0
print((a+b)*(c/d))->100.0
print(a+(b*c)/d) ->70
=>3/2*4+3+(10/5)**3-2
=>3/2*4+3+2**3-2
=>3/2*4+3+8-2
=>1.5*4+3+8-2
=>6.0+3+8-2
=>17-2
=>15.0
import math as m
print(m.sqrt(16))
print(m.pi)
ceil(x)
floor(x)
pow(x,y)
factorial(x)
trunc(x)
gcd(x,y)
sin(x)
cos(x)
tan(x)...etc
1) raw_input():
This function always read the data from the keyboard in the form of string format.
we have to convert the string type to our required type by using the corresponding
type casting methods.
print(type(x)) -> it will always print str type only for any input type
2) input():
input() function can be used to read data directly in our required format.
we are not required to perform type casting.
x=input("Enter value:")
type(x)
10->int
"naresh"-> str
10.5-> float
True-> bool
Note:
But in python 3 we have only input() method and raw_input() method
is not available.
python 3 input() method behaviour exactly same as raw_inpu() method of python 2.
i.e every input value is treated as str type only.
raw_input() function of python 2 is renamed as input() method in python 3.
q) write a program to read 2 numbers from the keyboard and print sum
o/p:
Enter first no:100
Enter second no:200
sum=300
Q) write a program to read Employee Data from the Keyboard and print that
data
eg-2
a,b,c,d=[int(x) for x in input("Enter any 4 no:").split()]
print("sum=",a+b+c+d)
-------------------------------------------------------------------------
eval():
eval function take a String and evalute the result
eg:
x=eval("10+20+30")
print(x)
Eg:
l=eval(input("Enter list:")
print(type(l))
print(l)
within the python program this commandline arguments are available in argv.
which is present in sys module
test.py 10 20 30
Note: argv[0] represent Name of program. but not first commandline argument
argv[1] represent first commandline argument
-------------------
from sys import argv
sum=0
args=argv[1:]
for x in args:
n=int(x)
sum=sum+n
print("total sum=",sum)
Note1:
Usually space is seperator between commandline arguments.
if our commandline arguments its self contains space then we should
enclose within double quotes
Note2:
within the python program command line arguments are available
in the string form. based on our requirement, we can convert into
corresponding type by using type casting method.
E:\DIVYA>py test.py 10 20
1020
Note3:
if we are trying to access command line arguments with out of range index
then we will get Error
Output Statements:
eg:
print("Nice Computers")
print()
print("Hello world")
form-2:
print(String):
print("Hello world")
print("Hello \n world")
print("Hello \t world")
form3:
print() with variable number of arguments
a,b,c=10,20,30
print("the values are:",a,b,c)
a,b,c=10,20,30
print(a,b,c,sep=',')
a,b,c=10,20,30
print(a,b,c,sep=',')
print(a,b,c,sep=':')
print(a,b,c,sep='@')
form4:
print() with end attribute
print("Hello")
print("Nice")
print("soft")
eg:
print("Hello",end=' ')
print("Nice",end=' ')
print("soft")
Note: the default value for end attribute is \n , which is nothing but
new line character
form:5
print(object) statement
we can pass any objects(like list,tuple,set etc) as argument to the print()
statement
l=[10,20,30,40,50]
t=(10,20,30,40,50)
print(l)
print(t)
form:6
print(String,Variable list)
we can use print() statement with String and any number of arguments
s="Naresh"
a=32
s1="java"
s2="Python"
print("Hello",s,"Your Age is ",a)
print("You are teaching",s1,"and",s2)
output:
Hello Naresh Your age is 32
Your are teaching java and python
Form:7
print(Formating string)
1) %i ->int
2) %d ->int
3) %f ->float
4) %s ->String type
Syntax: print("Formating string" %(variable list))
a=10
b=20
c=30
print("a value is %i" %a)
print("b value is %d and c value is %d" %(b,c))
eg:2
s="naresh"
list=[10,20,30,40]
print("Hello %s....the list of items are %s" %(s,list))
Hello naresh....the list of items are [10, 20, 30, 40]
form:8
print() with replacement operator {}
name="naresh"
salary=10000
gf="Python"
print("hello {x} your salary is {y} and your friend {z} is waiting" .format(x=name,y=salary,z=gf)
Flow Controls:
--------------
flow controls describes the order in which statements will be executed at runtime
1) if
syntax:
if condition :statement
or
if condition:
statement1
statement2
statement3
2)if-else:
if condition:
statement
else:
statement
3)if-elif-else:
if condition1:
statement
elif condition2:
statement
elif condtion3:
statement3
----
-----
else:
default statement
if condition:
statement1
statement2
statement3
name=input("ENter Name:")
if name=="naresh":
print("Hello naresh good morning")
print("How r u!!!")
2)if-else:
if condition:
statement
else:
statement
eg:1
name=input("Enter name:")
if name=="naresh":
print("Hello naresh Good morning")
else:
print("Orey good morning")
print("How r u")
3)if-elif-else:
if condition1:
statement
elif condition2:
statement
elif condtion3:
statement3
----
-----
else:
default statement
EG:
brand=input("Enter your favourite Brand:")
if brand=="RC":
print("It is Children brand")
elif brand=="KF":
print("It is not much kick")
elif brand=="FO":
print("Buy one get one offer")
else:
print("Other Brands are not required")
EG:4
if n1==n2:
print("both are equal")
elif n1>n2:
print("Biggest no is:",n1)
else:
print("Biggest no is:",n2)
eg:
#Write a program to find Smallest of 2 no from the command prompt
if n1==n2:
print("both are equal")
elif n1<n2:
print("smallest no is:",n1)
else:
print("smallest no is:",n2)
eg:
#Write a program to find biggest of 3 no from the command prompt
n=int(input("Enter number"))
if n>=1 and n<=100:
print("The number",n,"is in between 1 to 100")
else:
print("the number",n,"is not in between 1 to 100")
1) for loop:
if we want to execute some action for every element present in the some sequence
(it may be string or collection) then we should for
for loop
syntax:
for x in sequence:
body
eg:1
for x in range(10):
print(x)
o/p:0 1 2 3 4 5 6 7 8 9
eg:2
s="naga naresh"
for x in s:
print(x)
o/p:
n
a
g
a
n
a
r
e
s
h
Eg:3
To Print characters present in string index wize
s=input("Enter a string:")
i=0
for x in s:
print("the characters present at ",i,"index is:",x)
i=i+1
eg:3
to print hello 10 times
for x in range(10):
print("Hello")
eg:4
to display numbers from 0 to 10
for x in range(11):
print(x)
eg:5
# to display odd numbers from 0 to 20
for x in range(21):
if x%2==1:
print(x)
eg:6
# to display even numbers from 0 to 20
for x in range(21):
if x%2==0:
print(x)
eg:7
# to display numbers from 10 to 1 in descending order
for x in range(10,0,-1):
print(x)
eg:8
#to print sum of numbers present inside list
list=eval(input("ENter a list"))
sum=0
for x in list:
sum=sum+x
print("The sum=",sum)
while loop:
-----------
If we want to execute a group of statements iteratively until some condition false,
then we should go forwhile loop
Syntax:
while condition:
body
eg:
to print numbers from 1 to 10 by using while loop
x=1
while x<=10:
print(x)
x+=1
eg:
#to display the sum of first n numbers
n=int(input("Enter n Value:"))
sum=0
i=1
while i<=n:
x=int(input("ENTER A NO:"))
sum=sum+x
i=i+1
print("the sum=",sum)
eg:Write a program to prompt user to enter some name until entering Naresh
name=""
while name!="Naresh":
name=input("ENter Name:")
print("Thanks for confirmation")
Infinite loops:
---------------
i=0
while True:
i=i+1
print("Hello",i)
Nested Loops:
Some times we can take a loop inside another loop , which are known as nested loops
for i in range(4):
for j in range(4):
print(i,"....",j)
o/p:
0 .... 0
0 .... 1
0 .... 2
0 .... 3
1 .... 0
1 .... 1
1 .... 2
1 .... 3
2 .... 0
2 .... 1
2 .... 2
2 .... 3
3 .... 0
3 .... 1
3 .... 2
3 .... 3
*
* *
* * *
* * * *
* * * * *
eg:1
cart=[10,20,30,40,50]
for item in cart:
if item>=500:
print("We cannot process this order")
break
print(item)
else:
print("congrats...all items processed successfully")
eg:2
cart=[10,20,700,40,50]
for item in cart:
if item>=500:
print("We cannot process this order")
break
print(item)
else:
print("congrats...all items processed successfully")
3)pass statement:
-----------------
pass is a keyword in python.
if x<=10:
pass
pass:
it is a empty statement
it is null statement
it won't do any thing
Eg:
if True:
syntaxError: unexpexted EOF while parsing
def m1():
syntaxError: unexpexted EOF while parsing
def m1():pass
eg:
class rama:
def sum(self):
pass
r=rama()
r.sum()
eg:1
class rama:
def f1():
pass
class sita(rama):
def f1()
print("hello")
eg:
for i in range(100):
if i%9==0:
print(i)
else:pass
eg:
for i in range(100):
if i%9==0:
print(i)
else:pass
del statement:
--------------
del is a keyword in python
x=10
print(x)
del x
Note:
We delete variables which are pointing to immutable object.But we cannot
delete the elements present inside immutable object.
s="naresh"
print(s)
del s
del s[0]
But in the case of None Assignment the variable won't be removed but the
corresponding object is eligible for garbage collection (rebind operation)
.Hence after assigning with None value ,we can access that variable.
s="Naresh"
s=None
print(s)-None
------------------------------------------------------------------
String Data structures:
The most commonly used object in any project and in any programing language
is string only.
Hence we should aware complete information about string data type.
What is String?
any sequence of characters within either single quotes or double quotes is
considered as a String
syntax:
s="Naresh"
s='Naresh'
eg:
ch='a'
type(ch)
class 'string'
eg:
s='''nice
computers
education'''
we can also use triple quotes to use single quotes or double quotes as symbol
inside string literal
1) By using index
2) by using slice operator
s='naresh'
s='naresh'
s[0]
'n'
s[4]
's'
s[-1]
'h'
s[10]
error: String index out of range error
Note: if we are trying to access characters of a string with out range index
then we sill get error saying: index error
q) write a program to accept some string from the keyboard and display
its characters by index wise (both positive and negative index)
Note:
=>If we are not specifing begin index then it will consider from begining
of the string.
=>if we are not specifying end index then it will consider up to end of the string
=>the default value for step is 1
Behaviour Of Slice:
1)s[begin:end:step]
2) step value either positive (+ve) or negative(-ve)
3) if positive then it should be forward direction(left to right)
and we have to consider begin to end-1
4) if -ve then it should be backward direction(right to left )
and we have to consider begin to end+1
Note:
In the forward direction if end is 0 then result is always empty
In the backward direction if end is -1 then result is always empty
In forward direction:
default values for begin:0
default value for end: length of string
default value forstep:+1
In backward direction:
default values for begin:-1
default value for end: (length of string +1)
Note: either forward and backward direction,we can take both +ve and -ve values
for begin and end index
Note:
=>to use + operator for strings, compulsory both arguments should be strings
=>to use * operator for strings, compulsory one argument should be string and
another arguent should be int
print("\nbackward direction:")
i=-1
while i>=-n:
print(s[i],end='')
i-=1 #i=i-1
Alternate ways:
eg:1
s="Learning Python is very easy !!!"
print("forward direction:")
for i in s:
print(i,end='')
eg:2
s="Learning Python is very easy !!!"
print("forward direction:")
for i in s[::]:
print(i,end='')
eg:3
s="Learning Python is very easy !!!"
print("backward direction:")
for i in s[::-1]:
print(i,end='')
checking Memberships:
---------------------
checking membership operators: in ,not in
we can check wheatherthe character or string is the member of another string or not
by using in and not in operators
s="naresh'
print('r' in s) -true
print('z' in s) -false
print('z' not in s)-true
eg:
eg:
eg:
city=input("Enter your city name:")
scity=city.strip()
if scity=='Hyderabad':
print("Hello Hyderabadi...Adab")
elif scity=='Chennai':
print("Hello Madrasi....Vanakkam")
elif scity=="Bangalore":
print("Hello Kannadiya...subhodhaya")
else:
print("your entered city is invalid")
Finding Substrings:
-------------------
we can use following 4 methods
find():
-------
s.find(subsgring)
note: by default find() method can search total string.we can also specify
the boundaries to search
s.find(substring,begin,end)
it will always search from begin index to end-1 index
s="nareshravipavanshiva"
print(s.find('a')) #1
print(s.find('a',7,15)) #7
print(s.find('z',7,15)) #-1
2.index()
-------
index() method is exactly same as find() method except that if
the specified substring is not available then we will get value error
output:
Enter Main String:abbababababcdefg
Enter sub string:a
Found at position 0
Found at position 3
Found at position 5
Found at position 7
Found at position 9
s="abcabcabcabcadda"
print(s.count('a'))#6
print(s.count('ab'))#4
print(s.count('a',3,7))#2
eg:1
s="Learning python is very difficult"
s1=s.replace("difficult","easy")
print(s1)
o/p:bbbbbbbbbbbbbb
String objects are immutable then how we change the content by using replace() Method:
--------------------------------------------------------------------------------------
==> Once we create string object,we can not change the content.
This non changeable behaviour is nothing but Immutability.
If we are trying to change the content by using
any method,then with those changes a new objects will be created and changes
won't be happened in existing object.
Hence with replace() method also a new object got created but existing object
won't be changed.
Eg:3
s="abad"
s1=s.replace("a","b")
print(s,"is available at:",id(s))
print(s1,"is available at:",id(s1))
output:
abad is available at:4568672
bbbb is available at:4568704
Splitting of Strings:
---------------------
We can split the given string according to specified seperator by using split() method.
l=s.split(seperator)
The default seperator is space.The return type of split() method is List.
Eg:1
s="Nice Computer Education"
l=s.split()
for x in l:
print(x)
output:
Nice
Computer
Education
Eg:2
s="22-02-2019"
l=s.split('-')
for x in l:
print(x)
output:
22
02
2019
Joining of Strings:
-------------------
We can join a Group of Strings(List OR Tuple) wrt the given Seperator
s=seperator.join(group of strings)
Eg:1
t=('sunny','bunny','chinny')
s='-'.join(t)
print(s)
output:sunny-bunny-chinny
Eg:2
l=['Hyderabad', 'singapore','london','dubai']
s=':'.join(l)
print(s)
output: Hyderabad:singapore:london:dubai
Eg:1
s="learning Python is very Easy"
print(s.upper())
print(s.lower())
print(s.swapcase())
print(s.title())
print(s.caitalize())
output:
LEARNING PYTHON IS VERY EASY
learning python is very easy
LEARNING pYTHON IS VERY eASY
Learning Python Is Very Easy
Learning python is very easy
output:
-------
True
False
True
Eg:
print('Naresh786'.isalnum())->True
print('naresh786'.isalpha())->False
print('naresh'.isalpha())->True
print('naresh'.isdigit())->False
print('786786'.isdigit())->True
print('abc'.islower())->True
print('Abc'.islower())->False
print('abc123'.islower())->True
print('ABC'.isupper())->True
print('Learning Python is very easy'.istitle())->False
print('Learnign Python Is Very Easy'.istitle())->True
print(' '.isspace())->True
Demo Program:
-------------
s=input("Enter any character:")
if s.isalnum():
print("Alpha Numaric Charatcter")
if s.isalpha():
print("Alphabet character")
if s.islower():
print("Lowercase Alphabet Charatcter")
else:
print("UPPER CASE ALPHABET CHARACTER")
else:
print("It is a digit")
elif s.isspace():
print("It is a space character")
else:
print("Non space special character")
c:\1>py test.py
Enter any character:7
Alpha Numaric Charatcter
It is a digit
c:\1>py test.py
Enter any character:a
Alpha Numaric Charatcter
Alphabet character
Lowercase Alphabet Charatcter
c:\1>py test.py
Enter any character:$
Non space special character
c:\1>py test.py
Enter any character:A
Alpha Numaric Charatcter
Alphabet character
UPPER CASE ALPHABET CHARACTER
-------------------------------------------
Formating the strings:
We can format the strings with variable values by using replacement operator{}
and format() method.
name='naresh'
salary=10000
age=28
print("{}'s salary is {} and his age {}".format(name,salary,age))
print("{0}'s salary is{1} and his age{2}".format(name,salary,age))
print("{x}'s salary is{y} and his age{z}".format(z=age,y=salary,x=name))
output:
naresh's salary is 10000 and his age 28
naresh's salary is10000 and his age28
naresh's salary is10000 and his age28
1st way:
--------
s=input("Enter some string")
print(s[::-1])
2nd way:
--------
s=input("Enter some string")
print(''.join(reversed(s)))
3rd way:
--------
s=input("Enter some string:")
i=len(s)-1
target="
while i>=0:
target=target+s[i]
i=i-1
print(target)
output:
-------
Input:Learning Pythonis very Easy
output:Easy Very is Python Learning
1st way:
--------
s=input("Enter Some String:")
print("Charatcers at even position:",s[0::2])
print("Characters at odd position:",s[1::2])
2nd way:
--------
s=input("Enter some string:")computers
i=0
print("Character at even position:")
whiel i<len(s):
print(s[i],end=',')
i=i+2
print()
print("Characters at odd Position:")
i=1
while i<len(s):
print(s[i],end=',')
i=i+2
Input: s1="ravi"
s2="Teja"
output: rtaevjia
6)
write a program to sort the characters of the string and First alphabet
symbols followed by numaric values:
Input:B4A1D3
output:ABD134
s=input("Enter First String:")
s1=s2=output=''
for x in s:
if x.isalpha():
s1=s1+x
else:
s2=s2+x
for x in sorted(s1):
output=output+x
for x in sorted(s2):
output=output+x
print(output)
9)write a program to remove duplicates characters from the given input string:
Input:ABCDABBCDABBBCCCDDEEEF
output:ABCDEF
10)
write a program to find the number of occurrences of each character present in the given
string:
Input:ABCABCABBCDE
output:A-3,B-4,C-3,D-1,E-1
11)
write a program to perform the following task:
name='naresh'
salary=10000
age=28
print("{}'s salary is {} and his age {}".format(name,salary,age))
print("{0}'s salary is{1} and his age{2}".format(name,salary,age))
print("{x}'s salary is{y} and his age{z}".format(z=age,y=salary,x=name))
output:
naresh's salary is 10000 and his age 28
naresh's salary is10000 and his age28
naresh's salary is10000 and his age28
Case:2:Formatting Numbers
------
d->Decimal Number
f->Fixed point number(float).The default precision is 6
b->Binary format
o->octal Format
x->Hexa Decimal Format(Lower Case)
X->Hexa Decimal Format(Upper case)
Eg:1
print("The integer Number is:{}".format(123))
print("The integer Number is:{:d}".format(123))
print("The integer Number is:{:5d}".format(123))
print("The integer Number is:{:05d}".format(123))
Output:
The integer Number is:123
The integer Number is:123
The integer Number is: 123
The integer Number is:00123
Eg:2
print("The float number is:{}".format(123.4567))
print("The float number is:{:f}".format(123.4567))
print("The float number is:{:8.3f}".format(123.4567))
print("The float number is:{:08.3f}".format(123.4567))
print("The float number is:{:08.3f}".format(123.45))
print("The float number is:{:083f}".format(786786123.45))
output:
NOTE:
1.{:08.3f}
2.Total positions should be minimum 8
3.After decimal point exactly 3 digits are allowed.If it less then 0s will be placed in the last
positions
4.If total number<8 positions then 0 will be placed MSBs
5.if total number>8 positions then all integer digits will be considered.
6.The extra digit we can take only 0.
Eg:3
print Decimal value in binary, octal and hexadecimal form
output:
Binary Form:10011001
Octal Form:231
Hexa decimal Form:9a
HexaDeciaml Form:9A
Note:We can Represent only int values in binary,octal and hexadecimal and it is not possible
for float values.
Note:
1){:5d} it takes an integer argument and assigns a minimum width of 5.
2){:8.3f} it takes a float argument and assigns a minimum width of 8 including"."and after
decimal point exactly 3 digits are allowed with round operation if required
3){:05d} the blank spaces can be filled with 0.In this place only 0 allowed.
Case:3
Number Formating for signed numbers.
2.Using plus for -ve numbers there is no use and for -ve number -sign will come
automatically.
Output:
Int value with:+123
Int value with sign:-123
Float value with sign:+123.456000
Float value with sign:-123.456000
Eg:
print("{:5d}".format(12))
print("{:<5d}".format(12))
print("{:<05d}".format(12))
print("{:>5d}".format(12))
print("{:>05d}".format(12))
print("{:^5d}".format(12))
print("{:=5d}".format(-12))
print("{:^10.3f}".format(12.23456))
print("{:=8.3f}".format(-12.23456))
Output:
12
12
12000
12
12
00012
12
-12
12.235
-12.235
print("{:5d}".format(12))
print("{:5}".format("rat"))
print("{:>5}".format("rat"))
print("{:<5}".format("rat"))
print("{:^5}".format("rat"))
print("{:*^5}".format("rat")) #instead of * we can use any character(like +,$,a etc)
Output:
12
rat
rat
rat
rat
*rat*
Note: For numbers default alignment is right where as for string default alignment is left
Case:6
Truncating String with format() method
print("{:.3}".format("nicesoftware"))
print("{:5.3}".format("nicesoftware"))
print("{:>5.3}".format("nicesoftware"))
print("{:^5.3}".format("nicesoftware"))
print("{:*^5.3}".format("nicesoftware"))
output:
nic
nic
nic
nic
*nic*
person={'age':48,'name':'durga'}
print("{p[name]}'s age is:{p[age]}".format(p=person))
Output:
durga's age is:48
Note: p is alias name of dictionary
person dictionary we are passing as keyboard argument
person={'age':28,'name':'naresh'}
print("{name}'s age is :{age}".format(**person))
Output:
Naresh age is:28
Case:8
Formatting class members using format()
class person:
age=28
name="naresh"
print("{p.name}' age is :{p.age}".format(p=person()))
class Person:
def__init__(self,name,age):
self.name=name
self.age=age
print("{p.name}'s age is:{p.age}".format(p=Person('naresh',28)))
print("{p.name}'s age is:{p.age}".format(p=Person('Ravi',50)))
Note:
Here person object is passed as keyword argument .We can access by using its refference
variable in the template string.
Case:9
Dynamic Formatting using format()
string="{:{fill}{align}{width}}"
print(string.format('cat',fill='*',align='^',width=5))
print(string.format('cat',fill='*',align='^',width=6))
print(string.format('cat',fill='*',align='<',width=6))
print(string.format('cat',fill='*',align='>',width=6))
Output:
*cat*
*cat**
cat***
***cat
Case:10
--------
Dynamic Float format template
num="{:align}{width}.{precision}f}"
print(num.format(123.236,align='<',width=8,precision=2))
print(num.format(123.236,align='>',width=8,precision=2))
Output:
123.24
123.24
Case:11
-------
Formating Date Values
import datetime
#datetime formatting
date=datetime.datetime.now()
print("it 's now:{:%d/%m/%Y %H:%M:%S}".format(date))
complexNumber=1+2j
print("Real Part:{0.real} and imaginary Part:{0.imag}".format(complexNumber))
-6 -5 -4 -3 -2 -1
10 A B 20 30 10
0 1 2 3 4 5
[]
<class 'list'>
2)If we know elements already then we can create list as follows list=[10,20,30,40]
c:\1>py test.java
Enter List:[10,20,30,40]
[10,20,30,40]
<class,'list'>
c:\1>py test.py
[0,2,4,6,8]
<class 'list'>
Eg:1
s="naresh"
l=list(s)
print(l)
c:1>py test.py
['n','a','r','e','s','h']
c:1>py test.py
['Learning','python','is','very','very','Easy']
Note:Some time we can take list inside another list, such type of list are called nested lists.
[10,20,[30,40]]
-4 -3 -2 -1
10 20 30 40
0 1 2 3
print(list[0])->10
print(list[-1])->40
print(list[10])->Index error : list index out of range
start->It indicates the Index where slice has to start default value is 0.
stop-> It indicates the Index where slice has to End Default Value is max allowed Index of
List ie Length of the List
Step->increment value
Default Value is 1
n=[1,2,3,4,5,6,7,8,9,10]
print(n[2:7:2])
print(n[4::2])
print(n[3:7])
print(n[8:2:-2])
print(n[4:100])
output:
c:1>py test.py
[3,5,7]
[5,7,9]
[4,5,6,7]
[9,7,5]
[5,6,7,8,9,10]
List vs Mutability:
-------------------
Once we creates a List object,We can modify its content.Hence List objects are mutable.
n=[10,20,30,40]
print(n)
n[1]=777
print(n)
c:1>py test.py
[10,20,3,40]
[10,777,30,40]
c:1>py test.py
0
2
4
6
8
10
c:1>py test.py
A is available at positive index:0 and at negative index:-3
B is available at positive index:0 and at negative index:-2
C is available at positive index:0 and at negative index:-1
n=[1,2,2,2,2,3,3]
print(n.count(1))
print(n.count(2))
print(n.count(3))
print(n.count(4))
o/p:.append
c:1>py test.py
1
4
2
0
Note:If the specified element not present in the list then we will get ValueError.Hence
before index() method we have to check whether item present in the list or not by using in
operator.
print(4 in n)->false
list=[]
list.append("A")
list.append("B")
list.append("C")
print(list)
c:\1>py test.py
['A','B','C']
c:\1>py test.py
[0,10,20,30,40,50,60,70,80,90,100]
2)insert() Function:
To insert item at specified index position
n=[1,2,3,4,5]
n.insert(1,888)
print(n)
c:\1>py test.py
[1,888,2,3,4,5]
eg:1
n=[1,2,3,4,5]
n.insert(10,777)
n.insert(-10,999)
print(n)
c:\1>py test.py
[999,1,2,3,4,5]
[999,1,,2,3,4,5,777]
Note:If the specified index is greater than max index then element will be
inserted at last position.If the specified index is smaller than element will be
inserted at first position.
3) extend() Function:
---------------------
To add all items of one list to another list.
l1.extends(l2)
all items present in l2 will be added to l1
order1=["Chicken","Mutton","Fish"]
order2=["RC","KF","FO"]
order1.extend(order2)
print(order1)
c:1\>py test.py
['Chicken','Mutton','Fish','RC','KF','FO']
order=["Chicken","Mutton","Fish"]
order.extend("Mushroom")
print(order)
c:1>py test.py
["Chicken","Mutton","Fish","M","u","s","h","r","o","o","m"]
4)remove() Function:
--------------------
We can use this function to remove specified item from the list.If the item present multiple
times
then only first occurence will be removed.
n=[10,20,10,30]
n.remove(10)
print(n)
c:1>py test.py
[20,10,30]
If the specified item not present in list then we will get ValueError.
n=[10,20,10,30]
n.remove(40)
print(n)
Note:Hence before using remove() method first we have to check specified element
present in the list or not by using in operator.
5)pop() Function:
----------------
It removes and returns the last element of the list.
This is only function which manipulate list and returns some element.
n=[10,20,30,40]
print(n.pop())
print(n.pop())
print(n)
c:1>py test.py
40
30
[10,20]
n=[]
print(n.pop())->index error:pop from empty list
Note:
1)pop() is the only function which manipulates the list and returns some value
2)In general we can use append() and pop() functions to implement stack datastructure
by using list,which follows LIFO(Last in first out) order.
In general we can use pop() function to remove last element of the list. but we can use to
remove
elements based on index.
n=[10,20,30,40,50,60]
print(n.pop())->60
print(n.pop(1))->20
print(n.pop(10))-> Index error :pop index out of range
Note:List Objects are dynamic.i.e. based on our requirement we can increase and decrease
the size.
1)reverse():
------------
We can use to reverse() order of elements of list.
n=[10,20,30,40]
n.reverse()
print(n)
c:1>pt test.py
[40,30,20,10]
2)sort():
---------
In list by default insertion order is preserved.If we want to sort the elements of list
according to default natural sorting order then we should go for sort() method.
n=[20,5,15,10,0]
n.sort()
print(n)->[0,5,10,15,20]
s=["Dog","Banana","Cat","Apple"]
s.sort()
print(s)->['Apple','Banana','Cat','Dog']
Note:To use sort() function,compulsory list should contain only homogeneous elements.
Otherwise we will get TypeError.
n=[20,10,"A","B"]
n.sort()
print(n)
Type Error:'<' not supported between instance of 'str' and 'int'.
Note:In Python 2 if list contains both numbers and Strings then sort() functions first sort
numbers followed by strings.
n=[20,"B",10,"A"]
n.sort()
print(n)#[10,20,'A','B']
n=[40,10,30,20]
n.sort()
print(n)->[10,20,30,40]
n.sort(reverse=True)
print(n)->[40,30,20,10]
n.sort(reverse=False)
print(n)->[10,20,30,40]
x=[10,20,30,40]
y=x
print(id(x))
print(id(y))
The problem in this approach is by using one reference variable if we are changing
content,then those changes will be reflected to the other reference variable.
x=[10,20,30,40]
y=x;
y[1]=777
print(x)->[10,777,30,40]
Eg:
c=a+40->Type error: can only concatenate list(not "int") to list
c=a+[40]->valid
2)Repetition Operator(*):
-------------------------
We can use repetition operator * to repeat elements of list specified number of times.
x=[10,20,30]
y=x*3
print(y)->[10,20,30,10,20,30,10,20,30]
x=["Dog","Cat","Rat"]
y=["Dog","Cat","Rat"]
z=["DOG","CAT","RAT"]
print(x==y)->True
print(x==z)->False
print(x!=z)->True
Note:Whenever we are using comparison operators (==,!=) for List object then the
following should be considered.
1)The Number of Elements
2)The Order of Elements
3)The Content of Elements(Case Sensitive)
Note:When ever we are using relational Operators(<,<=,>,>=) between List Object,
only 1st Element comparison will be performed.
x=[50,20,30]
y=[40,50,60,100,200]
print(x>y)->True
print(x>=y)->True
print(x<y)->False
print(x<=y)->False
Eg:
x=["Dog","Cat","Rat"]
y=["Rat","Cat","Dog"]
print(x>y)->False
print(x>=y)->False
print(x<y)->True
print(x<=y)->True
Membership Operators:
---------------------
We can check wheather element is a member of the list or not by using membership
operators.
in Operator
not in Operator
n=[10,20,30,40]
print(10 in n)
print(10 not in n)
print(50 in n)
print(50 not in n)
output:
-------
True
False
False
True
clear() Function:
-----------------
We can use clear() function to remove all elements of List.
n=[10,20,30,40]
print(n)
n.clear()
print(n)
output:
c:\>py test.py
[10,20,30,40]
[]
Nested Lists:
-------------
Sometimes we can take one list inside another list.Such type of lists are called
needed lists.
n=[10,20,[30,40]]
print(n)
print(n[0])
print(n[2])
print(n[2][0])
print(n[2][1])
Output:
c:1> py test.py
[10,20,[30,40]]
10
[30,40]
30
40
Note:We can access nested list elements by using index just like accessing
multi dimensional array elements.
n=[[10,20,30],[40,50,60],[70,80,90]]
print(n)
print("Elements by Rows wise:")
for r in n:
print(r)
print("Elements by Matrix style:")
for i in range(len(n)):
for j in range(len(n[i])):
print(n[i][j],end=' ')
print()
output:
c:1>py test.py
[[10,20,30],[40,50,60],[70,80,90]]
c:\1>py test.py
[1,4,9,16,25,36,49,64,81,100]
[2,4,8,16,32]
[4,16,36,64,100]
eg:
words=["Balaiah","Nag","Venkatesh","Chiranjeevi"]
l=[w[0] for w in words]
print(l)
output: ['B','N','V','C']
num1=[10,20,30,40]
num2=[30,40,50,60]
num3=[i for i in num1 if i not in num2]
print(num3) [10,20]
Eg:
words="the quick brown fox jumps over the lazy dog".split()
print(words)
l=[[w.upper(),len(w)] for w in words]]
print(l)
output:
['the','quick','fox','jumps','over','the','lazy','dog']
[['THE',3],['QUICK',5],['BROWN',5],['FOX',3],['JUMPS',5],['OVER',4],['THE',3],['LAZY',4],
['DOG',3]]
EG:
WRITE A PROGRAM TO DISPLAY UNIQUE VOWELS PRESENT IN THE GIVEN WORD?
vowels=['a','e','i','o','u']
word=input("Enter the word to search for vowels:")
found=[]
for letter in word:
if letter in vowels:
if letter not in found:
found.append(letter)
print(found)
print("The number of different vowels present in",word,"is",len(found))
c:1>py test.py
List out all Functions of List and write a program to use these Functions.
t=10,20,30,40
print(t)
print(type(t))
output:
(10,20,30,40)
<class 'tuple'>
t=()
print(type(t))->tuple
Note:We have to take special care about single valued tuple.compulsary the value should
ends with comma,
otherwise it is treated as tuple.
eg:1
t=(10)
print(t)
print(type(t))
outut
10
<class'int'>
eg:2
t=(10,)
print(t)
print(type(t))
output:
(10,)
<class 'tuple'>
Tuple Creation:
------------------
1)t=()
Creation of empty Tuple
2)t=(10,)
t=10,
Creation of Single valued Tuple,Parenthisis are optional,should ends with comma
3)
t=10,20,30
t=(10,20,30)
Creation of multi values Tuples & Parenthesis are Optional.
list=[10,20,30]
t=tuple(list)
print(t)
t=tuple(range(10,20,2))
print(t)
output:
(30,40,50)
(30,40,50,60)
(10,30,50)
Tuple vs Immutability:
----------------------
Once we creates Tuple, we cannot change its content.
Hence tuple objects are immutable.
Eg:
t=(10,20,30,40)
t[1]=70->Type Error:'tuple' object does not support item assignment
t1=(10,20,30)
t2=t1*3
print(t2)->(10,20,30,10,20,30,10,20,30)
Eg:t=(10,20,30,40)
print(len(t))->4
2)count()
To return number of occurrences of given element in the tuple
Eg:t=(10,20,10,10,20)
print(t.count(10))->3
3)index()
Returns index of first occurences of the given element.
If the specified element is not available then we will get ValueError.
Eg: t=(10,20,10,10,20)
print(t.index(10))->0
print(t.index(30))->ValueError:tuple.index(x):x not in tuple
4)sorted()
To sort elements based on default natural sorting order.
t=(40,10,30,20)
t1=sorted(t)
print(t1)
print(t)
output:
-------
(10,20,30,40)
(40,10,30,20)
t=(40,10,30,20)
print(min(t))->10
print(max(t))->40
6)cmp():
--------
It compares the elements of both tuples.
if both tuples are equal then return 0.
if the first tuple is less than second tuple then it returns -1
if the first tuple is greater than second tuple then it returns +1.
t1=(10,20,30)
t2=(40,50,60)
t3=(10,20,30)
print(cmp(t1,t2))->-1
print(cmp(t1,t3))->0
print(cmp(t2,t3))->+1
Eg:
a=10
b=20
c=30
d=40
t=a,b,c,d
print(t)->(10,20,30,40)
Here a,b,c,d are packed into a Tuple t.This is nothing but Tuple packing.
Tuple unpacking is the reverse process of Tuple packing.
We can unpack a Tuple and assign its values to different variables.
t=(10,20,30,40)
a,b,c,d=t
print("a=",a,"b=",b,"c=",c,"d=",d)
Output:a=10 b=20 c=30 d=40
Note:At the time of tuple unpacking the number of variables and number of values
should be same,otherwise we will get ValueError.
Eg:
t=(10,20,30,40)
a,b,c=t->Value Error:too many values to unpack(expected 30)
Tuple Comprehension:
--------------------
Tuple Comprehension is not supported by Python.
t=(x**2 for x in range(1,6))
Here we are not getting tuple object and we are getting generator object.
c:1>py test.py
<class 'generator'>
1
4
9
16
25
Q)Write a program to take a Tuple of Numbers from the keyboard and Print
its Sum and Average?
c:\1>py test.java
Enter Tuple of Numbers:(10,20,30,40)
The Sum=100
The Average=25.0
c:1>py test.py
Enter Tuple of Numbers:(100,200,300)
The Sum=600
The Average=200.0
List Tuple
1)List is a Group of comma separeated Tuple is a Group of comma seperated
values within Square Brackets and Values with in Parenthisis and
square Brackets are mandatory. Parenthisis are optional.
Eg: i=[10,20,30,40] Eg: t=(10,20,30,40)
t=10,20,30,40
2.List Objects are Mutable i.e Once we Tuple Objects are Immutable i.e once
create List Object we can perform any we create Tuple Object we cannot
changes in that object. change its content.
Eg:i[1]=70 t[1]=70->ValueError:tuple
object
does not
support item assignment.
3)If the Content is not fixed and keep on If the content is fixed and never changes
changes then we should go for List. then we should go for Tuple.
4)List Objects can not used as Keys for Tuple Objects can be used as
Keys for
Dictionary because Keys should be Dictionary because Keys should
be
Hashable and Immutable. Hashable and Immutable.
---------------------------------------------------------------------------------------------------------------
Output
------
{40,10,20,30}
<class 'set'>
Eg1:
---
l=[10,20,30,40,10,20,10]
s=set(l)
print(s)#{40,10,20,30}
Eg2:
---
s=set(range(5))
print(s)#{0,1,2,3,4}
Note:
-----
while creating empty set we have to take special care.
compulsory we should use set() function.
s={} ->it is treated as dictionary but not empty set.
s={}
print(s)
print(type(s))
Output
-------
{}
<class,'dict'>
Eg:
---
s=set()
print(s)
print(type(s))
Output
------
set()
<class,'set'>
2)update(x,y,z):
-----------------
To add multiple items to the set.
Arguments are not individual elements and these are iterable objects like List,Range etc.
All elements present in the given iterable objects will be added to set.
s={10,20,30}
L=[40,50,60,10]
s.update(L,range(5))
print(s)
Output:
------
{0,1,2,3,4,40,10,50,20,60,30}
3)copy():
---------
1) returns copy of the set.
2) it is cloned object.
s={10,20,30}
s1=s.copy()
print(s1)
4)pop():
--------
it removes and returns some random element from the set.
s={40,10,30,20}
print(s)
print(s.pop())
print(s)
Output
------
{40,10,20,30}
40
{10,20,30}
5)remove(x):
------------
1) It removes specified element from the set.
2) If the specified element not present in the set then we will get keyError.
s={40,10,30,20}
s.remove(30)
print(s) {40,10,20}
s.remove(50) keyerror-50
6)discard(x):
-------------
1) It removes the specified element from the set.
2) If the specified element not present in the set then we won't get any error.
s={10,20,30}
s.discard(10)
print{<>(s) 20,30}
s.discard(50)
print(<>(s) 20,30}
7)clear():
----------
To remove all elements from the set.
s={10,20,30}
print(s)
s.clear()
print(s)
Output:
-------
{10,20,30}
set()
2)intersection():
------------------
x.intersection(y)OR x&y.
Returns common elements present in both x and y.
x={10,20,30,40}
y={30,40,50,60}
print(x.intersection(y))->{40,30}
print(x&y)->{40,30}
3)difference():
---------------
x.difference(y) OR x-y.
returns the elements present in x but not in y.
x={10,20,30,40}
y={30,40,50,60}
print(x.difference(y))->10,20
print(x-y)->{10,20}
print(y-x)->{50,60}
4)symmetric_difference():
-------------------------
x.symmetric_difference(y) Or x^y.
Returns elements present in either x OR y but not in both.
x={10,20,30,40}
y={30,40,50,60}
print(x.symmetric_difference(y))->{10,50,20,60}
print(x^y)->{10,50,20,60}
Output:
-------
{'u','g','r','d','a'}
True
False
Set Comprehension:
------------------
set comprehension is possible.
D:\Python_classes>py test.py
Enter word to search for vowels:durga
The different vowel present in durga are{'u','a'}
Eg:
rollno----name
phone number---address
ipaddress----domainname
Note:In c++ and java Dictionaries are known as "Map" where as in Perl and Ruby It is
Known as "Hash"
How to create Dictionary?
-------------------------
d={} or d-dict()
We are creating empty dictionary.We can add entries as follows.
d[100]="durga"
d[200]="ravi"
d[300]="shiva"
print(d)->{100:'durga',200:'ravi',300:'shiva'}
d={100:'durga',200:'ravi',300:'shiva'}
d={key:value,key:value}
d={100:'durga',200:'ravi',300:'shiva'}
print(d[100]) #durga
print(d[300]) #shiva
we can represent this by checking whether is already available or not by using has_key()
function or by using in oprator.
d.has_key(400)-> Returns 1 if key is available otherwise returns 0
But has_key()function is available only in python 2 but not in python 3. Hence compulsory
we have to use in operator.
if 400 in d:
print(d[400])
q)write a program to enter name and percantage marks in a Dictionary and display
information on the screen
---------------------------------------------------------------------------------------------------------------------------
-------
rec={}
n=int(input("Enter number of students:"))
i=1
while i<=n:
name =input("Enter student name:")
marks=input("Enter % of marks of student:")
rec[name]=marks
i=i+1
print("Name of student",name,"% of marks",marks)
for x in rec:
print("\t",x,"\t",rec[x])
D:\python_classes>py test.py
Enter number of students:3
Enter student name :durga
Enter % of marks of student:60%
Enter student name : ravi
Enter % of marks of student:70%
Enter student name : shiva
Enter % of marks of student :80%
Name of student % of marks
--------------- -----------
Durga 60%
ravi 70%
shiva 80%
2)d.clear()
---------
To remove all entries from the dictionary.
d={100:"durga",200:"ravi",300:"shiva"}
print(d)
d.clear()
print(d)
output:
{100:'durga',200:'ravi',300:'shiva'}
{}
3)del d:
-------
to delete total dictionary. Now we cannot access d.
d= {100:"durga",200:'ravi',300:"shiva"}
print(d)
del d
print(d)
output:
-------
{100:'durga',200:'ravi',300:'shiva'}
nameerror: name 'd' is not defined
3)clear():
To remove all elements from the dictionary.
4)get():
To get the value associated with the key
d.get(key)
if the key is available then returns the corresponding value otherwise returns None.it wont
raise any error.
d.get (key,defaultvalue)
if the key is availble then returns the corresponding value otherwise returns default value.
d={100:"durga",200:"ravi",300:"shiva"}
print(d[100])-> durga
print(d[400])->keyerror:400
print(d.get(100))->durga
print(d.get(400))->none
print(d.get(100,'Guest'))->durga
print(d.get(400,'Guest'))->Guest
5)pop():
--------
d.pop(key)
1).It removes the entry associated with the specified key and return the corresponding
value.
2).If the specified key is not available then we will get KeyError.
d={100:"durga",200:"ravi",300:"shiva"}
print(d.pop(100))
print(d)
print(d.pop(400))
output
------
durga
{200:'ravi',300:'shiva'}
KeyError:400
6)popitem():
-------------
It removes an arbitrary item(key-value)from the dictionary and returns it.
d={100:"durga",200:"ravi",300:"shiva"}
print(d)
print(d.popitem())
print(d)
output
------
{100:'durga',200:'ravi',300:'shiva'}
(300,'shiva')
{100:'durga',200:'ravi'}
if the dictionary is empty then we will get KeyError
d={}
print(d.popitem())==>KeyError:'popitem():dictionary is empty'
7)keys():
----------
it returns all keys associated with dictionary.
d={100:"durga",200:"ravi",300:"shiva"}
print(d.keys())
for k in d.keys():
print(k)
output
------
dict_keys([100,200,300])
100
200
300
8)values():
-----------
It returns all values associated with the dictionary.
d={100:"durga",200:"ravi",300:"shiva"}
print(d.values())
for v in d.values():
print(v)
output
------
dict_values(['durga','ravi','shiva'])
durga
ravi
shiva
9)items():
----------
It returns list of tuples representing key-value pairs.
[(k,v),(k,v),(k,v)]
d={100:"durga",200:"ravi",300:"shiva"}
for k,v in d.items():
print(k,"--",v)
output
-------
100--durga
200--ravi
300--shiva
10)copy():
-----------
To create exactly duplicate dictionary(cloned copy)
d1=d.copy();
11)setdefault():
----------------
d.setdefault(k,v)
1)If the key is already available then this function returns the corresponding value.
2)If the key is not available then the specified key-value will be added as new item to the
dictionary.
d={100:"durga",200:"ravi",300:"shiva"}
print(d.setdefault(400,"pavan"))
print(d)
print(d.setdefault(100,"sachin"))
print(d)
output
-------
pavan
{100:'durga',200:'ravi',300:'shiva',400:'pavan'}
durga
{100:'durga',200:'ravi',300:'shiva',400:'pavan'}
12)update():
-------------
d.update(x)
All items present in the dictionary x will be added to dictionary d
Q) write a program to take dictionary from the keyboard and print the sum of values?
-------------------------------------------------------------------------------------
d=eval(input("Enter dictionary:"))
s=sum(d.values())
print("sum=",s)
output
------
D:\python_classws>py test.py
Enter dictionary:{'A':100,'B':200,'c':300}
sum=600
Q)write a program to find number of occurences of each letter present in the given string?
-------------------------------------------------------------------------------------------
word=input("enter any word:")
d={}
for x in word:
d[x]=d.get(x,0)+1
for k,v in d.items():
print(k,"occurred",v,"times")
output
------
D:\python_classws>py test.py
Enter any word:mississippi
m occurred 1 times
i occurred 4 times
s occurred 4 times
p occurred 2 times
Q)write a program to find number of occurrences of each vowel present in the given string?
-------------------------------------------------------------------------------------------
word=input("Enter any word:")
vowels={'a','e','i','o','u'}
d={}
for x in word:
for x in vowels:
d[x]=d.get(x,0)+1
for k,v in sorted(d.items()):
print(k,"occurred",v,"times")
output
-------
D:\python_classws>py test.py
Enter any word:doganimaldoganimal
a occurred 4 times
i occurred 2 times
o occurred 2 times
Q)write a program to accept student name and marks from the keyboard and creates a
dictionary.also display student marks by taking
---------------------------------------------------------------------------------------------------------------------------
---------
student name as input?
-----------------------
output
------
D:\python_classws>py test.py
Enter the number of students:5
Dictionary Comprehension:
--------------------------
Comprehension concept application for dictionaries also.
output
-------
{1:1,2:4,3:9,4:16,5:25}
{1:2,2:4,3:6,4:8,5:10}
----------------------------------------------------------------------------------------------------------
FUNCTIONS
----------
-If a group of statements is repeatedly required then
it is not recommended to write these statements everytime seperately.
we have to define these statements as a single unit and we can call that unit
any number of times based on our requirement without rewriting.
This unit is nothing but function
-The main advantage of functions is code reusability.
1)Built in functions
----------------------
The functions which are coming along with python software automatically,
are called built in functions or pre defined functions.
Eg:
----
id()
type()
input()
eval()
etc..
note:
-----
while creating functions we can use 2 keywords
1)def(mandatory)
2)return(optional)
Eg 1:
-----
write a function to print hello
test.py
-------
1)def wish():
2) print("hello Good Morning")
3) wish()
4) wish()
5) wish()
Parameters
-----------
parameters are inputs to the function.if a function contains parameters,
then at the time of calling,compulsory we should provide
values otherwise, we will get error.
Eg:
---
write a function to take name of the student as input and print wish message by name.
1) def wish(name):
2) print("hello",name,"Good Morning")
3) wish("durga")
4) wish("Ravi")
D:/Python_classses>py test.py
Hello Durga Good morning
Hello Ravi Good Morning
Eg:write a function to take number as input and print its square value
--
1) def squarelt(number):
2) print("The Square of",number,"is",number*number)
3) squarelt(4)
4) squarelt(5)
D:/Python_classses>py test.py
The Square of 4 is 16
The Square of 5 is 25
Return Statement:
-----------------
Function can take input values as parameters and executes business logic,
and returns output to the caller with return statement.
D:/Python_classses>py test.py
The sum is 30
The sum is 300
If we are not writing return statement then default return value is None.
1) def f1():
2) print("Hello")
3) f1()
4) print(f1())
output
-------
Hello
Hello
None
1)def even_odd(num):
2) if num%2==0:
3) print(num,"is Even Number")
4) else:
5) print(num,"is odd number")
6) even_odd(10)
7) even_odd(15)
output
-------
D:/Python_classses>py test.py
10 is even number
15 is odd number
x=int(input("Enter a no:"))
print("factorial of",x," =",fact(x))
Output
-------
D:/Python_classses>py test.py
The Factorial of 1 is : 1
The Factorial of 2 is : 2
The Factorial of 3 is : 6
The Factorial of 4 is : 24
Eg 1:
------
1) def sum_sub(a,b):
2) sum=a+b
3) sub=a-b
4) return sum,sub
5) x,y=sum_sub(100,50)
6) print("The sum is :",x)
7) print("The substraction is:",y)
Output
------
The sum is: 150
The substraction is :50
Eg 2:
-----
1) def calc(a,b):
2) sum=a+b
3) sub=a-b
4) mul=a*b
5) div=a/b
6) return sum,sub,mul,div
7) t=calc(100,50)
8) print("The Results are")
9) for i in t:
10) print(i)
Output:
-------
The Results are
150
50
5000
2.0
Types of arguments
-------------------
def f1(a,b)
------
------
------
f1(10,20)
1) Positional Arguments
-----------------------
-> These are the arguments passed to function in correct positional order.
def sub(a,b)
print(a-b)
sub(100,200)
sub(200,100)
-> The number of arguments and postion of arguments must be matched.if we change the
order then result may be changed.
-> If we change the number of arguments then we will get error.
2)Keyword Arguments:
--------------------
we can pass argument values by keyword i.e, by parameter name.
1) def wish(name,msg):
2) print("hello",name,mgs)
3) wish(name="Durga",mgs="Good Morning")
4) wish(mgs="Good Morning",name="Durga")
Output
------
Hello Durga Good Morning
Hello Durga Good Morning
Here the order of arguments is not important but number of arguments must be matched.
Note:
----
We can use both positional and keyword arguments simultaneously.But first we have to take
positional arguments and then keyword arguments,otherwise we will get syntax error.
1) def wish(name,msg):
2) print("Hello",name,mgs)
3) wish("Durga","GoodMorning")->valid
4) wish("Durga",msg="GoodMorning")->valid
5) wish(name="Durga","GoodMorning")->invalid
6) SyntaxError:positional argument follows keyword argument
3)Default Arguments:
---------------------
sometimes we can provide default values for our positional arguments.
1) def wish(name="Guest"):
2) print("Hello",name,"Good Morning")
3) wish("Durga")
4) wish()
Output
-------
Hello Durga Good Morning
Hello Guest Good Morning
If we are not passing any name then only default value will be considered
***Note:
--------
After default arguments we should not take non default arguments.
1) def sum(*n):
2) total=0
3) for n1 in n:
4) total=total+n1
5) print("The Sum=",total)
6)
7) sum()
8) sum(10)
9) sum(10,20)
10) sum(10,20,30,40)
Output
-------
The sum=0
The sum=10
The sum=30
The sum=100
Note:
-----
we can mix variable length arguments with positional arguments.
1) def f1(n1,*s):
2) print(n1)
3) for s1 in s:
4) print(s1)
5)
6) f1(10)
7) f1(10,20,30,40)
8) f1(10,"A",30,"B")
Output
-------
10
10
20
30
40
10
A
30
B
Note:
----
After variable length argument,if we are taking any other arguments then we should provide
values as keyword arguments.
1) def f1(*s,n1):
2) for s1 in s:
3) print(s1)
4) print(n1)
5)
6) f1("A","B",n1=10)
Output
------
A
B
10
f1("A","B",10)->Invalid
TypeError:f1()missing 1 required keyword-only argument:'n1'
Note:
----
We can declare key word variable length arguments also.
*For thia we have to use**.
*def f1(**n):
*we can call this function by passing any number of keyword arguments.internally these
keyword arguments will be stored inside a dictionary
1) def display(**kwargs):
2) for k,v in kwargs.items():
3) print(k,"=",v)
4) display(n1=10,n2=20,n3=30)
5) display(rno=100,name="Durga",marks=70,subject="Java")
Output
------
n1 = 10
n2 = 20
n3 = 30
rno = 100
name = Durga
marks = 70
subject = Java
Case Study:
-----------
def f(arg1,arg2,arg3=4,arg4=8):
print(arg1,arg2,arg3,arg4)
1) f(3,2)-> 3 2 4 8
2) f(10,20,30,40)-> 10,20,30,40
3) f(25,50,arg4=100)->25 50 4 100
4) f(arg4=2,arg1=3,arg2=4) -> 3 4 4 2
5) f()-> Invalid
TypeError: f() missing 2 required positional arguments:'arg1' and 'arg2'
6) f(arg3=10,arg4=20,30,40)-> Invalid
SyntaxError: positional argument follows keyword argument
[After Keyword arguments we should not take positional arguments]
7) f(4,5,arg2=6)->Invalid
TypeError:f()got an multiple values for argument 'arg2'
8) f(4,5 arg3=5,arg5=6)->Invalid
TypeError:f() got an unexpected keyword argument 'arg5'
Note:
-----
Function vs module vs Library
1) A group of lines with some name is called a function
2) A group of functions saved to a file, is called module
3) A group of modules is nothing but library
Library
------------------------------
module1 module2
-------- --------
function 1 function 1
function 2 function 2
function 3 function 3
function
---------
---------
---------
---------
---------
---------
---------
---------
Types of Variables
-------------------
python supports 2 types of variables.
1) Global Variables
2) local Variables
1) Global Variables
--------------------
- The variables which are declared outside of function are called global variables.
- These variables can be accessed in all functions of that module.
Output
------
10
10
2)Local Variables:
------------------
* The variables which are declared inside a function are called local variables.
* Local variables are available only for the function in which we declared it.i.e from outside of
function we cannot access.
1) def f1():
2) a=10
3) print(a) #valid
4)
5) def f2():
6) print(a) #invalid
7)
8) f1()
9) f2()
Global keyword:
---------------
we can use global keyword for the following 2 purposes:
1) To declare global variable inside function
2) To make global variable available to the function so that we can perfom required
modifications
1) a=10
2) def f1():
3) a=777
4) print(a)
5)
6) def f2():
7) print(a)
8)
9) f1()
10) f2()
11)
Output
-------
777
10
1) a=10
2) def f1():
3) global a
4) a=777
5) print(a)
6) def f2():
7) print(a)
8)
9) f1()
10) f2()
Output
------
777
777
1) def f1():
2) a=10
3) print(a)
4)
5) def f2():
6) print(a)
7)
8) f1()
9) f2()
Output:
-------
NameError:name'a' is not defined
1) def f1():
2) global a
3) a=10
4) print(a)
5)
6) def f2():
7) print(a)
8)
9) f1()
10) f2()
Output:
-------
10
10
Note:
----
If global variable and local variable having the same name then we can access global
variable inside a function as follows
1) a=10->Global variable
2) def f1():
3) a=777->Local Variable
4) print(a)
5) print(globals()['a'])
6) f1()
Output
-------
777
10
Recursive functions
-------------------
A function that calls itself is known as Recursive Function.
Eg:
---
factorial(3)= 3*factorial(2)
= 3*2*factorial(1)
= 3*2*1*factorial(0)
= 3*2*1*1
=6
factorial(n)= n*factorial(n-1)
1) def factorial(n):
2) if n==0:
3) result=1
4) else:
5) result=n*factorial(n-1)
6) return result
7) print("Factorial of 4 is:",factorial(4))
8) print("Factorial of 5 is:",factorial(5))
Output
------
Factorial of 4 is: 24
Factorial of 5 is : 120
Anonymous Functions:
--------------------
-Sometimes we can declare a function without any name,such type of nameless functions
are called anonymous functions or lambda functions.
-The main purpose of anonymous function is just for instant use(i,e for one time usage)
Normal Function:
----------------
We can define by using def keyword.
def squarelt(n):
return n*n
Lambda Function:
----------------
we can define by using lambda keyword lambda n:n*n
Note:
-----
By using lambda Functions we can write very concise code so that readability of the program
will be improved.
Output
-------
The square of 4 is:16
The square of 5 is:25
Output
-----
The Sum of 10,20 is: 30
The Sum of 100,200 is: 300
Output
------
The Biggest of 10,20 is:20
The Biggest of 100,200 is:200
Note:
-----
Lambda Function internally returns expression value and we are not required to write return
statement explicitly.
Note:
-----
Sometimes we can pass function as argument to another function.In such cases lambda
functions are best choice.
We can use lambda functions very commonly with filter(),map() and reduce() functions,
because these functions expect function as argument.
Filter() Function:
------------------
We can use filter() function to filter values from the given sequence based on some
comdition.
filter(function,sequence)
Where Function Argument is responsible to perform conditional check sequence can be List
OR Tuple OR String.
Q) Program to filter only Even Numbers from the List by using filter() Function?
---------------------------------------------------------------------------------
map()Function:
--------------
-> For every element present in the given sequence,apply some functionality and generate
new element with the required modification.For this requirement we should go for map()
function.
-> Eg:For every element present in the list perform double and generate new list of doubles.
Syntax:
-------
map(function,sequence)
-> The function can be applied on each element of sequence and generates new sequence.
Without Lambda
--------------------
1) l=[1,2,3,4,5]
2) def doublelt(x):
3) return 2*x
4) l1=list(map(doublelt,l))
5) print(l1) #[2,4,6,8,10]
With Lambda
------------
1) l=[1,2,3,4,5]
2) l1=list(map(lambda x:2*x,l))
3) print(l1) #[2,4,6,8,10]
Eg 2:
-----
To find square of given numbers
1) l=[1,2,3,4,5]
2) l1==list(map(lambda x:x*x,l))
3) print(l1) #[1,4,9,16,25]
We can apply map() function on multiple lists also.But make sure all list should have same
length.
Syntax:
-------
map(lambda x,y:x*y,l1,l2))
x is from l1 and y is from l2
1) l1=[1,2,3,4]
2) l2=[2,3,4,5]
3) l3=list(map(lambda x,y:x*y,l1,l2))
4) print(l3) #[2,6,12,20]
reduce()Function:
-----------------
- reduce()function reduces sequences of elements into a single element by applying the
specified function.
- reduce(function,sequence)
- reduce() function present in functools module and hence we should write import statement.
Eg:
---
1) result=reduce(lambda x,y:x*y,l)
2) print(result) #12000000
Eg:
---
1) from functools import*
2) result=reduce(lambda x,y:x+y,range(1,101))
3) print(result) #5050
Everything is an Object:
------------------------
- In Python every thing is treated as object.
- Even functions also internally treated as objects only.
1) def f1():
2) print("Hello")
3) print(f1)
4) print(id(f1))
Output:
-------
<function f1 at 0x00419618>
4298264
Function Aliasing:
------------------
For the existing function we can give another name,which is nothing but function aliasing.
1) def wish(name):
2) print("Good Morning:",name)
3)
4) greeting=wish
5) print(id(wish))
6) print(id(greeting))
7)
8) greeting('Durga')
9) wish('Durga')
Output:
------
4429336
4429336
Good Morning:Durga
Good Morning:Durga
Note:
----
- In the above example only one functional is available but we can call that function by using
either wish name or greeting name.
- If we delete one name still we can access that function by using alias name.
1) def wish(name):
2) print("Good Morning:",name)
3)
4) greeting=wish
5)
6) greeting('Durga')
7) wish('Durga')
8)
9) del wish
10) #wish('Durga')->NameError: name'wish'is not defined
11) greeting('pavan')
Output:
-------
Good Morning:Durga
Good Morning:Durga
Good Morning:pavan
Nested Functions:
---------------------
We can declare a function inside another function,such type of functions are called Nested
functions.
def f1():
def inner(a,b):
print("The sum=",a+b)
print("The Average=",(a+b)/2)
print()
inner(10,20)
inner(20,30)
inner(40,50)
inner(100,200)
f1()
eg:2
-----
1) def outer():
2) print("outer function started")
3) def inner():
4) print("inner function execution")
5) print("outer function calling inner function")
6) inner()
7) outer()
8) #inner()->NameError:name'inner' is not defined
Output:
-------
outer function started
outer function calling inner function
inner function execution
In the above example inner() function is local to outer() function and hence it is not possible
to call directly from outside of outer()function.
Note:
-----
A function can return another function.
1) def outer():
2) print("outer function started")
3) def inner():
4) print("inner function execution")
5) print("outer function returning inner function")
6) return inner
7) f1=outer()
8) f1()
9) f1()
10) f1()
Output:
-------
outer function started
outer function returning inner function
inner function execution
inner function execution
inner function execution
f1=outer
f1=outer()
- In the first case for the outer() function we are providing another name f1 (function
aliasing).
- But in the second case we calling outer() function,which returns inner function.For that
inner function() we are providing another name f1
Note:
----
We can pass function as argument to another function
Eg:
---
filter(function,sequence)
map(function,sequence)
reduce(function,sequence)
Decorators:
------------
Bride===>Beautiparlour...==>Heroine
def decor(func):
def inner(name):
if name=='sunny':
print("Hello sunny bad moring..")
else:
func(name)
return inner
@decor
def wish(name):
print("Hello",name,"Good Morning")
wish("Naresh")
wish("Ravi")
wish("Sunny")
eg:2
def decor(func):
def inner(name):
if name=='sunny':
print("Hello sunny bad moring..")
else:
func(name)
return inner
def wish(name):
print("Hello",name,"Good Morning")
decorfunction=decor(wish)
wish("Sunny")
decorfunction("Sunny")
wish("NARESH")
decorfunction("NARESH")
EG:3
def smartdivision(func):
def inner(a,b):
if b==0:
print("Hello stupid..How can divide with zero")
else:
return func(a,b)
return inner
@smartdivision
def division(a,b):
retun a/b
print(division(10,2))
print(division(10,5))
print(division(10,0))
---------------------------------------------------------------------------------------------------------------------------
----------
MODULES
-------
- A group of functions, variables and classes saved to a file, which is nothing but module.
- Every python file(.py) acts as a module.
durgamath.py
-------------
1) x=888
2)
3) def add(a,b):
4) print("The Sum:",a+b)
5)
6) def product(a,b):
7) print("The product:",a*b)
test.py:
--------
1) import durgamath
2) print(durgamath.x)
3) durgamath.add(10,20)
4) durgamath.product(10,20)
Output
------
888
The Sum: 30
The Product:200
Note:
----
Whenever we are using a module in our program,for that module compiled file will be
generated and stored in the hard disk permanently.
test.py:
-------
1) import durgamath as m
2) print(m.x)
3) m.add(10,20)
4) m.product(10,20)
from...import:
--------------
We can import particular members of module by using from...import.
The main advantage of this is we can access members directly without using module name.
test.py:
--------
1) from durgamath import*
2) print(x)
3) add(10,20)
4) product(10,20)
Member Aliasing:
----------------
1) from durgamath import x as y, add as sum
2) print(y)
3) sum(10,20)
Once we defined as alias name,we should use alias name only and we should not use
original name
Reloading a Module:
-------------------
By default module will be loaded only once eventhough we are importing multiple times.
module1.py:
----------
print("This is from module1")
test.py
--------
1) import module1
2) import module1
3) import module1
4) import module1
5) print("This is test module")
Output
------
This is from module1
This is test module
- In the above program test module will be loaded only once eventhough we are importing
multiple times.
- The problem in this approach is after loading a module if it is updated outside then updated
version of module1 is not available to our program.
- We can solve this problem by reloading module explicitly based on our requirement.
- We can reload by using reload() function of imp module.
1) import imp
2) imp.reload(module1)
test.py:
--------
1) import module1
2) import module1
3) from imp import reload
4) reload(module1)
5) reload(module1)
6) reload(module1)
7) print("This is test module")
In the above program module1 will be loaded 4 times in that 1 time by default and 3 times
explicity. In this case output is
The main advantage of explicit module reloading is we can ensure that updated version is
always available to our program.
Another example:
module1.py:
----------
1.print("This is from module1")
test.py:
-------
import time
from imp import reload
import module1
print("profram enter into sleeping state")
time.sleep(30)
reload(module1)
print("program entering into again sleeping state")
reload(module1)
print("this is the last line")
Eg 1:test.py
------------
1) x=10
2) y=20
3) def f1()
4) print("hello")
5) print(dir()) #To print all members of specified module
Eg 1:test.py
------------
1) x=10
2) y=20
3) def f1():
4) print("Hello")
5) print(dir()) #To print all members of current module
Output
------
['_annotations_','_builtins_','_cached_','_doc_','file_','_loader_','_name_','package_','_spec_','
f1','x','y']
Eg 2:
----
To display members of particular module
durgamath.py:
--------------
1) x=888
2)
3) def add(a,b)
4) print("The sum:",a+b)
5)
6) def product(a,b):
7) print("The product:",a*b)
test.py:
--------
1) import durgamath
2) print(dir(durgamath))
output
-------
['_builtins_','_cached_','_doc_','_file_','_loader_','_name_','_package_','_spec_','add','product'
,'x']
Note:
-----
For every module at the time of execution python interpreter will add some special
properties automatically for internal use.
Eg:
---
_builtins_,_cached_,_doc_,_file_,_loader_,_name_,_package_,_spec_
Based on our requirement we can access these properties also in our program.
Eg:
---
test.py
1)print(_builtins_)
2)print(_cached_)
3)print(_doc_)
4)print(_file_)
5)print(_loader_)
6)print(_name_)
7)print(_package_)
8)print(_spec_)
Output
-------
<module'builtins'(built-in)>
None
None
test.py
-------
Demo program:
-------------
module1.py:
-----------
1) def f1():
2) if_name_=='_main_':
3) print("The code executed as a program")
4) else:
5) print("The code executed as a module from some other program")
6) f1()
test.py:
--------
1) import module1
2) module1.f1()
D:\Python_classes>py module1.py
The code executed as a program
D:\Python_classes>py test.py
The code executed as a module from some other program
The code executed as a module from some other program
Output
-------
2.0
11
10
10.6
10.6
Note:
-----
We can find help for any module by using help() function
Eg:
---
import math
help(math)
1) random()Function:
--------------------
This function always generate some float value between 0 and 1( not inclusive)
0<x<1
1) from random import*
2) for i in range(10):
3) print(random())
Output
------
0.4572685609302056
0.6584325233197768
0.15444034016553587
0.18351427005232201
0.1330257265904884
0.9291139798071045
0.6586741197891783
0.8901649834019002
0.25540891083913053
0.7290504335962871
2) randint() Function:
---------------------
To generate random integer betweeen two given numbers(inclusive)
3)uniform()Function:
---------------------
It returns random float values between 2 given numbers(not inclusive)
Output:
-------
9.578477968323773
7.7350642246780374
2.0572938669434535
1.0902143578722594
8.41020155782424
2.940478753853089
9.726156649079659
2.222538546560088
9.940249578591855
4.218384799153155
4) randrange([start],stop,[step])
---------------------------------
- Returns a random number from range
- start <=x<stop
- start argument is optional and default value is 0
- step argument is optional and default value is 1
Output:
-------
2
2
8
10
3
5
9
1
6
3
Output:
--------
1
3
9
5
7
1
1
1
7
3
5) choice() Function:
----------------------
- It wont't return random number.
- It will return a random object from the given list or tuple.
1) from random import*
2) list=["Sunny","Bunny","chinny","vinny","pinny"]
3) for i in range(10):
4) print(choice(list))
Output:
-------
Bunny
pinny
Bunny
Sunny
Bunny
pinny
pinny
vinny
Bunny
SunnyS