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

Python 6

Uploaded by

mamidigunna765
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Python 6

Uploaded by

mamidigunna765
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 141

types of applications in real time:

==========================

in real-time,we will have the following applications:


========================================

1.stand-alone application/desktop application:


====================================

if a application does not require any internet to access and

does not require any server to run the application,then the

application is termed as "stand-alone application"

example: clock,calcuator,billing software,...…..

note:

the main drawback of the stand-alone application is "data

sharing is not available"

2.web application:
==============

if a application does require internet to access and

does require server to run the application,then the

application is termed as "web application"

example: gmail,college websites,...……..

3.enterprise application:
====================

enterprise application is a "Web application"

it is also require "both internet to access and server to run"

enterprise application is also called as "business specific"

application

in enterprise application,we will have server to server

communication

4.mobile application:
================

these application can run in the mobiles and these applications

may be stand-alone,web,enterprise,...…..

python:
======

what is python?:
=============

python is a "high-level,programming,object-oriented,stongly-

typed,dynamic typed language"

in computers,we will have three types of languages:


========================================

1.high-level language:
=================

high-level language means "this language will understand and

used by the programmers or developers to write

program/code/script"

example: c,c++,java,python,js,php,...………….

program ===>set of machine excutable statements/instructions

2.assembly language:
=================

3.low-level/binary language/machine language:


=====================================

this language will understand only by the "machine"

this language will also called as "low-level/machine/binary"

this language will completely use "0's and 1's"

when any programmer or developer will write any code,then

they need to convert the given code into binary, to make

machine understand the programmer or developer written code

in-order to convert any code into binary,we will use language

translators

language translator is a software and it is used to convert the

given code into binary code

in general,we will have the following language translators:


=============================================
1.compiler

2.assembler

3.interpreter

complier:
=======

compiler is a software and it is used to convert the given code

into binary

compiler will translates "the given whole program at a time into

binary"

the translation process of the compiler is known as

"compilation"

the following languages uses the "compiler" as translator:


============================================

1.c

2.c++

3.java

4.python

5.typescript...……………….

for example:
==========

sample.c ====>compiler ====>sample.obj (object code)

sample.java ===>compiler ===> sample.class(byte code)

sample.py ====>python compiler ===>sample.pyc(byte code)

object code is a output of the compiler,when we given any

program/code

in the case of the complier


=====================

===>compiler performance is very high when we compare with

interpreter(because compiler translates whole code at

a time)

===>with help of compiled code, we can not able to perform


debugging very easily(de-bugging means finding and

rectifying the bug from the code),bug means error

interpreter:
=========

interpreter is a software and it is used to convert the given

code into binary

interpreter will translates "the given whole program in a line by

line into binary"

the translation process of the interpreter is known as

"interpretation"

the following languages uses the "interpreter" as translator:


==============================================

1.java

2.python

3.javascript

4.sql...……………….

for example:
==========

sample.java ===>compiler ===> sample.class(byte code) ===>

JVM(interpreter) ====>sample.exe

sample.py ====>python compiler ===>sample.pyc(byte code)

===>PVM (interpreter)===>sample.exe

in the case of the interpreter


======================

===> interpreter performance is very poor when we compare

with compiler(because interpreter translates line by line)

===>with help of interpretd code, we can able to perform

debugging very easily

generally all "programming languages" uses "compiler" as

language transalator,when we say a language is "programming


language and its translator is "compiler" (because programming

languages code will be more in general)

generally all "scripting languages" uses "interpreter" as

language transalator,when we say a language is "scripting

language and its translator is "interpreter"(because any code

we write using scripting language and it will be very less)

object-oriented:
============

object-oritented is a "programming paradigm(model)"

the programming paradigm tells that "how we can write the

program or structure/approach of the programming style"

when we say any language is "object-oriented",it will follows

the following concepts:


================================================

1.classes and objects

2.inheritance

3.data abstraction and encapsulation

4.polymorphism

the example for object-oriented,those are

c++,java,python,javascript,...………………….

note:

python is multi/poly-programming paradigm language(it will

also follows function-oriented)

dynamic-typed:
============

when we want to store any data in the python variable, we no

need to specify the data type of the variable,python will

automatically become that type based on the given value.

if we need to specify the any data type to the variable,then the

language is called as "static typed language"

example for dynamic typed: python,javascript,ruby,...…….


example for static typed: c,c++,java

note:
====

in python,the data type of the variable will known at run-time

only

strongly-typed:
============

in python,when we are performing any operation on operends

(on which we will perform operation),the operends must be

same data type,otherwise python will raise an error

in strongly typed langauges,when we will perform any

operation on opereands,operends must be similar type

if any languages,to perform any operation on operends and

operends need not to be similar type,then the language is

loosly typed language

example for strongly typed is python

example for loosly typed is javascript/java

tools and software need to installed:


============================

1.python( download url: https://www.python.org/downloads/)

2.anaconda navigator(spyder and jupyter notebook)


[ url: https://www.anaconda.com/download]

3.vs code editor

why python?
==========

1.python syntax is very simple unserstand

2.python is a platform independent language(because when

we write the python program,first we will give the python

program to python compiler,the python compiler will generate

the byte code,this byte code will run in the any platform(any

operating system))
sample.py ===>compiler ==>byte code ===>PVM

3.python will have big community and using this community

we will get vast update or improvements in the python

4.python is having rich set of packages/libraries like java

5.python is used in the following all domains:


====================================

1.application development

2.testing

3.data science

4.data analytics

5.data engineering

6.cloud and devops

7.Artificial intelligence(ML,DL,NLP)

8.gaming development

9.IOT

10.networking...……………..

python language fundamentals(core python):


===================================

in python we will have the following language fundamentals:


===============================================

1.python character set:


==================

in python,we will have the following characters:


=====================================

1.alphabets ===>

upper-case(capital) ==>A,B,C,D,...Z

lower-case(Small)===>a,b,c,d...z

2.digits ===>0,1,2,3,4,5,6,7,8,9

3.special symbols/chracters===>~,!,@,#,$,%,^,&,*,(,),[,],|,{,},:,,",',...

2.keywords are reserved words:


=========================
keywords or reserved words are "pre-defined words" of

the language or these words are given by the language.

these words are used in the program,to perform a specific

action.

in python,we will have the following keywords:


====================================

for,while

break,continue

if,else,elif,match

case,True,False,

or,and,not

in,is,class,pass,return,def

try,except,finally,raise,import,from,as,with,assert,yield……………..

3.comments:
==========

comments are used in the code "to describe the line of the code

or to give the descrption of the code"

comments are written in "general language"

comments will ignore by the compiler or interpreter

by adding comments,will never give any effect to the code

comments will write only the for sake "readability" of the code

in python,we will have two types of comments:


====================================

1.single line comments:


==================

to write the single line comments,in python we will use a

symbol called "#"

syntax:
======

#write the comments here

example:
=======
#program for adding two numbers

2.multi-line comments:
==================

when we want to write the multi-line comments,in python we

will use """ """ (triple quotes)

syntax:
======

"""

write the comments here

"""

example:
=======
"""
program for adding two numbers

"""

4.identifiers:
==========

identifier means "any name in the program"

the identifier name may be "variable name/class name/function

name/list name/tuple name/set name/dictionary name/……."

in python,to create any identifier,we will use the following rules:


=================================================

1.any identifier name must start with "any alphabet or

underscore"

2.any identifier name must have the following characters only:


================================================

1.all digits(0,1,2,3,4,5,6,7,8,9)

2.all alphabets(a-z/A-Z)

3.only one special symbol(_)

3.identifer name may be "alphanumeric(the name may be

contain both alphabets and digits)

4.identifier name never has white spaces/spaces

5.identifier name length may be any length,but use less length

6.identifier name never be reserved word name or keyword


name

example:
========

abc_(valid)

_abc(valid)

_123(valid)

_12abc$(invalid)

1abc(invalid)

#abc(valid)

5.variables:
=========

variable is a container and which is uses to hold a value in the

program

the value of the variable can be changes or may be changes

throughout the program

we can able to change the value of the variable in python

program

variable often called as "named memory location"

in order to create the variable,in python we will use the

following syntax:
===============================================

variable_name=value

example:
=======

a=10

here "10" is called value /literal

python litreals:
============

literal means "values which are stored in the variable"

in python,we will have the following litreals:


==================================

1.numeric litreals:
===============

integer(1,1234,-45,-6789,....)

real/floating point numbers(1.234,-5.678,...…)

complex number(10+5j,10-6j,-9j,...…..)

2.boolean litreals:
==============

these are either True or False

in python, True in numeric is "1"

in python, False in numeric is "0"

3.chracter literal/string litreals:


========================

in python,character/string literals can be stored in

"single/double/triple quotes"

example:

"hello"

'hello'

""" hello""" or '''hello'''

4.list literal ===>it is used to list of numbers/chracters/any

type

example: [1,2,3,4,"hello",.....]

5.tuple literal ==>it is used to list of numbers/chracters/any

type

example: (1,2,3,4,5...….)

6.dictionary literals ==>group of data ,where data is stored

in the form of key and value pairs

example: {key1:val1,key2:val2,...…...}

7.set literal ===>it will store the data and all data in the set are

unique.

example: {1,2,3,4,5,.........}

8.None as literal ===>it represents no value/empty value


example: a=None

9.range() as literal,

10.binary literal

11.octal literal

12.hexadecimal litreal...………………

python input and output statements:


=============================

in python,we will take any input from the user,with help

of a function called "input()"

syntax:
======

variable_name=input("enter the data for variable_name")

when we got any data from the "input()" function in python,

the data will always in the format of "string" only

when we give the data like,

number ===>input() ===>String

string ====>input() ====>string

any other data ===>input()====>string

due this reason,when we are working with input() function data,

we will employ the "type conversion or type casting"

type conversion means "conveting the given data type into

another type"

type conversion is also two types:


==========================

1.implicit type conversion or type casting:


=================================

this type conversion will perform by the machine itself or

this type conversion will not perform by the programmer or

developer

2.explicit type conversion or type casting


================================
this type conversion will not perform by the machine itself or

this type conversion will perform by the programmer or

developer

to convert the given string data into integer data,in python

we will use "int()" function

to convert the given string data into float/real number,in

python we will use "float()" function

to convert the given string data into complex number,in python

we will use "complex()" function

to convert the given integer data into string data,in python

we will use "str()" function

to convert the given float/real number data into string data,in

python we will use "str()" function

to convert the given complex number into string data, in

python we will use "str()" function

to convert the given integer data into float/real number

data, we will use "float()" function

to convert the given float/real number to integer number in

python, we will use "int()" function

to convert the given string data into Boolean data, in python we

will use "bool()"

to convert the given integer data into Boolean data, in python

we will use "bool()"

to convert the given float/real number into Boolean data,in

python we will use bool()

to convert the given complex number into Boolean data,in

python we will use "bool()" function

to convert integer data into complex number,we will use

complex() function in python

to convert the float/real number into complex number,we will


use "complex()" function in python

we can not convert the complex number into integer and float/

real number

from to function
===== === =======

integer complex complex()

float complex complex()

complex integer we can not convert

complex float we can not convert

string complex complex()

complex string str()

string integer int()

string float float()

string Boolean bool()

integer Boolean bool()

float Boolean bool()

Boolean integer int()

Boolean float float()

Boolean complex complex()

note:
====

in genereal,

any data except [empty string,None,0],all are True in Boolean

zero/empty string/None, is always False

in numeric,

True ===>1

False ===>0

when we are performing any operation on Boolean data,

in python True(become 1) and false (become 0)

for example:
10+True ==>11

10-False ===>10

in python,to display any output of the python program using

a function called "print()"

syntax:
======

print("control_string/data string",sep=" ",end=" ")

programs on print() function and input() function:


=======================================

1.write a python program to display the "hello world"


=========================================

code:
====

"""
author:Ram
program for display the message called "hello world"
"""
print('hello world')
print("hello world")
print('''hello world''')

note:
====

in python,by default print() will display result in the new line

2.write a python program to display are print() functions data in

the same line:


=================================================

code:
====

"""
author:Ram
program for display the message called "hello world"
"""
print('hello world',end=",")
print("hello world",end=",")
print('''hello world''',end=",")

3.write a python program to display the different datatypes

data using print() function:


=================================================
"""
author:Ram
program to display the different types of the
data using print()
"""
a=10 #integer object/value
b=1.234 #float object
c="hello" #string object
b1=True #boolean object
c1=10+5j#complex object
print(a)
print(b)
print(c)
print(b1)
print(c1)
print(a,b,c,b1,c1,sep=",")
print(a,b,c,sep=",")

note:
=====

if we say "10" is integer object and its class is "int" class

if we say "1.234" is float object and its class is "float" class

if we say "true/false is Boolean object and its class is "bool"

class

it we say "hello" is string object and its class is "str"

in python, when we want to check any object type,we will use

a function called "type()"

in python,if we want to check a object is related to a class or

not,we will use a function called "isinstance()"

4.write a python program,to find the type of the each object

of the variable:
===============================================

note:
====

when we want to find the type of the object of the any variable

,in python we will use a function called "type()"

example:
=======
"""
author:Ram
program to find the type of object of the variable
"""
a=10#integer object
print(type(a))
b=1.234#float object
print(type(b))
c=True#boolean object
print(type(c))
d=10+5j#complex object
print(type(d))
e="hello" #string object
print(type(e))

5.write a python program to demonstrate arithmetic operators:


=================================================

code:
====

"""
author:Ram
program for demonstrate airthmetic operators
"""
#taking the values from the user
a=int(input("enter the value for a:"))#10
b=int(input("enter the value for b:"))#20
print("the sum of a and b is:",a+b)#30
print("the subtraction of a and b is:",a-b)#-10
print("the product of a and b is:",a*b)#200
print("the division of a and b is:",a/b)#0.5
print("the floor division of a and b is:",a//b)#0
print("the modulo diviison of a and b is:",a%b)#10
print("the power/exponenent of a and b is",a**b)#

6.write a python program to demonstrate relational operators:


================================================

code:
=====

"""
author:ram
python program to demonstrate relational operators
"""
a=int(input("enter the number for a:"))#10
b=int(input("enter the number for b:"))#20
print("a>b:",a>b)#False
print("a<b:",a<b)#True
print("a>=b:",a>=b)#False
print("a<=b:",a<=b)#True
print("a==b:",a==b)#False
print("a!=b:",a!=b)#True

7.write a python program to demonstrate logical operators:


==============================================

code:
====

"""
author:ram
python program to demonstrate logical operators
"""
a=int(input("enter the number for a:"))#10
b=int(input("enter the number for b:"))#20
#or
print("(a>b) or (a<b):",(a>b) or (a<b))#True
#and
print("(a>b) and (a<b):",(a>b) and (a<b))#False
#not
print("not(a>b):",not(a>b))#True

8.write a python program to demonstrate the "Assignment

operators"
=================================================

"""
author:Ram
python program to demonstrate the "Assignment

operators"

"""
a=10
print("the value of a is:",a)#10
a+=10#a=a+10
print("the value of a is:",a)#20
a-=10
print("the value of a is:",a)#10
a*=10
print("the value of a is:",a)#100
a/=10
print("the value of a is:",a)#10.0

9.write a python program to demonstrate bitwise operators:


===============================================

code:
====

"""author:Ram
python program to demonstrate bitwise operators
"""
a=10
b=20
print("bitwise or(a|b):",a|b)#30
print("bitwise and(a&b):",a&b)#0
print("bitwise exclusive or(a^b):",a^b)#30
print("bitwise left shift(a<<2):",a<<2)#40
print("bitwise right shift(a>>2):",a>>2)#2
print("bitwise one's complement':",~a)#-11

10.write a python program,to demonstrate membership operators:


=================================================
code:
====
"""
author:Ram
python program,
to demonstrate membership operators"""
x="i am from india"
print("am" in x)#True
print("AM" in x)#False
print(" " in x)#True
print("india" not in x)#False
print("India" not in x)#True
print("from" in x)#True
print("1" in "123")

11.write a python to find the memory address of the given object:


================================================

note:
====

in python, id() function will return "memory address of the

object at memory"

code:
====
"""
author:Ram
a python to find the memory address
of the given object
"""
a=10
print(id(a))
print(id(10))
b=1.234
print(id(b))
print(id(1.234))
c=a
print(id(c))
h="hello"
print(id(h))

12.write a python program to demonstrate the identity operators:


=================================================

code:
=====

"""
author:Ram
program to demonstrate identity operators in python
"""
a=10
b=20
c=10
print(a is b)
print(a is c)
print(a is not b)
print(c is not b)
print(a is c or a is b)
print(a is c and a is b)

13.write a python program to demonstrate walrus operator in

python:
=================================================

code:
====

"""
author:Ram
program to demonstarate warlus operator
"""
a=10
if (a:=a+10)>=20:
print("a value more than 20 or equal to 20")
else:
print("a value less than 20")
print("the value of a is:",a)

6.operators:
==========

operator means "symbol" and which is used to perform a

specific operation/task in the program

operand means "on which we will perform operation"

expression means "combination of both operends and

operator"

for example,

a=10,b=20

c=a+b <== expression

here a,b are operends and + is operator

in python,we will have the following operators:


====================================

1.airthmetic operator(+,-,*,/,//,%,**):
============================

to perform any arithmetic operations, we will use the following

arithmetic operators in python:


================================================

+ (meaning: addtion):
================

a=10,b=20 ===>a+b===>30

-(meaning: subtraction):
==================

a=10,b=50 ===>b-a ==>40

*(meaning: multiplication)
====================

a=10,b=20 ===>a*b ==>200


/(meaning: real division):
====================

a=10,b=20 ===>a/b ==>0.5

a=20,b=10 ==>a/b ==>2.0

note:
====

when we apply "/" on the given operends,the result is always

real number

//(meaning: floor division(result is always integer quotient):


==============================================

a=10,b=20 ==>10//20 ==>0

a=20,b=4 ==>a//b ==>5

a=36,b=5 ==>a//b===>7

%(modulo division(it will give remainder as the result):


==========================================

a=10,b=20 ===> a%b ==>10

a=20,b=10 ===>a%b ==>0

a=19,b=7 ===>a%b ===>5

a=21,b=12 ==>a%b ===>9

a=25,b=1000===>a%b ==>25

note:
====

if n1%n2(n1<n2),then the remainder is "n1"

if n1%n2(n1>n2),then the remainder is "Actual remainder"

**(exponent):
==========

10**3 ===>1000

34**3 ===>39304

1**3===>1

2.relational operators/comparision operators(>,<,>=,<=,==,!=):


================================================

these operators are used to compare any two values

these operators will give result either True or False


example:
=======

a=10,b=20

a>b ===>False

a<b ===>True

a>=b( greter than or equal to) ===>False

a<=b(less than or equal to) ===>True

a==b (equal to) ===>False

a!=b (not equal to) ===>True

3.logical operator(or,and,not):
=======================

these operators are used to compare any two conditions

these operators will give the Boolean values as result

in this,we will have the following:


==========================

logical or:
========

rule:
====

in the case of the logical or,if any one condition is true,then

the entire result/output is "true"

example:
=======

a=10,b=20

(a>b) or (a<b) ===>True

(a<b) or (a>b) ===>True

(a>b) or (b>a) ===>True

(a<a) or (b<b) ===>False

note:
====

while working with logical or,if we have multiple conditions,

if any one condition is true,then the logical or never check the

remaining conditions,this behaviour is known "short-circuit"


behaviour

2.logical and:
==========

rule:
====

in the case of the logical and,if any one condition is false,then

the entire result/output is "false"

example:
=======

a=10,b=20

(a>b) and (a<b) ===>False

(a<b) and (a>b) ===>False

(a>b) and (b>a) ===>False

(a<a) and (b<b) ===>False

(a<b) and (b>a) ===>True

note:
====

while working with logical or,if we have multiple conditions,

if any one condition is true,then the logical or never check the

remaining conditions,this behaviour is known "short-circuit"

behaviour

3.logical not:
==========

this operator will change the result which is True into False

or False into True

example:
=======

a=10,b=20

not(a>b) ===>True

not(a<b) ===>False
4.assignment operator(=):
====================

to assign the value to the any variable in python, we will use

the assignment operator

example:

a=10 <=== the value a is 10

a=1.234 <== the value of a is 1.234

using "assignment operator",in python we can do

compound operations,those are like:


=================================================
a=10

a+=10===>a=a+10 ==>a=20

a-=10 ===>a=a-10 ===>a=10

a*=10 ===>a=a*10 ==>a=100

a/=10 ==>a=a/10 ===>a=10.0

5.bitwise operator(|,&,^,<<,>>,~):
==========================

these operators will be performed on the binary data

of the given data

when we give the data to bitwise operator,it will convert the

given data into binary,on that it will perform the bitwise

operation and again it will give result in normal

number(Decimal number)

in python,we will have the following bitwise operators:


==========================================

1.bitwise or:
==========
symbol: |(pipe)

rule: in the case of bitwise or,if any one input is "1",then the

entire result is "1"

example:
=======

a=10 ===>01010
b=20 ===>10100
==============
a|b ===> 11110<=== 30

a=45===>101101

b=60===>111100
===============
111101<===61

2.bitwise and:
===========

symbol: &(ampracend)

rule: in the case of bitwise and,if any one input is "0",then the

entire result is "0"

example:
=======

a=10 ===>01010

b=20 ===>10100
==============
a|b ===> 00000<=== 0

a=98 ===> 1100010


b=78====>1001110
=================
a&b===> 1000010==>66

3.bitwise exclusive or:


==================

symbol: ^(caret)

rule: in the case of bitwise exclusive or,if both inputs are same

,then the result is "0",otherwise 1

example:
=======

a=10 ===>01010

b=20 ===>10100
==============
a^b ===> 11110<=== 30

a=100 ===>01100100

b=200===>11001000
====================
a^b ====>10101100 <==172

4.bitwise left shift:


===============

symbol: <<

formula: n<<s = n* 2 power s

example:
========

a=20

a<<4 ===>a* 2 power 4 ===>20 *16 ===>320

5.bitwise right shift:


================

symbol: >>

formula: n>>s = n/ 2 power s

example:
========

a=20

a<<4 ===>a/ 2 power 4 ===>20 /16 ===>1

6.bitwise one's complement:


=======================

symbol: ~(tlide)

formula: ~n=-(n+1)

example:
========

a=10

~a=-(a+1)=-11

a=-19

~a=-(-19+1)=18

6.membership operator(in,not in):


==========================

these operators are used in python "to check the given value

is present in the iterables are not"

in python,iterable means(which can refer more than one value)

in python,iterables are "list,tuple,set,range(),string,dictionary"


these operators are used only with "iterables"

these operators will return "Boolean value as result"

in this operators,we will have the following:


==================================

1.in(it is going to check value is there or not)

2.not in(it is going to check value is not there or not)

example:
=======

result="I am from india"

"am" in result ===>True

" " in result ===>True

"from" not in result ===>False

"I" in result ===>True

"From" in result ===>False

7.identity operator(is ,is not):


=======================

this operator is used in python, "to compare any two objects

memory locations are same or not"

this operator will return result as Boolean value(True or False)

this operator will have the following:


============================

1.is(it will both objects are reside at same memory location)

2.is not(it will check both objects are not at same memory

location)

example:
=======

x=10

y=20

z=10

a=y

x is y ===>False

x is not y ==>True
x is not a ===>True

y is not z===>True

note:
====

when we create any two variables with same object, then the

both variables will refer same memory location in python, in

python, two similar objects will never have different memory

location

8.conditional operator/tenary operator( exp if cond else exp2):


=================================================

if we want to perform any operation/execute any statement

in python, based on the certain condition, then we will use

conditional or tenary operator

syntax:
======

expression if condition else expression

in the conditional operator,

if the condtition is true,before if will be executed

if the condition is false,after else will be executed

example:
=======

x=10,y=20

print(x) if x>y else print(y) ===>output ==>20

print(y) if x<y else print(x) ===>output===>20

print(x+y) if x!=y else print(y) ===>output ==>30

9.warlus operator(:=):
=================

this operator will be used especially in the the "loops or

conditional statements in python"

symbol:
======

:=
example:
========

x=10

x:=x+1 <=== x=11

x=30

(x:=x+10)>50 ====>False

7.conditional statements:
====================

In python,we will use conditional statements,to execute any

logic based on the certain condition.

in python,we will have the following conditional statements:


===============================================

1.if statement/simple if statement:


===========================

when we have a logic ,that has to execute only when certain

condition is true ,then in python we will use "if or simple if

statement"

syntax for if statement or simple if statement:


====================================

if condition:

here we will write the logic

note:

when we are working with if, the logic under the if will be

executed only when the condition is true, otherwise the logic

what we write under the if will not be executed

when we write the any statement under the if, each statement

will have some space at beginning,this will called as indentation

when we write any number statements in the if as logic,each

statement will have same space, otherwise python will raise

indentation error

the right amount of spaces for indentation is always "4" spaces


syntax:
======

if condition:

#logic

example:
=======

"""
author:ram
if statement
"""
a=10
if a>10:
print("a value is more than 10")
if a<=10:print("a value is less than 10 or equal to 10")

how to create the if is always true in python:


===================================

example:
=======

if True:
#logic

if any data other than false/0/empty string/None

how to create empty if statement in python:


==================================

empty if statement means, if with no logic/no code

to create the empty if statement,we will use a keyword called

"pass"

in python,"pass" is a keyword

pass is going to tell "there is no code/it is a place holder where

it tells no code/logic for if"

example:
=======

"""
author:ram
if statement
"""
a=10
if a>10:#empty if statement
pass
if a<=10:
print(a)
pass
2.if-else statement :
================

in python,if we have two conditions,then in python we will use

if-else statements

when we have if and else statements,

if will be "true part"

else will be "false part"

else is always "counter part of the if"

syntax:
======

if condition:

#logic

else:

#logic

note:
====

in python,

we can write "if", without else statement

we can not write "else", without if statement

example:
=======

"""
author:ram
if-else statement
"""
a=10
b=20
if a>b:print("a>b")
else:print("b>a")
#or
print("a>b") if a>b else print("b>a")

3.else-if ladder:
============

when we have three or more than three conditions,in python we

can use "else-if" ladder

syntax:
======
if condition:

#logic

elif condition:

#logic

elif condition

#logic

.
.
.
else:
#logic

note:
====

else-if ladder should always starts with "if" only

in else-if ladder,we can write only one if and any number of

elif conditions"

in else-if ladder"else" is always optional and if we write else

in the else-if ladder,it will be the last .

suppose we have 10 conditions:


=========================

1-if and 9-elif

or

1-if,8-elif and 1-else

example:
=======

"""
author:Ram
else-if ladder
"""
a=10
b=20
c=30
if a>b and a>c:
print(a)
elif b>c:
print(b)
else:
print(c)

4.nested conditional statements:


==========================

when we write the one conditional statement inside another

conditional statement, then we say it is "nested conditional

statements"

example:
=======

if condition:
if condition:
if condition:

else:

else:
if condition:
#logic

else:

#logic

example:
=======
age=int(input("Enter the age:"))
if age>=21:
if age>=21 and age<=30:
print("enjoy the bachelor life")
elif age>=31 and age<=40:
print("good age,check with experts before marriage")
elif age>=41 and age<=60:
print("already you are in heaven,enjoy the remaing life")
elif age>=61:
print("RIP!")
else:
print("this is not a video game!")

8.looping statements/iterative statements:


=================================

these statements are used in python, "to execute any logic for

"n" number of times until the condition become false"

in python, we will have the following iterative/looping

statements:
================================================

1.while loop:
==========

syntax:
======
while condition:

#logic

example:
=======

"""
author:Ram
while loop
"""
a=1# the value of the a is 1
times=0
while a<=10:
print(a)#1 2 3 4 5 6 7 8 9 10
a+=1 #a=11
times+=1
print("the value of a is:",a)
print("the number of times loop is executed:",times)
#output:
#1 2 3 4 5 6 7 8 9 10
#the value of a is:11

example-2:
=========

write a python program to print the even numbers from 1 to 100:


================================================

code:
=====

"""
author:Ram
while loop
"""
start=1
while start<=100:
if start%2==0:
print(start,end=" ")
start+=1

example-3:
=========

print the odd numbers from 100 to 1:


=============================

code:
====

"""
author:Ram
while loop
"""
start=100
while start>=1:
if start%2!=0:
print(start,end=" ")
start-=1

example-4:
========

find the given number factors and print them using python:
==============================================

"""
author:Ram
while loop
"""
num=int(input("enter the number:"))#6
fact=1
while fact<=num:
if num%fact==0:
print(fact,end=" ")#1,2,3,6
fact+=1

infinite loop:
==========

infinite loop means "the condition what we taken for the loop

will never be false"

example:
=======

a=1
while a<=10:
print(a)

2.for loop:
=========

in python, when we want to work with for loop, we always has

to use "iterables" only

(list/tuple/range()/set/string/dictionary....)

syntax:
======

for variable_name in iterable_name:

#logic for for loop

note:
====

in python, when we want to work with any iterable, we will

always use "for" loop

in python, while loop is always created based on the certain


conditions

when we use for loop, the loop termination is always depends

on "length of the given iterable in the for loop"

to work with for loop, we will understand about "range()"

function in python:

range() will give the number from given start to end-1

syntax for range():


==============

range(start,end,step) ===>start to end-1

example:
=======

range(1,10) ===>1,2,3,4,5,6,7,8,9

range(1,21) ====>from 1 to 20

note:
====

in range() function start is optional ,default value for start in

range() is "0"

in range() function step is optional, default value for step in

range() is "1"

example:
=======

range(10) <=== here if we give only one value,then range() assumes it is only end
value

range(10) ===>range(0,10,1)

0,1,2,3,4,5,6,7,8,9

range(1,10,2) ===>1,3,5,7,9

range(1,10,4) ===>1,5,9

range(1,10,6) ===>1,7

range(10,10,4) ==>no value/no result

range(1,10,-4) ===>no value/no result

range() function with for loop:


========================

example-1:
=========

"""
author:Ram
for loop
"""
for i in range(10):#it is always end value
print(i,end=" ")
print()
for i in range(1,10,6):
print(i,end=" ")
print()
for i in range(1,10,4):
print(i,end=" ")
print()
for i in range(1,10,-6):
print(i,end=" ")
print()
for i in range(10,10,6):
print(i,end=" ")

example-2:
=========

"""
author:Ram
for loop
"""
for i in range(1,10,0):
print(i,end=" ")
print()
"""
step value never be zero

step value either positive or negative

"""

example-3:
=========

range() function with negative step

code:
====

"""
author:Ram
for loop
"""
for i in range(10,0,-3):
print(i,end=" ")
print()
for i in range(99,0,-2):
print(i,end=" ")
"""
when we take negative step in range()

start should always greter than end value


"""

what is type of the range() in python:


==============================

when we create the any range in python,it will having a type

called <class 'range'> and even it also an object called "range"

object, it's class is "range"

example:
=======

"""
author:Ram
range type
"""
x=range(1,10)
print(x)
print(type(x))
print(help(range))

indexing and slicing with range() function:


=================================

indexing with range():


=================

in python, we can apply the indexing on range()

in python, we will have two types of indexing:


===================================

1.positive indexing or forward indexing:


================================

this indexing will start from 0 to n-1

where "n" means the number of numbers of the range

this indexing direction is from left to right /start to end

2.negative indexing or backward indexing:


================================

this indexing will start from -1 to -n

where "n" means the number of numbers of the range

this indexing direction is from right to left /end to start

syntax:
======

range_object_name[index]
example:
=======

"""
author: ram
indexing on range()
"""
a=range(10,110,10)
print(a[0])
print(a[7])
print(a[8])
print(a[4])
print(a[2])
print(a[-1])
print(a[-5])
print(a[-10])
print(a[-4])

write a python program print the even index elements from the
range.

code:
====

"""
author: ram
indexing on range()
"""
x=range(10,100,10)
index=0
for i in x:
if index%2==0:
print(i)
index+=1
"""
in python,to find the length of the range,we will
use,len() function,
length of the range=number of numbers in range
"""
index=0
print("length of the x range is:",len(x))
while index<len(x):
if index%2==0:
print(x[index])
index+=1

slicing on range():
==============

slicing may give o or more elements from the range

indexing may give only one element in the range

syntax:
======

range_object_name[start:end:step]

this will always give values from start to end-1


example-1:
=========

"""
author: ram
indexing on range()
"""
x=range(10,110,10)
for i in x[1:4]:
print(i,end=" ")
print()
for i in x[1:]:
print(i,end=" ")
print()
for i in x[:6]:
print(i,end=" ")
print()
for i in x[:]:
print(i,end=" ")
print()
for i in x[1:10:4]:
print(i,end=" ")

example-2:
=========

x=range(10,110,10)
for i in x[-10:]:
print(i,end=" ")
print()
for i in x[-8:-1]:
print(i,end=" ")
print()
for i in x[::3]:
print(i,end=" ")
print()
for i in x[-10::3]:
print(i,end=" ")
print()

example-3:
=========

"""
author: ram
indexing on range()
"""
x=range(10,110,10)
for i in x[-4:-8]:
print(i,end=" ")
print()
for i in x[-4:-8:-1]:
print(i,end=" ")
print()
for i in x[-8:-4:1]:
print(i,end=" ")
print()
for i in x[-10:5]:
print(i,end=" ")
print()

example-4:
=========

"""
author: ram
indexing on range()
"""
x=range(10,110,10)
for i in x[::3]:
print(i,end=" ")
print()
x=range(10,110,10)
for i in x[::4]:
print(i,end=" ")
print()
x=range(10,110,10)
for i in x[::5]:
print(i,end=" ")
print()
x=range(10,110,10)
for i in x[::-1]:
print(i,end=" ")
print()
x=range(10,110,10)
for i in x[::-4]:
print(i,end=" ")
print()

write a python program for the following:


=================================

1.swap the two numbers without using any thrid variable

or temporary variable:
==============================================

code-1:
======

"""
author:ram
swapping of the two numbers
"""
a=int(input("Enter the number for a:"))
b=int(input("Enter the number for b:"))
print("before swapping:")
print(a,b,sep=",")
a,b=b,a
print("after swapping:")
print(a,b,sep=",")

code-2:
======

"""
author:ram
swapping of the two numbers
"""
a=int(input("Enter the number for a:"))
b=int(input("Enter the number for b:"))
print("before swapping:")
print(a,b,sep=",")
#using airthmetic operators
a=a+b
b=a-b
a=a-b
print("after swapping:")
print(a,b,sep=",")

code-3:
======
"""
author:ram
swapping of the two numbers
"""
a=int(input("Enter the number for a:"))
b=int(input("Enter the number for b:"))
print("before swapping:")
print(a,b,sep=",")
#using airthmetic operators
a=a*b
b=a//b
a=a//b
print("after swapping:")
print(a,b,sep=",")

code-4:
======

"""
author:ram
swapping of the two numbers
"""
a=int(input("Enter the number for a:"))
b=int(input("Enter the number for b:"))
print("before swapping:")
print(a,b,sep=",")
#using bitwise operators
a=a^b
b=a^b
a=a^b
print("after swapping:")
print(a,b,sep=",")

2.area of the circle:


===============

code:
=====
"""
author:ram
area of the circle
"""
print("the area of the circle:",(3.14)*(int(input("enter the number:"))**2))
3.simple interest:
=============="""
author:ram
simple interest
"""
p=int(input("enter P:"))
t=int(input("enter T:"))
r=int(input("enter R:"))
print("simple interest:",(p*t*r)//100)

4.maximum of the given three numbers:


================================

code:
====

"""
author:ram
maximum of the given three numbers
"""
num1=int(input("enter Num1:"))
num2=int(input("enter Num2:"))
num3=int(input("enter Num3:"))
if num1>num2 and num1>num3:print("maximum:",num1)
elif num2>num3:print("maximum",num2)
else:print("maximum:",num3)

5.minimum of the given three numbers:


===============================

code:
====
"""
author:ram
minimum of the given three numbers
"""
num1=int(input("enter Num1:"))
num2=int(input("enter Num2:"))
num3=int(input("enter Num3:"))
if num1<num2 and num1<num3:print("minimum:",num1)
elif num2<num3:print("minimum",num2)
else:print("minimum:",num3)

6.average of the given six subjects marks


=================================

code:
====
"""
author:ram
average of the six subjects
"""
sub1=int(input("enter sub1:"))
sub2=int(input("enter sub2:"))
sub3=int(input("enter sub3:"))
sub4=int(input("enter sub4:"))
sub5=int(input("enter sub5:"))
sub6=int(input("enter sub6:"))
print("Average of the six subjects:",(sub1+sub2+sub3+sub4+sub5+sub6)//6)
7.check given number is positive or not
================================
code:
====
"""
author:ram
check given number is positive or not
"""
num=int(input("enter the number:"))
if num>0:print("positive")
elif num<0:print("negative")
else:print("neither positive nor negative")

8.check given number is even or odd


=================================

"""
author:ram
check given number is even or odd
"""
print("Even") if int(input("enter the number:"))%2==0 else print("odd")

9.check given divisible by both 8 and 16 or not


=======================================

"""
author:ram
check given divisible by both 8 and 16 or not
"""
num=int(input("enter the number:"))
print("yes") if num%8==0 and num%16==0 else print("no")

10.print the last digit of the given number:


==================================
"""
author: ram
print the last digit of the given number
"""
print(int(input("enter the number:"))%10)

12.print the digits of the given number:


===============================

example: 123 ===>digts ==>1,2,3

code:
====

"""
author:Ram
print the digits of the given number
"""
#take the number from the user
num=int(input("enter the number:"))#123
#convert the given number into string,using str()
num=str(num)#123
#print the each digit using for loop
for i in num:
print(i)#1 2 3

or
"""
author:Ram
print the digits of the given number
"""
#take the number from the user
num=int(input("enter the number:"))#123
#using while loop
while num!=0:
digit=num%10
print(digit)
num//=10

13.print the number of digits in the given number


=======================================

code:
====
"""
author:Ram
print the number of digits in the given number
"""
#take the number from the user
num=int(input("enter the number:"))#123
count=0
#using while loop
while num!=0:
count+=1#count=count+1
num//=10
print("the number digits in the given number is:",count)

14.print the sum of the digits of the given number:


========================================

example:
=======

123 ===>1+2+3=6

code:
====
"""
author:Ram
print the sum of digits in the given number
"""
#take the number from the user
num=int(input("enter the number:"))#123
sum=0
#using while loop
while num!=0:
digit=num%10
sum+=digit#sum=sum+digit
num//=10
print("the sum of digits in the given number is:",sum)

15.maximum digit in the given number:


===============================

"""
author:Ram
maximum digit in the given number
"""
#take the number from the user
num=int(input("enter the number:"))#123
max=0
#using while loop
while num!=0:
digit=num%10#3,2,1
if max<digit:
max=digit#max=3
num//=10
print("the maximum digit in the given number is:",max)

16.minimum digit in the given number:


===============================

code:
====
"""
author:Ram
maximum digit in the given number
"""
#take the number from the user
num=int(input("enter the number:"))#123
min=9
#using while loop
while num!=0:
digit=num%10#3,2,1
if min>digit:
min=digit#min=1
num//=10
print("the minimum digit in the given number is:",min)

17.product of the digits of the given number:


====================================

code:
====

"""
author:Ram
product of the digits of the given number
"""
#take the number from the user
num=int(input("enter the number:"))#123
product=1
#using while loop
while num!=0:
digit=num%10#3,2,1
product*=digit
num//=10
print("the product of the digits in the given number is:",product)

18.print the even digits in the given number

19.print the odd digits in the given number

20.print the prime digits in the given number

21.print the sum of the even digits in the given number

22.print the sum of the odd digits in the given number

23.print the sum of the prime digits in the given number

24.print the maximum even digit in the given number

25.print the maximum odd digit in the given number

26.print the maximum prime digits in the given number

27.print the minimum even digit in the given number

28.print the minimum odd digit in the given number

29.print the minimum prime digits in the given number

30.print the number of even digits in the given number

31.print the number of odd digits in the given number

32.print the number of prime digits in the given number

33.print the prodcut of even digits in the given number

34.print the product of odd digits in the given number

35.print the product of prime digits in the given number

36.print the average of even digits in the given number

37.print the average of odd digits in the given number

38.print the average of prime digits in the given number

39.print the average of the digits of the given number

40.check the given digits is present in the number or not

41.print the factors of the given number:


================================

code:
====
"""
author:Ram
factors of the given number
"""
#take the number from the user
num=int(input("enter the number:"))#123
fact=1
#using while loop
while fact<num:
if num%fact==0:
print(fact,end=" ")
fact+=1

42.find the maximum factor of the given number:


=======================================

example:
=======

24 ====>1,2,3,4,6,8,12

code:
====
"""
author:Ram
maximum factor of the given number
"""
#take the number from the user
num=int(input("enter the number:"))
fact=1
max=1
#using while loop
while fact<num:
if num%fact==0:
if max<fact:
max=fact
fact+=1
print("the Maximum factor of the given number:",max)

43.find the minimum factors of the given number:


========================================

code:
=====

"""
author:Ram
minimum factor of the given number
"""
#take the number from the user
num=int(input("enter the number:"))
fact=2
min=num
#using while loop
while fact<num:
if num%fact==0:
if min>fact:
min=fact
fact+=1
print("the minimum factor of the given number:",min)

44.find the sum of the factors of the given number:


========================================
example:
=======
6 ===>1+2+3===>6
24 ==>1+2+3+4+6+8+12=36

code:
====

"""
author:Ram
sum of the factors of the given number
"""
#take the number from the user
num=int(input("enter the number:"))
fact=1
sum=0
#using while loop
while fact<num:
if num%fact==0:
sum+=fact
fact+=1
print("the sum of the factors of the given number:",sum)

45.find the common factors of the given two numbers:


===========================================

example:
=======

10 ===>1,2,5,10

20===>1,2,4,5,10,20

ouput: 1,2,5,10

code:
=====
"""
author:Ram
common factors of the given two numbers
"""
#take the numbers from the user
num1=int(input("enter the number 1:"))#70
num2=int(input("enter the number 2:"))#50
fact=1
#take the smallest number
num=num1 if num1<num2 else num2
#using while loop
while fact<=num:
if num1%fact==0 and num2%fact==0:
print(fact)
fact+=1

46.find the gcd or hcf of the given two numbers


======================================

code:
====

"""
author:Ram
common factors of the given two numbers
"""
#take the numbers from the user
num1=int(input("enter the number 1:"))#70
num2=int(input("enter the number 2:"))#50
fact=1
#take the smallest number
num=num1 if num1<num2 else num2
max=0
#using while loop
while fact<=num:
if num1%fact==0 and num2%fact==0:
if max<fact:max=fact
fact+=1
print("HCF/GCD of the given two numbers is:",max)

47.find the lcm of the given two numbers:


=================================

code:
====

"""
author:Ram
LCM of the given two numbers
"""
#take the numbers from the user
num1=int(input("enter the number 1:"))#70
num2=int(input("enter the number 2:"))#50
fact=1
#take the smallest number
num=num1 if num1<num2 else num2
max=0
#using while loop
while fact<=num:
if num1%fact==0 and num2%fact==0:
if max<fact:max=fact
fact+=1
print("LCM of the given two numbers is:",(num1*num2)//max)

48.write a python program find the square root of the given

number without using any built-in function in python:


=================================================

code:
====
"""
author:Ram
square root of the given number
"""
#take the numbers from the user
num1=int(input("enter the number 1:"))
print("square root of the number:",(num1)**(0.5))

49.write a python program find the factorial of the given

number without using any built-in function:


=================================================

code:
====
"""
author:Ram
factorial of the given number
"""
#take the numbers from the user
num=int(input("enter the number:"))
fact=1
if num==0 or num==1:
print("Factorial of the given number:1")
elif num>1:
while num!=0:
fact*=num
num-=1
print("Factorial of the given number:",fact)
elif num<0:
print("given number is invalid")

50.print the following series:


=======================

0 1 1 2 3 5 8 13 ………...<=== fibnocii series

code:
====

"""
author:Ram
fibnocii series
"""
a=0
b=1
count=int(input("how many numbers you want in the fibnocii series:"))
print(a,b,end=" ")
while count!=0:
print(a+b,end=" ")
a,b=b,a+b
count-=1

9.un-conditional statements:
======================
these statemens are used in python to change the "control

flow of the execution" in the program

these statements are also called as "control-flow statements

with no conditions"

in python,we will have the following un-conditional statements:


=================================================

1.break <=== it will stop the execution of the loop pre-maturly

2.continue<=== it will skip/stop executing the current iteration

3.return

both break and continue will used only with loops

return is used only with fucntions

example-1:
=========

"""
author: ram A
break statement
"""
for i in range(1,11):
print(i)
if i==5:
break

a=1
while a<=10:
print(a)
if a==5:
break
a+=1

example-2:
=========

"""
author:ram
continue statement
"""
a=0
while a<=10:
a+=1
if a==5:
continue
print(a)

nested loops:
===========
nested loops means create the one loop inside another loop

in one loop we can any number of nested loops

nested loop using while loop:


=======================

exampel-1:
=========

"""
author: Ram

nested loop with while loop

"""
a=1
b=1
times=0
while a<=10:
while b<=5:
#print(a)#1 1 1 1 1
b+=1
times+=1
a+=1
b=1
print(times)

example-2:
=========

"""
author: Ram

nested loop with while loop

"""
a=1
b=1
k=1
times=0
while a<=10:
while b<=5:
while k<=5:
if k==4:
break
k+=1
times+=1
b+=1
k=1
times+=1
a+=1
b=1
k=1
print(times)

example-3:
=========
"""
author:ram
continue statement
"""
a=1
b=1
c=1
d=1
times=0
while a<=10:
while b<=5:
while c<=10:
while d<=5:
if d==2:
break
times+=1
d+=1
d=1
times+=1
c+=1
b+=1
times+=1
a+=1
times+=1
print(times)#

example-4:
=========

"""
author:ram
continue statement
"""
a=1
b=1
c=1
d=1
times=0
while a<=10:
while b<=5:
while c<=10:
while d<=5:
if d==2:
break
times+=1
d+=1
d=1
times+=1
c+=1
b+=1
times+=1
a+=1
times+=1
b=1
c=1
b=1
print(times)#

example-5:
=========

"""
author:ram
continue statement
"""
a=1
b=1
c=1
d=1
times=0
while a<=10:
while b<=5:
while c<=10:
while d<=5:
if d==2:
break
times+=1
d+=1
d=1
times+=1
c+=1
b+=1
times+=1
c=1
a+=1
times+=1
b=1
c=1
b=1
print(times)#

eample-6:
========

"""
author:ram
continue statement
"""
a=b=c=d=1
times=1
while a<=5:
while b<=10:
while c<=5:
while d<=6:
if d==1:
break
times+=1
if c==2:
break
c+=1
times+=1
if b==3:
break
b+=1
times+=1
a+=1
times+=1
b=c=d=1
print(times)

example-7:
=========

"""
author:ram
continue statement
"""
a=b=c=d=1
times=0
while a<=5:
a+=1
if a==5:
break
else:
while b<=5:
b+=1
if b==3:
break
else:
times+=1
times+=1
print(times)
b=1
#print(times)

write a python program to display numbers which are never

has digit 1 and digit 2 and digit 3 at any position in the

number in between 1 to 100:


=================================================

code:
====

for i in range(1,101):
if "1" not in str(i) and "2" not in str(i) and "3" not in str(i):
print(i,end=" ")

example:
========

i,j,k,count=1,1,1,0
while i<=10:
while j<=10:
while k<=5:
count+=1
k+=1
k=1
j+=1
j,k=1,1
i+=1
print(count)

write a python program to display the number in the reverse


to its original form for the given range ,without using any built-in function:
================================================
example:
========

10 and 20 ===>01,11,21,31,41,51,61,71,81,91,02

code:
====

start=int(input("enter the start:"))#110


end=int(input("enter the end"))#120
if end<start:start,end=end,start
temp=start#110
rev=0
while start<=end:
while start!=0:
digit=start%10#0,1,1
rev=digit+rev*10#0,,111
start//=10#11,1,0
print(rev)#11
rev=0
temp+=1#111
start=temp#111

write the python program to print the following series:


===========================================

1.0,2,4,6,8,10,12,14,...…………….<=== even number series

code:
====

start=0
count=int(input("enter the number values you want in series:"))
while count!=0:
print(start,end=",")#0,2
start+=2#4
count-=1#8
print()
#using for loop
for i in range(0,20,2):
print(i,end=",")

2.10,120,1440,...…………
================================================

code:
====
start=10
count=int(input("enter the number values you want in series:"))
while count!=0:
print(start,end=",")#10,120
start*=12#1440
count-=1#8
print()
#using for loop
start=10
for i in range(1,11):
print(start,end=",")
start*=12

3.1000,100,10,...……………..
=================================================

code:
====

start=1000
count=int(input("enter the number values you want in series:"))#10
while count!=0:
print(start,end=",")#1000,100,10
start//=10#1
count-=1#7
print()

4.0,1,1,2,3,5,8,13,...……………… fibnocii series


=================================================

code:
=====

a,b=0,1
count=int(input("enter the number values you want in series:"))#10
count-=2
print(a,b,end=",")
while count!=0:
print(a+b,end=",")#1,
a,b=b,a+b
count-=1
print()

5.1,4,9,16,25,...……… without using any built-in function and

any * or ** operator:
=================================================

code:
=====

start=1
count=int(input("enter the number values in the series:"))
sum=0
num=1
while count!=0:
while num<=start:
sum+=start
num+=1
print(sum,end=",")
num=1
sum=0
count-=1
start+=1

problems on patterens:
==================

patteren-1:
=========

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

code:
====

"""
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
"""
rows=int(input("enter the number of rows:"))
for i in range(1,rows+1):
for col in range(1,i+1):
print(col,end=" ")
print()

patteren-2:
=========
0
2 4
6 8 10
12 14 16 18
20 22 24 26 28

code:
====

"""
0
2 4
6 8 10
12 14 16 18
20 22 24 26 28

"""
rows=int(input("enter the number of rows:"))
data=0
for i in range(1,rows+1):
for col in range(1,i+1):
print(data,end=" ")
data+=2
print()

patteren-3:
=========
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

code:
====

"""
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

"""
rows=int(input("enter the number of rows:"))
col=rows
for i in range(1,rows+1):
for data in range(1,col+1):
print(data,end=" ")
col-=1
print()

patteren-4:
=========

5 4 3 2 1
4 3 2 1
3 2 1
2 1
1

code:
=====
"""
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1

"""
rows=int(input("enter the number of rows:"))#5
col=rows#5
data=rows#5
for i in range(1,rows+1):#(1,6)
for j in range(1,col+1):#(1,6)
print(data,end=" ")#5 4 3 2 1
data-=1
col-=1#4
data=col#4
print()

patteren-6:
=========
*
* *
* * *
* * * *
* * * * *

code:
====

"""
*
* *
* * *
* * * *
* * * * *
"""
rows=int(input("enter the number of rows:"))#5
for i in range(1,rows+1):print("* "*i)

patteren-7:
=========
* * * * *
* * * *
* * *
* *
*

code:
====

"""
*
* *
* * *
* * * *
* * * * *
"""
rows=int(input("enter the number of rows:"))#5
col=rows
for i in range(1,rows+1):
print("* "*col)
col-=1

patteren-8:
=========

*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*

code:
====
"""
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
"""
rows=int(input("enter the number of rows:"))#5
for i in range(1,rows+1):
if i<=(rows//2):
print("* "*i)
elif i>(rows//2):
print("* "*(rows-i))

patteren-9:
=========

*
*
*
*
*
code:
====

"""
*
*
*
*
*
"""
rows=int(input("enter the number of rows:"))#5
for i in range(rows):
print(" "*i+"*")

patteren-10:
==========

*
*
*
*
*

code:
====

"""
*
*
*
*
*
"""
rows=int(input("enter the number of rows:"))#5
spaces=rows
for i in range(rows):
print(" "*spaces+"*")
spaces-=1

10.functions:
===========

functions are "a block of statements in python and which are

used to perform a specified task in the program"

mainly in python, we are using functions to eliminate the code

reduancy (to eliminate the code duplication)

with help of the functions,we can write the code once, we can

reuse function in the same program as many times where want

in the program

functions are can help make the entire program can be

divided into "n" number of parts

function can reused even in other python files using a concept

called "modules"

function can have any number of lines as a code

function can able to take external data as

arguments/parameters

function can able to return the result, after the function

execution

to create the function in python, we will use the following

syntax:

def function_name(arg1,arg2,arg3,....argn):

#logic

note:
====

in python, to create the function, we will use a keyword called

"def"

function may take arguments, it means for function arguments

are always optional, based on requirement we will take the


arguments

when we create the function in python, it never executed

automatically, until we will call the function

calling the function means "Executing the function"

to call the any function in python, we will use the following

syntax:

name_of_the_function(arg1,arg2,arg3,....argn)

here in the function calling, the arguments we will give only

when the function has arguments, otherwise we will never give

the arguments in the function calling

example:
=======

"""
create the function in python
"""
def display():
print("this is my first function in python")
#call the function display
display()

example-2:
=========
"""
create the function in python
"""
def factorial():
#take the number
num=int(input("enter the number:"))#5
fact=1
for i in range(1,num+1):
fact*=i
print("the factorial of the given number is:",fact)

factorial()

in python, we can write the functions in the following ways:


==============================================

1.function with no arguments and no return type:


=======================================

in this model,

"""function never take any argument as data and function can


not return any value as result"""

example:
=======
"""
function without arguemnts and without return type
"""
def sum_of_the_two_numbers():
#take the numbers
num1=int(input("enter the number1:"))
num2=int(input("enter the number2:"))
print("the sum of the two numbers is:",num1+num2)
sum_of_the_two_numbers()

2.function with arguments and with no return type:


========================================

in this model,

"""function will take arguments as data and but function can

not return any value as result"""

example:
=======

"""
function with arguemnts and without return type
"""
def sum_of_the_two_numbers(x,y):
print("the sum of the two numbers is:",x+y)
#take the numbers
num1=int(input("enter the number1:"))
num2=int(input("enter the number2:"))
#calling function
sum_of_the_two_numbers(num1,num2)

3.function with arguments and with return type:


======================================

in this model,

"""function will take arguments as data and but function can

also return a value as result, after its execution"""

note:
====

function can return any value as result after its execution, with

help a keyword called "return"

generally, we can write the "return" is always at the end of the

function, because after return if we write any code,it never be


executed

return statement is often called as "exit" statement in the

function

return can "return any number of values in python"

when return is returning the values,the return value is coming

from the function, we need to store the function calling in some

variable, then the variable will hold the function returned value

or we can print the value directly using print() function

syntax:
======

variable_name=fucntion_name(arg1,arg2,...….)

or

print(function_name(atg1,arg2,arg3,arg4,...…..))

example:
=======

"""
function with arguemnts and with return type
"""
def sum_of_the_two_numbers(x,y):
return x+y
#take the numbers
num1=int(input("enter the number1:"))
num2=int(input("enter the number2:"))
#calling function
result=sum_of_the_two_numbers(num1,num2)
print(result)

4.function without arguments and with return type:


=========================================

in this model,

"""function will not take any arguments as data and but

function can also return a value as result, after its

execution"""

example:
=======

"""
function without arguemnts and with return type
"""
def sum_of_the_two_numbers():
#take the numbers
num1=int(input("enter the number1:"))
num2=int(input("enter the number2:"))
return num1+num2
#calling function
result=sum_of_the_two_numbers()
print(result)

types of arguments in python functions:


===============================

in python,we will have the following types of arugments:


============================================

1.positional arguments:
==================

when we call the function with arguments, the called function

take the arguments from the "function calling" based on the

position, then the arguments are said to be "positional"

arguments

example:
=======
"""
positional arguments
"""
def my_positional_arguments(x,y,z):
print(x,y,z)
my_positional_arguments(10,20,30)#x=10,y=20,z=30

note:
====

when we are working with positional arguments,we need to

give the "arguments", based on the number of arguments in the

function and even single argument never be skipped,while

calling the function

2.default arguments:
=================

when we are create function and its arguments with default

values, in the function. when we are calling the function,we can

skip the any arguments in the function, while skipping the

function argument will take default value as argument value

example:
=======
"""
default arguments
"""
def my_default_arguments(x=100,y=200,z=300):
print(x,y,z)
my_default_arguments()
my_default_arguments(10)
my_default_arguments(10,20)
my_default_arguments(10,20,30)

3.keyword arguments:
==================

when we are calling the function with arguments, when we

make the function take the values to the arguemnts of the

function from calling based on the names,then those

arguments are called as "keyword arguments"

or

when we call the function with arguments using names of the

arguments of the function, then those arguments can called as

keyword arguments

example:
=======

"""
keyword arguments
"""
def my_keyword_arguments(x,y,z):
print(x,y,z)
my_keyword_arguments(x=10,y=20,z=30)
my_keyword_arguments(z=10,y=20,x=30)
my_keyword_arguments(y=10,z=20,x=30)
my_keyword_arguments(z=10,x=20,y=300)

4.arbitary arguments:
=================

for a function, we can give any number of arguments ,if the

argument in the function is arbitrary, while function calling

these arguments are also called as "var-length" arguments

these arguments can be defined using "*",before its argument

name

syntax for arbitrary argument:


========================

*argument_name
these arguments will take any number of values and all values

can be taken as "tuple" format

example:
=======
"""
arbitary arguments
"""
def my_arbitary_arguments(*x):
print(x)
print(type(x))
my_arbitary_arguments()
my_arbitary_arguments(1,2,3,4,5,6)
my_arbitary_arguments(10,20,30)
my_arbitary_arguments(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)

5.keyword arbitrary arguments:


=========================

for a function, we can give any number of arguments ,if the

argument in the function is keyword arbitrary, while function

calling

these arguments are also called as "keyword var-length"

arguments

these arguments can be defined using "**",before its argument

name

when a function has keyword arbitrary arguments, from

function we can give any number of argument, using names

all keyword arbitrary arguments can be taken by the function

as "dictionary"

example:
=======

"""
keyword_arbitary arguments
"""
def my_keyword_arbitary_arguments(**x):
print(x)
print(type(x))
my_keyword_arbitary_arguments()
my_keyword_arbitary_arguments(a=100,b=200,c=400)
my_keyword_arbitary_arguments(name="ram",location="hyderabad")

example-1:
=========
def display(x,y,z=100):
print(x)#300
print(y)#100
print(z)#450
display(10,20)
display(10,20,30)
display(y=100,x=300,z=450)

example-2:
=========

def display(x,y,z=100,*arg):
print(x)#300
print(y)#100
print(z)#450
print(*arg)
display(10,20)
display(10,20,30)
display(y=100,x=300,z=450)
display(1,2,3,50,60,70,80,90,100)
display(x=100,z=200,y=300)

example-3:
=========

def display(*arg,**kwarg):
print(arg)
print(kwarg)
display()
display(1,2,3,4)
display(1,2,a=10,b=20,c=30)
display(a=10,b=20,c=30)
display(1,10,20,40,a=10,b=20)

exmaple-4:
=========

def display(x,y,z=100,*arg,**kwarg):
print(x,y)
print(z)
print(arg)
print(kwarg)
display(10,20)
display(20,y=100,z=300)
display(30,20,50,1,2,3,a=10,b=20,c=40)

recursive functions:
===============

recursive function means "a function which is call itself"

recursive function can exhibit "loops" behaviour

example:
=======

def display(x):
if x<=10:
print("this is recursive function")
x+=1
display(x)
display(1)

example:
=======

find the factorial of the given number using recursion:


==========================================

code:
====

def factorial(num):
if num==0 or num==1:
return 1
elif num>1:
return num*factorial(num-1)
print(factorial(int(input("enter the nummber:"))))

example:
=======
print the factors of the given number using recursion
==========================================

def factor(num,fact):
if fact<=num:
if num%fact==0:
print(fact)
factor(num,fact+1)
fact=1
factor(int(input("enter the nummber:")),fact)

lambda functions:
==============

lambda function is a function and which can have only one line

as code

this function is also called "anonymous" function ,like normal

functions, lambda functions can not have the any name

to create the lambda function, we will use a keyword called

"lambda"

lambda function can able take o or any number of arguments

lambda function can return result like normal functions

syntax:
======

lambda arg1,arg2,arg3,..argn: expression or code in one line


when we want to call the lambda function, in python we will

store the entire lambda function in the variable, that variable

name we can use "To call the lambda function in python"

we never use "return" keyword in the lambda function,because

it by default return the result, when write any code result

example:
=======
x=lambda:print("this is my first lambda function")
print(type(x))
x()
x=lambda a,b:a+b
print(x(10,20))
x=lambda a,b,c:a+b+c
print(x(1,2,3))

example:
=======

lambda function with normal function:


==============================

example:
=======

def result(num):
return lambda x:num*x
res=result(int(input("number:")))
print(type(res))
print(res(10))

python scope:
===========

scope refers "at what extent we can able to access the data

in the program"

generally we will have two types of scope:


=================================

1.local scope:
============

when we define the any data inside the function, then that data

can able to access only in the function, but not outside the

function , these data can have local scope

2.global scope:
============

when we define any data outside the function, then the data

can access any where in the program(inside the function or

outside the function),these data can have global scope

global data,we can access inside the function, but we can not

to manipulate the data inside the function

example:
=======

x=10#global data
def display():
y=20
print(x)#global data
print(y)#local data
print(x)#10
display()

example:
=======

x=1000
def display1():
print(x)
x=100
def display2():
print(x)#100
display2()#100
display1()#100

python scope will follows a rule like "LEGB"

L ===>Local

E===>Enclosed

G===>Global

B===>Built-in

example-3:
=========

x=10
def display():
x=100
print(x)
x+=100
print(x)
display()

inner functions(global and nonlocal keywords):


====================================
inner functions(global and nonlocal keywords):
====================================

inner function means "creating the function inside another

function"

inner function is also called as "nested functions or python

closures"

when we creare the inner function,the inner function will have

the following:
=================================================

inner function can able to access the outer function data ,but

not vice versa(outer function can not access the inner function

data)

inner functions can be called only in outer function, but not

outside outer function

inner function can able to access the global data (the data

which is defined outside the outer function in the program, but

global data can not be in any other function)

in a outer function, we can able to create any number of inner

functions

example:
=======
def outer():
def inner1():
print("This is inner 1")
def inner2():
print("This is inner 2")
def inner3():
print("This is inner 3")
inner1()
inner2()
inner3()
outer()

example-2:
=========

p,q,r=1,2,3#global data
def outer():
x,y,z=100,200,300
print(p,q,r)
def inner1():
a=10
print(p,a,x)
def inner2():
b=20
print(q,b,y)
def inner3():
c=30
print(r,c,z)
inner1()
inner2()
inner3()
outer()

example-3:
=========

global keyword :

using global keyword,we can able access the local data,any

where in the program

when we give the global to variable, we never assign any value

while using global keyword

syntax:
======

global variable_name

example:
=======

def display():
global x
x=100
print(x)
display()
print(x)
def display2():
print(x)
display2()

example-2:
=========

def display():
global x
def inner1():
global x
x=1000
def inner2():
global x
print(x)
inner1()
inner2()
print(x)
display()
print(x)

nonlocal:
=======

nonlocal keyword used to "Access the data which is having

enclosed scope or inner function data outside"

nonlocal is defined same as "global"

syntax: nonlocal variable_name

example:
=======

x=10
def display():
def inner1():
x=100
print(x)#100
inner1()
print(x)#10
display()

example:
========
x=10
def display():
def inner1():
x=1000
print(x)
def inner2():
def inner3():
print(x)
global x
x=1000
inner3()
inner1()
inner2()
print(x)
display()
print(x)

example:
=======

x=10
def display():
x=10
print(x)#10
def inner1():
nonlocal x
x=100
print(x)#100
inner1()
print(x)#100
display()
print(x)

example:
=======

x=10
def display():
x=100
def inner1():
nonlocal x
print(x)
inner1()
print(x)
display()
print(x)

example:
=======

x=10
def display():
x=100
def inner1():
nonlocal x
x=1000
def inner2():
nonlocal x
print(x)
print(x)
inner2()
inner1()
print(x)
display()
print(x)#10

example:
=======

def display():
global x
x=100
display()
print(x)
def display2():
global x
x=1000
print(x)
display2()
print(x)#1000

example:
=======

x=10
def display():
global x
x+=10
print(x)#20
def inner():
global x
x+=100
print(x)#120
inner()
display()
print(x)#120
def display2():
global x
x+=300
print(x)#420
display2()

example:
=======
x=10
def display():
x=100
def inner():
nonlocal x
x+=100
print(x)#200
inner()
print(x)#200
def inner2():
nonlocal x
x+=300
print(x)#500
inner2()
print(x)#500
display()
print(x)

11.modules & packages:


====================

modules:
=======

module means "is a python file"

in python, modules can have "data and functions"

data means "variable, list, tuple,...…….."

using modules, any python file can use another python file

data/functions

using python module, we can reuse the any other python file

data or functions

to create/to work with python module, we will use the following

steps:
=================================================

step-1: create the python file with data and functions


step-2: save the python file with some_name.py, here the

python file name is itself "module name"

step-3: to use the any module data/functions, in another

python file, we will use the following syntax:

import module_name

here "import" is a python keyword and using this keyword

we can access the any python module in any python file

step-4: to access the any data/method in the python file ,from

the module, we will use following syntax:

module_name.data_name/method_name()

example:
=======

sample.py:
=========
x=100
y=200
z=300
def display():
print("this is sample module")
def add(a,b):
print(a+b)
def sub(a,b):
print(a-b)
def mul(a,b):
print(a*b)

test.py:
======
import sample
print(sample.x)
print(sample.y)
print(sample.z)
sample.display()
sample.add(10,20)
sample.sub(10,20)
sample.mul(10,20)

how to alias the module name in python:


================================

to alias the module name in the python, we will use a keyword

called "as"

syntax for "as"


============
import module_name as alias_name

example:
========
import sample as s
print(s.x)
print(s.y)
print(s.z)
s.display()
s.add(10,20)
s.sub(10,20)
s.mul(10,20)

note:
====

from python module, if we want only a specific data/methods,

in python we will use a keyword called "from"

syntax for from:


=============

from module_name import data_mem_name1,...…..

example:
=======

from sample import x,y,display


print(x)
print(y)
display()

packages and sub-packages:


=======================

package means "collection of python modules(files)"

package is often called as "python files folder"

in python, package can have any number of python files

in python, python module is a single python file

to work with python package, we will use the following steps:


================================================

step1-: create a python folder

step-2: once we create the python folder, we need to create

a empty python file with name "__init__.py"

step-3: create any number of python modules(files) in the

folder

step-4: use package, to access the data or methods of any


python module(file) as follows:

import package_name.module_name as alias_name

package name: mypackage

mypackage files: sample.py,sample2.py

sample.py:
=========

x=100
y=200
z=300

sample2.py:
=========

def add(a,b):print(a+b)
def sub(a,b):print(a-b)
def mul(a,b):print(a*b)

using "test.py" we are accessing the data/functions of

mypackage module ,first create the test.py outside the

mypackage

test.py:
======

import mypackage.sample as ms1


import mypackage.sample2 as ms2
print(ms1.x,ms1.y,ms1.z)
ms2.add(10,20)
ms2.sub(10,20)
ms2.mul(10,20)

if we want to access specific data/functions from the mypakage

, we will use the following syntax:


=================================================

from package_name.module_name import data1,data2,....

example:
=======

test.py
======

from mypackage.sample import x,y,z


from mypackage.sample2 import add,sub,mul
print(x,y,z)
add(10,20)
sub(10,20)
mul(10,20)
working with sub packages:
======================

mypackage2
|
|
__init__.py(create, save and run the file)
mysubpackage1
|
__init__.py(create, save and run the file)
sample.py
mysubpackage2
|
__init__.py(create, save and run the file)
sample2.py
sample.py:
=========

x=100
y=200
z=300

sample2.py:
=========

def add(a,b):print(a+b)
def sub(a,b):print(a-b)
def mul(a,b):print(a*b)

create the "test.py" outside the "mypackage2" as follows:


============================================

test.py:
======

import mypackage2.mysubpackage1.sample as mms1


import mypackage2.mysubpackage2.sample2 as mms2
print(mms1.x,mms1.y,mms1.z)
mms2.add(10,20)
mms2.sub(10,20)
mms2.mul(10,20)

if we want to access the only a spesific data from the

subpackage moduels, we will use following syntax:


=================================================

from package_name.subpackagename.module_name import data1,data2...

example:
=======

test.py:
======
from mypackage2.mysubpackage1.sample import x,y
from mypackage2.mysubpackage2.sample2 import add,sub
print(x,y)
add(10,20)
sub(10,20)

13.built-in functions:
=================

generally, in python we will have two types of functions:


============================================

1.user-defined function:
===================

these functions are created by the programmers or developers

2.built-in function:
===============

these functions can be given by python, these functions are not

created by the programmer or developer

in python, we will have some the following important built-in

functions:
================================================

1.print()<=== it used to print/display the output of the program

example:
=======

x,y,z=10,20,30
print(x)
print(y)
print(z)
print(x,y,z,sep=",")
print(x,y,z,end=",")

example-2:
=========

output formatting with print(via f-strings):


=================================

code-1:
======
x,y,z=10,20,30
print(f"the value of x is:{x}")
print(f'the value of y is:{y}')
print(f"the sum of the x and y is:{x+y}")

output formatting with print(via format specifiers)


=======================================
code-2:
x,y,z=10,20,30
print("the value of x is:%d"%(x))
print("the value of x+y is:%d"%(x+y))
print("the value of x/y is:%d"%(x/y))
print("the value of result is:%f"%(x))
print("the value of result is:%d"%(4.56789))
print("the value of x is :%s"%(100000))
print("the value of result is:%d"%(True))

output formatting with print() (via format() function)


========================================

code-3:
======

x,y,z=10,20,30
print("the value of x is:{0}".format(x))
print("the value of y is {1} and x is :{0}".format(x,y))
print("the value of y is {value2}".format(value2=y))
print("the value of z is {z1} and x is {x1}".format(z1=z,x1=x))

2.input()<=== it is used to take the input from the user:


===========================================

note:
====

to make the user,to give the data to input() function,always

recommend to give the prompt in the function, otherwise user

will not able to give the input/user will not understand where

to give the input

example:
=======

x=input("X value:")

3.int()<=== it used to convert the given data into integer type

example:
=======

x=int()
print(x)
x=int(12_34)
print(x)
x=int(1_2_3_4)
print(x)
x=int("123")
print(x)
x=int(12.34)
print(x)
x=int("+123")
print(x)
x=int("-123")
print(x)

4.float()<===it used to convert the given data into float type


example:
=======

print(float(10))
print(float())
print(float("+123"))
print(float("-67"))
print(float("1_2.3_4"))
print(float(+12_34.5_6_7))
print(float("12.34"))

5.str()<===it used to convert the given data into string type

example:
=======

print(str())

7.bool()<=== it used to convert the given data into Boolean type

example:
=======

print(bool())#default is False
print(bool(1))
print(bool(0))
print(bool(None))
print(bool("abc"))
print(bool(''))
print(bool(10+5j))
print(bool(-123))

8.complex()<=== it used to convert he given data into complex:

example:
=======

print(complex(10))
print(complex(1.2))
#print(complex("abc"))
print(complex(True))
print(complex(False))
#print(complex(None))
print(complex(10+5j))
print(complex())

9.list()<=== it used to convert given iterable data into list type

example:
=======
print(list(range(1,10)))
print(list((1,2,3,4,5)))
print(list("hello"))
print(list({1,2,3,4,5,6,7,8,9,10}))
print(list({1:2,3:4,5:6}))
10.tuple()<== it used to convert the given iterable data into

tuple

example:
=======

print(tuple([1,2,3,4,5]))
print(tuple("12345"))
print(tuple("hello"))
print(tuple({1,2,3,4,5,6,7,8,9,10}))
print(tuple({1:2,3:4,5:6}))
print(tuple("h"))

11.set()<=== it used to convert the given iterable data into set

example:
=======

print(set([1,2,3,4,5]))
print(set("12345"))
print(set("hello"))
print(set({1,2,3,4,5,6,7,8,9,10}))
print(set({1:2,3:4,5:6}))
print(set("h"))
print(set([1,2,3,12,3,1,23,4,5]))

12.range():
=========
example:
========
print(range(1,10))
print(type(range(1,10)))
print(list(range(1,10,4)))
a=range(10,1,-1)
print(a)
print(tuple(a))

13.dict():<===it used to convert the given data into dictionary


========

example:
========
print(dict(a=10,b=20,c=30,d=40))
print(dict())
print(set())
a={}
print(type(a))

14.bin(): it used to convert the given number into binary

in python binary number can start with "0b or 0B"

example: 0b101010,0B1010101

example:
=======
print(bin(10))#10 is decimal number(0-9 only digits)
print(bin(0o127))#here is octal number(0-7 only digits)
print(bin(0xabc))#here is hexadecimal number(0-9 and a-f)
a=bin(27)#110011
print(type(a))#<class 'str'>

15.oct() ===> it used to convert the given number into binary

in python binary number can start with "0o or 0O"

example:
=======

print(oct(100))
print(oct(0b10101))
print(bin(0xabc))
a=oct(27)
print(type(a))

16.hex():
=======

print(hex(100))
print(hex(0b10101))
print(hex(0xabc))
a=hex(27)
print(type(a))

note:
=====

a=0b10101#binary literal
b=0x121#hexa decimal litreal
c=0o127#octal litreal
print(a)
print(b)
print(c)
a=bin(a)
print(a)

17.split():
========

this function will used to split the given string into "n"

number of parts based on the given delimeter or character

example:
=======
print("hello world".split())
print("abcdefghij".split("e"))
print("hello world".split("l"))
print("hellllworlld".split("l"))
print("hellllllld".split("l"))
print("delloh".split("h"))
a,b,c=input("enter:").split(",")
print(a,b,c)
18.map()

19.filter()

20.eval():
=======

this function will evaluate the given expression in the string

form

example:
=======
a=10
b=20
print(eval("10+20"))
print(eval("a+b"))
print(eval("a>10"))
print(eval("a<20"))
print(eval("a**2"))

21.exec():
========

this function will execute the given code which is in the form

of string

example:
=======

exec("a=10")
exec("b=20")
print(a)
print(b)
exec("result=a+b")
print(result)
print(eval("a+b"))

22.min():
=======

this function is used to "find the minimum of value of the given

iterable data"

example:
=======
print(min(range(1,10)))
print(min([10,2,3,4,0,-12,100]))
print(min(range(10,-3,-4)))
print(min({1,2,3,10,90,100,345,789}))
print(min(1,2,3,4,5,6,7,8,9,10))
print(min(10,20,30,40,50,60,70,80,90,100))
a=1,2,3,4,5,6,7,8,9,10
print(type(a))
23.max():
========

this function is used to find the "maximum value of the given

iterable" in python

example:
=======

print(max(range(1,10)))
print(max([10,2,3,4,0,-12,100]))
print(max(range(10,-3,-4)))
print(max({1,2,3,10,90,100,345,789}))
print(max(1,2,3,4,5,6,7,8,9,10))
print(max(10,20,30,40,50,60,70,80,90,100))
a=1,2,3,4,5,6,7,8,9,10
print(type(a))

24.len():
=======

this is function is used "To count the number values are

present in the given iterable in python"

example:
========

print(len(range(1,10)))#9
print(len([10,2,3,4,0,-12,100]))#7
print(len(range(10,-3,-4)))#4
print(len({1,2,3,10,90,100,345,789}))#8
print(len([1,2,3,4,5]))#10

25.ord():
=======

this function will return the "Unicode number of the given character"

example:
=======

print(ord("A"))
print(ord('C'))
print(ord('a'))
print(ord('b'))
print(ord('1'))
print(ord(";"))

26.chr():
=======
this function will return "the given number equitant character

in the Unicode"

example:
=======

print(chr(96))
print(chr(99))
print(chr(100))
print(chr(120))
print(chr(90))

27.any():
=======

this function will check "in the given iterable any one is

True, then the entire result is "True", otherwise False

example:
=======

print(any((1,2,3,4,5,6,7)))
print(any(''))
print(any({0}))
print(any([1,2,3,0,0,0]))

28.all():
======

this function will check "in the given iterable, all values are

True, then the entire result is "True", otherwise False

example:
========
print(all((1,2,3,4,5,6,7)))
print(all(''))
print(all({0}))
print(all([1,2,3,0,0,0]))

29.zip():
=======

this function will be to "zip the given two iterables"

example:
=======

l1=[1,2,3,4,5]
l2=[4,5,6,7,8]
result=list(zip(l1,l2))
print(result)
l1=[1,2,3,4,5]
l2=[4,5,6,7]
result=list(zip(l1,l2))
print(result)
l1=[1,2,3]
l2=[4,5,6,7,8]
result=list(zip(l1,l2))
print(result)

30.enemurate():
=============

l1=[1,2,3,4,5]
l2=[4,5,6,7,8]
result=list(enumerate(l1))
print(result)
result=list(enumerate([10,20,30,40,50,60,70,80,90,100]))
print(result)
result=list(enumerate("hello world"))
print(result)

31.sorted():
=========

this function will used "to sort the given iterable data and it

will give the result any iterable data in list form only"

this function will sort the data "either in ascending or

descending order"

example:
=======

l1=[1,2,3,4,5]
l2=[4,5,100,-12,34,56]
print(sorted(l1))
print(sorted(l2))
print(sorted(l2,reverse=True))
print(sorted("hello"))
print(sorted({1,2,3,100,567,890,-45,-78}))

32.round():
=========

this function is a built-in function and it is used to round the

given value ,here it will take number as "float or real number"

syntax:
======

round(float/real number)

example:
=======

print(round(1.234,0))
print(round(1.456,3))
print(round(1.5))
print(round(1.49999))
print(round(1.4567,2))
print(round(1.456789,3))
print(round(1.4))

14.built-in modules(math,random,time,datetime,os,sys):
============================================

1.working with math module:


=======================

this module is used in python "to perform any mathematical

operations"

this module will provide the "functions which are related to

mathematical, logarithmic, trigonometric "

in this module, we will following functions:


=================================

1.ceil():
======

this function is used to find the "ceil value or upper value

of the given real/floating-point number" and the result of this

function is "integer" number

syntax:
======

import math as mt

mt.ceil(real/floating-point number)

example:
=======

import math as mt
print(mt.ceil(1.234))
print(mt.ceil(9.01))
print(mt.ceil(5.0))
print(mt.ceil(-4.56))

2.floor():
=======

this function is used to find the "floor value or lower value

of the given real/floating-point number" and the result of this

function is "integer" number

syntax:
======

import math as mt
print(mt.floor(realnumber))

example:
=======

import math as mt
print(mt.floor(1.234))
print(mt.floor(9.01))
print(mt.floor(5.0))
print(mt.floor(-4.56))

3.trunc()<== this function simple remove the given number

fractional part/decimal part,return number which

before the decimal part

syntax:
======

import math as mt
print(mt.trunc())

example:
=======

import math as mt
print(mt.trunc(1.234))
print(mt.trunc(9.01))
print(mt.trunc(5.0))
print(mt.trunc(-4.56))

4.fsum()<=== is used to find the sum of the values of the given

iterable

syntax:
======

import math as mt
print(mt.fsum())

example:
=======

import math as mt
print(mt.fsum([1,2,3,4,5,6,7,8,9,10]))
print(mt.fsum(range(1,10)))
print(mt.fsum((1,2,3,4,5,6,7,8,9,10)))
print(mt.fsum({1,2,3,4,5,6,7,8,9,10}))

5.prod():
=======
this function is used to find the "product of the values of the

given iterable"

syntax:
======

import math as mt
print(mt.prod(sequence_name))

example:
=======

import math as mt
print(mt.prod([1,2,3,4,5,6,7,8,9,10]))
print(mt.prod(range(1,10)))
print(mt.prod((1,2,3,4,5,6,7,8,9,10)))
print(mt.prod({1,2,3,4,5,6,7,8,9,10}))

6.factorial():
==========

this function is used to find the factorial of the given number

syntax:
======

import math as mt

print(mt.factorial(number))

example:
=======

import math as mt
print(mt.factorial(10))
print(mt.factorial(0))
#print(mt.factorial(1.2))
#print(mt.factorial(-10))

write a python program,find the given number is which number factorial or not?
==============================================

code:
=====

import math as mt
number=int(input("enter the number:"))
fact=1
while True:
if mt.factorial(fact)==number:
print(f"the given {number} is factorial of {fact}")
break
elif mt.factorial(fact)>number:
print(f"given {number} not any factorial of the number")
break
else:
fact+=1

7.perm():
========

this is used to find the permutation of the given number

syntax:
======

import math as mt

print(mt.perm(n,k))

example:
========
import math as mt
print(mt.perm(4,4))
print(mt.perm(5,4))
print(mt.perm(10,2))
print(mt.perm(10,20))

8.comb():
=======

this is used to find the combination of the given number

example:
=======

import math as mt
print(mt.comb(4,4))
print(mt.comb(5,4))
print(mt.comb(10,2))
print(mt.comb(10,20))

9.sqrt():
======

it is used to find the square root of the given number

example:
=======

import math as mt
print(mt.sqrt(100))
print(mt.sqrt(196))
print(mt.sqrt(80))
print((int(input("number:")))**(0.5))

10.cbrt():
=======

it is used to find the cube root of the given number

syntax:
======

import math as mt
print(mt.cbrt(number))

example:
=======

import math as mt
print(mt.cbrt(100))
print(mt.cbrt(196))
print(mt.cbrt(80))
print((int(input("number:")))**(1/3))
print(mt.cbrt(27))

11.exp():
=======

this is used to find the expoenential value of the given number

syntax:
======

import math as mt

print(mt.exp(number))

example:
=======

import math as mt
print(mt.exp(1))
print(mt.exp(19))
print(mt.exp(-4))

12.pow():
========

it used to find the power of the given number

syntax:
======

import math as mt

print(mt.pow(number))

example:
=======

import math as mt
print(mt.pow(3,3))
print(mt.pow(2,10))
print(mt.pow(2,-10))

13.fabs():
========
it is used to "get the given number as always positive number"

it act like "modulus" in mathematics

syntax:
======

import math as mt

print(mt.fabs(number))

example:
=======

import math as mt
print(mt.fabs(-10))
print(mt.fabs(10))
print(abs(10))
print(abs(-10))

14.fmod():
========

this function is used to give the "remainder of the given two

numbers and it is work like "%" in python"

syntax:
======

import math as mt
result=mt.fmod(num1,num2)

example:
=======

import math as mt
print(mt.fmod(10,20))#10.0
print(mt.fmod(3,4))#3.0
print(mt.fmod(10,5))#0.0
#divmod()<=== it will return both quotient and remainder
print(divmod(10,20))#(10//20,10%20)==>(0,10)
print(divmod(20,4))#(5,0)

note:
=====

divmod() is a "built-in function in python"

15.gcd():
=======

it is used to find the "gretest common divisor of the given two

numbers"
syntax:
======

import math as mt

print(mt.gcd(num1,num2))

example:
========

import math as mt
print(mt.gcd(10,20))#10
print(mt.gcd(16,64))#16
print(mt.gcd(100,200))#100
print(mt.gcd(100,0))#100
print(mt.gcd(12,56))#4

in math module,we will have other functions:


===================================

sin()

cos()

tan()

asin()

acos()

atan()

sinh()

cosh()

tanh()

log()

log10()

log2()

in math module,we will have the following constants:


=========================================

math.e <==eluer's number

math.pi

math.tau

math.inf

math.nan

example:
=======

import math as mt
print(mt.log(1))
print(mt.log(12))
print(mt.log10(1234))
print(mt.log2(123))
#shoutcut using log10(),we can find number length
print(int(mt.log10(123456789))+1)
print(mt.log10(123456789))
print(int(mt.log10(int(input("Enter:"))))+1)

example:
=======

import math as mt
print(mt.e)#2.7
print(mt.tau)
print(mt.inf)
print(mt.nan)
print(10+mt.inf)
print(10-mt.inf)
print(mt.pi)

2.random module:
==============

this module is used in python "To generate the random or

to work with random numbers"

in this module, we will have the following functions:


========================================

1.random():
==========

this function will generate the random in between "0 to 1"

this random number will be always "float/real number"

syntax:
======

import random as rd

print(rd.random())

example:
=======

import random as rd
print(rd.random())
print(int(rd.random()*10))
print(int(rd.random()*100))
print(int(rd.random()*1000))
print(int(rd.random()*10000))
print(int(rd.random()*100000))

2.randint():
=========

this function will generate the "an integer random number"

for the given range

syntax:
======

import random as rd

print(rd.randrange(start,end))

example:
=======

import random as rd
print(rd.randint(1,10))
print(rd.randint(1,1000))
print(rd.randint(1,10000))
print(rd.randint(1,100000))
print(rd.randint(1,1000000))

3.randrange():
===========

this function will give the "integer random number" and this

function will take the arguemnts like range() function

this function will have arguments like start,end and step

syntax:
======

import random as rd

print(rd.randrange(start,end,step))

example:
========

import random as rd
print(rd.randrange(1,10,2))
print(rd.randrange(10,100,10))
print(rd.randrange(1,100,23))

4.choice():
========

this function will give the a spesic number only as random

number form the given choice of numbers


example:
=======

import random as rd
print(rd.choice(range(1,10)))
print(rd.choice([1,2,3,4,5,6,7,8,9,10]))
print(rd.choice((10,20,30,40,50,60,70,80,90,100)))
print(rd.choice("helloworld"))

5.shuffle()
========

this function will shuffle the data "elements which are available

in the given list"

example:
=======

import random as rd
l1=[1,2,3,4,5,6,7,8,9,10]
rd.shuffle(l1)
print(l1)
rd.shuffle(l1)
print(l1)
rd.shuffle(l1)
print(l1)

6.uniform():
=========

this function will generate a float/real random number for

the given range

example:
=======

import random as rd
print(rd.uniform(10.0,20.0))
print(rd.uniform(10,20))
print(rd.uniform(0.5,0.8))

7.sample():
=========

this function is used to get a sample(list of numbers) as

random from the given list of numbers

example:
=======

import random as rd
l1=[10,20,30,40,50,60,70,80,90,100]
print(rd.sample(l1,3))
print(rd.sample(l1,4))
print(rd.sample(l1,8))
print(rd.sample(l1,1))

write a python program generate a random number which is

having length as "10" digits and number must start with even

digit and end with odd digit

code:
====
import random as rd
res=''
res+=str(rd.randrange(0,10,2))
while len(res)!=9:
res+=str(rd.randrange(1,10))
res+=str(rd.randrange(1,10,2))
print(res)

write a python program "to generate a random number

which is does not have digits like 2,3,4,5 and length of the

number must be 12 digits"

code:
====
import random as rd
res=''
while len(res)!=12:
i=str(rd.randrange(1,10))
if i not in "2345":
res+=i
print(res)

write a python program to "generate a random number which

is having length 10 and which is having vowels and digits. the

random number never have uppercase vowels. the number of

vowels in the random never exceed 5

code:
====

import random as rd
res=''
while len(res)!=10:
i=chr(rd.randrange(97,123))
if i in "aeiou":
res+=i
else:
res+=str(rd.randrange(1,10))
print(res)
write a python program to generate a random number which

having length is 15 and it may contain only alphabets and

digits. every alternate character in the number is digit and

random number start with "alphabet"

code:
====

import random as rd
res=''
while len(res)<=15:
if len(res)<15:res+=chr(rd.randrange(97,123))
else:break
if len(res)<15:res+=str(rd.randrange(1,10))
else:break
print(res)

write a python generate a random number which is of length

18,which may follow the following rules:


=================================================

number must have 4 digits

number must have 4 vowels

number must have 4 special symbols are (+,@,#,$,%,&)

number must have 4 consodents

3.os module:
===========

this module is used in python, to work with directories and

files in the system

with help of python we can able to "work with directories and

files"

in order to, work with directories or files in the python, python

uses a module called "os(operating system)"

working with directories:


===================

directory means "a folder"

a folder can have "collection of files"

in python os module ,we will have the following functions to


work with directories(folders):

1. mkdir()<== it is "to create/make directory"

2. chdir()<=== it is used to "change directory" path

3. getcwd()<=== to get the "current working directory path"

4. rmdir()<=== to remove the "directory"

5.rename()<=== it is used to "rename the directory"

example-1:
=========

import os
#get the current working directory path
print(os.getcwd())

example-2:
=========

import os
#get the current working directory path
print(os.getcwd())
#create the directory
os.mkdir('sample4')
os.mkdir("sample5")
#list the all directories
print(os.listdir())

example-3:
=========
import os
#get the current working directory path
print(os.getcwd())
#change the directory path
os.chdir("D:/training/360digrii/python FP4_2024/python_practical/sample")
#get the current working directory path
print(os.getcwd())
#create the directory
os.mkdir("mysample")

example-4:
=========

import os
#get the current working directory path
print(os.getcwd())
#change the directory path
os.chdir("D:/training/360digrii/python FP4_2024/python_practical/sample")
#get the current working directory path
print(os.getcwd())
#remove the directory
os.rmdir("mysample")
example-5:
=========

import os
#get the current working directory path
print(os.getcwd())
#change the directory path
os.chdir("D:/training/360digrii/python FP4_2024/python_practical")
path="D:/training/360digrii/python FP4_2024/python_practical"
#get the current working directory path
print(os.getcwd())
#list the directories in the current path
res=os.listdir()
for i in res:
if os.path.isdir(i):
print(i)
#listn the directories in the current path
res=list(os.scandir())
for i in res:
if os.path.isdir(i):
print(i)

example-6:
=========

write a python program to remove the only directories from the

given path:
=================================================import os
#get the current working directory path
print(os.getcwd())
#change the directory path
os.chdir("D:/training/360digrii/python FP4_2024/python_practical")
path="D:/training/360digrii/python FP4_2024/python_practical"
#get the current working directory path
print(os.getcwd())
#list the directories in the current path
res=os.listdir()
for i in res:
if os.path.isdir(i):
os.rmdir(i)

example-7:
=========

create 20 dummy folders inside a given path using python:


==============================================

code:
====

import os
#get the current working directory path
print(os.getcwd())
#change the directory path
os.chdir("D:/training/360digrii/python FP4_2024/python_practical")
path="D:/training/360digrii/python FP4_2024/python_practical"
#get the current working directory path
print(os.getcwd())
#create the 20 directories in the given path
for i in range(1,21):
os.mkdir("sample"+str(i))

example-8:
=========

import os
#get the current working directory path
print(os.getcwd())
#change the directory path
os.chdir("D:/training/360digrii/python FP4_2024/python_practical")
path="D:/training/360digrii/python FP4_2024/python_practical"
#get the current working directory path
print(os.getcwd())
#rename the directory
os.rename("sample1","mysample1")

example-9:
=========

rename the all directories which are existing in the given path,

by just add "my" as prefix for each directory using python


=================================================

import os
#get the current working directory path
print(os.getcwd())
#change the directory path
os.chdir("D:/training/360digrii/python FP4_2024/python_practical")
path="D:/training/360digrii/python FP4_2024/python_practical"
#get the current working directory path
print(os.getcwd())
#rename the directory
for i in os.listdir():
if os.path.isdir(i):
os.rename(i,"my"+i)

working with files:


==============

file means "collection of information"

file can also called as "location in a auxiliary memory/secondary

memory"

in python, when we want to work with "files", we will use a

module called "os"

the os module, will provide the following functions, to work


with files in python:
=================================================

1.open()<=== it is used to "open" a file

2.read()<==== to read the file content

3.readline()<=== to read the file content in a line by line

4.readlines()<== to read the file content in a line by line, it gives

the result in a list form

5.write()<===to write or append the file, we will use this

function

6.close()<=== to close the file in python, we will use this

function

7.remove()<=== this function is used to remove the file

8.rename()<=== this function is used to rename the file in

python

note:
====

when we are open any file in python, while opening the file we

need to specify the "mode"

mode of the file will represents "what type of operation ,we are

performing on the file"

in python, we will use the following modes, while opening the

file:
=================================================

1.r <=== read mode

2.w<=== write mode

3.a<=== append mode

4.r+<=== read and write

5.w+<=== write and read

6.a+<=== append and read

when we are performing the operation on the binary file, it will

have the following modes:


=================================================
1.rb<=== read binary

2.wb<=== write the binary

3.ab<=== append binary

4.rb+<=== read and write binary

5.wb+<=== write and read binary

6.ab+<=== append and read binary

write and append in python:


======================

in python, when we writing the any data into the file, first the

entire file content will be removed and place the content what

we are writing in the file

in python write operation is act like ,"overwrite the old content

with new content"

in python, when we perform append, the writing the data

simply add at end of the file, it never remove the previous

content in the file

in the case of both append and write operation, file need not be

there inside the folder, if the file is not there inside the working

folder, file will automatically created while performing write or

append, but not in the case of "read" operation

example-1:
=========

import os
#get the current working directory path
print(os.getcwd())
#open a file
fp=open("sample.txt","w")
#here we are write the content in the file using write() fucntion
fp.write("this is data is added")
#after performing the operations,we need to close the file
fp.close()

example-2:
========

import os
#get the current working directory path
print(os.getcwd())
#open a file
fp=open("sample.txt","a")
#here we are append the content in the file using write() fucntion
fp.write("this is data is added")
#after performing the operations,we need to close the file
fp.close()

example-3:<===read the data from the file using read()

read() function will read the data from the file, character by

character

when we use the read(),with no parameter or argument, it will

simply read whole file content

when we give the read(),with argument or parameter generally

we will give the number as argument in the read function, the

number represents "number of characters to read from the file"

code:
====

import os
#get the current working directory path
print(os.getcwd())
#open a file
fp=open("sample.txt","r")
#here we are read the content in the file using read() fucntion
data=fp.read(10)
print(data)
data=fp.read(10)
print(data)
data=fp.read()
print(data)
#after performing the operations,we need to close the file
fp.close()

example-4:<== read the file content using readline()

when we are read the file content using readline(), this function

will read the entire file content in a line by line

when we are using readline(), if we are not given any argument

it simply read only one line

when we are using readline(), if we give any argument or

parameter, generally we will give a number, this will tells that

how many characters to read from the file

code:
====

import os
#get the current working directory path
print(os.getcwd())
#open a file
fp=open("sample.txt","r")
#here we are read the content in the file using read() fucntion
data=fp.readline()
print(data)
data=fp.readline(12)
print(data)
#after performing the operations,we need to close the file
fp.close()

example:
========

import os
#get the current working directory path
print(os.getcwd())
#open a file
fp=open("sample.txt","r")
#here we are read the content in the file using read() fucntion
data=fp.readlines()
print(data)
#after performing the operations,we need to close the file
fp.close()

example:
=======

in python, we will use a keyword called "with", when we open

any file using "with" ,it can be close automatically when we use

with

"with" keyword will be used in python the following cases:


============================================

1.working with files

2.working with database connections

3.wroking with network connections

4.any other resources

example-1:
=========

import os
#get the current working directory path
print(os.getcwd())
with open("sample.txt") as fp:
#here we are read the content in the file using read() fucntion
data=fp.readlines()
print(data)
print(fp.readlines())

when we want to work with files, we will have a function called

"seek()",to set the file pointer position

example:
=======
import os
#get the current working directory path
print(os.getcwd())
with open("sample.txt") as fp:
#here we are read the content in the file using read() fucntion
print(fp.seek(5))
data=fp.read(5)
print(data)

to get the file pointer position in python ,we will use a function

called "tell()"

example:
=======

import os
#get the current working directory path
print(os.getcwd())
with open("sample.txt") as fp:
#get the file pointer position
print(fp.tell())
#set the file pointer position
fp.seek(5)
#get the file pointer position
print(fp.tell())
#set the file pointer position
fp.seek(15)
#get the file pointer position
print(fp.tell())#15
#set the file pointer position
fp.seek(5+fp.tell())
#get the file pointer position
print(fp.tell())

example:
=======
import os
#get the current working directory path
print(os.getcwd())
with open("sample.txt") as fp:
#to rename the file,we will rename()
os.rename("sample2.txt","sample_new.txt")

example:
=======

import os
#get the current working directory path
print(os.getcwd())
with open("sample.txt") as fp:
#to remove the file,we will remove()
os.remove("sample_new.txt")

when we are working with files, in python we need to use the

following functions:
================================================

1.open()====>to open the file

2.read()=====>to read the file (character by character)

3.readline()===>to read the file(line by line)

4.readlines()===>to read the file (line by line, but result in list)

5.write()===>used to write or append (based on the mode)

6.seek()===>used to set the file pointer position

7.tell()====>used to get the current file pointer position

8.rename()===>used to rename the file

9.remove() ===>used to remove the file in the directory

pickling and un-pickling:


===================

pickling means "the process of converting a python object

into byte stream(it unreadable "by the users or anyone")

pickling is also called as "Serialization"

pickling is a "most safe process"

un-pickling means "the process of converting the byte stream

into python object"

unpickling is also called as "deserialization"

using un-pickling we are again convert the given data into

normal form(readable form)

un-pickling is "not a safe process, we never perform generally

due to we do not know the source"

generally, when we are performing "pickling", it is used when

we send the data over a network

to implement the pickling and un-pickling in python we will


use a module called "pickle"

syntax for pickle module:


====================

import pickle as ple

in this module, we will have two functions:


=================================

1.dump()===>it is used to "perform pickling"

2.load()====>it is used to "perform un-pickling"

generally ,pickle file is a "binary file" and it's extension is ".pkl"

example-1:
=========

#example for python pickling


import os
import pickle as ple
#get the current working directory path
print(os.getcwd())
with open("sample.pkl","wb") as fp:
data={"name":"Ram","location":"hyderabad","salary":10000}
ple.dump(data,fp)

example-2:
=========

#example for python un-pickling


import os
import pickle as ple
#get the current working directory path
print(os.getcwd())
with open("sample.pkl","rb") as fp:
data=ple.load(fp)
print(data)

json , time and datetime module:


==========================

time module:
==========

this module is used in python,to work with time related tasks in

program

to work with this module, we will use the following syntax:


=============================================

import time as t
this module will have the following important functions:
============================================

1.sleep()<== it used to make the program execution will halt

or pause for given time slice/period in the sleep

function

import time as t

t.sleep(time_period)

example:
=======

import time as t
for i in range(1,11):
t.sleep(3)
print(i)

2.time() and localtime():


===================

time() function will give the current time an date in the seconds

localtime() is used to convert the given seconds time to "user"

under standable format

example:
=======
import time as t
#get the time in seconds
seconds=t.time()
print(seconds)
#convert the seconds into time
result=t.localtime(seconds)
print(result)
print(result.tm_year)
print(result.tm_mon)
print(result.tm_mday)
print(result.tm_hour)
print(result.tm_min)
print(result.tm_sec)
print(f"{result.tm_year}/{result.tm_mon}/{result.tm_mday}")

4.ctime():
========

using this ,we can able to get convert the given seconds time

into human readable form

example:
========

import time as t
#get the time in seconds
seconds=t.time()
print(seconds)
#convert the seconds into time usinf ctime()
result=t.ctime(seconds)
print(result)

5.process_time():
=============

this function is used to calculate a "process(program) is

executed in how much time or the time taken by the cpu,to

execute a process"

example:
=======

import time as t
#start time
start=t.process_time()
#logic
for i in range(1,10):
t.sleep(0.3)
print(i)
#end-time
end=t.process_time()
print(f"result:{start-end}")

6.perf_counter():
=============

this function is used to calculate the "overall performance of

the given code/program" in python

generally, it is used in the "testing", how the given is executing

in different conditions with respect to time

example:
=======

import time as t
#start time
start=t.perf_counter()
#logic
for i in range(1,10):
t.sleep(0.3)
print(i)
#end-time
end=t.perf_counter()
print(f"result:{end-start}")

7.strf_time():
==========

it is used to format the given time and date in the user defined

way

strf_time() is a "time and date formatting function"

when we are using this function, it will uses "format spesifiers

to represent the date and time "

example:
=======

import time as t
#get the time in seconds
seconds=t.time()
#convert the seconds into human readble form
result=t.ctime(seconds)
print(result)
print(t.strftime("%d"))
print(t.strftime("%m"))
print(t.strftime("%Y"))
print(t.strftime("%H"))
print(t.strftime("%M"))
print(t.strftime("%S"))
print(t.strftime("%d/%m/%Y"))
print(t.strftime("%H:%M:%S"))

datetime module:
==============

using this module we can able manipulate the both date and

time

in this module,we will have the following three classes:


===========================================

1.date class

2.time class

3.timedelta class

example-1:
=========

from datetime import date


date1=date(2021,3,3)
print(date1)
#get the current data using today() function of date class
today_date=date.today()
print(today_date)
print(today_date.day)
print(today_date.month)
print(today_date.year)
example-2:
=========

from datetime import time


t=time(14,12,35)
print(t)
print(t.hour)
print(t.minute)
print(t.second)

example-3:
=========
from datetime import datetime,date,time
t=datetime.now()
print(t)
datetime2=datetime.combine(date(2024,7,9),time(15,20,20))
print(datetime2)
print(t.strftime("%H"))
print(t.strftime("%d"))
print(t.strftime("%m"))
print(t.strftime("%Y"))
print(t.strftime("%H"))
print(t.strftime("%M"))
print(t.strftime("%S"))
print(t.strftime("%d/%m/%Y"))
print(t.strftime("%H:%M:%S"))

example-4:
=========

from datetime import datetime,date,time


t=datetime(2024,7,9,15,15,45)
print(t)
d=date(2021,10,15)
print(d)
t=time(15,16,16)
print(t)

example-5:
=========

from datetime import datetime,timedelta


t=datetime(2024,7,9,15,15,45)
t1=datetime(2024,3,9,15,15,45)
print(t)
#working with time delta
result=t+timedelta(days=100)
print(result)
result=t-timedelta(days=100)
print(result)
result=t-timedelta(hours=2400)
print(result)
result2=t-t1
print(((result2.days)//30)+1)

example-6:
=========
from datetime import date,timedelta
t=date(2024,7,9)
t1=date(2024,3,9)
print(t)
print((((t-t1).days)//30)+1)

example-7:
=========

calculate the age of the person by taking year, month and day

as input from the user to till today.

code:
====
from datetime import date
year=int(input("enter the year"))
month=int(input("enter the month:"))
day=int(input("enter the day:"))
t=date(year,month,day)
t1=date.today()
if year>1900 and year<=2100:
if month>=1 and month<=12:
if day>=1 and day<=31:
print(f"{((t1-t).days//365)}years")
else:
print("please give the valid day number")
else:
print("please give valid month number")
else:
print("please give the valid year number")

sys module:
=========

this module is used to "work with system related jobs"

to import this module, we will use the following syntax:


===========================================

import sys

this will the following important functions:


=================================
1.getsizeof():
==========

it will return the "object memory size at memory in bytes"

this is a rough calculation or estimated size of the given

object

example:
========

import sys
a=10
b=1.234
c="hello"
print(sys.getsizeof(a))
print(sys.getsizeof(b))
print(sys.getsizeof(c))

2.sys.exit():
=========

this is function is used to stop the "program execution or

terminate the program execution"

example:
=======

import sys
for i in range(1,10):
if i>5:
sys.exit()
else:
print(i)
print("the value of i is:",i)

note:
====

in python ,we will also have built-in functions called "exit() and

quit()",to terminate the program execution.even os.exit() is not

in use in the latest verions

3.sys.version and sys.platform:


==========================

example:
=======
import sys
print(sys.platform)#platform name
print(sys.version)#python inpreter version

4.sys.argv:
=========

in python, we can also use "command line arguments"

generally,we will exeute any python code in two modes:


============================================

1.interactive mode

2.shell mode

command line arguments are arguments which are given at

command line while execution in command prompt

to run the any python code at command prompt, we will use


the following syntax:
=================================================

python file_name.py arg1 arg2 arg3,....argn

example-1:
=========

import sys
a=int(input("enter the value for a:"))
b=int(input("enter the value for b:"))
print(a+b)
print(sys.argv)#argv talks about command line arguments
print(type(sys.argv))
print(sys.argv[0])

example-2:
=========

import sys
print(sys.argv)#argv talks about command line arguments
for i in sys.argv[1:]:
print(i)

python memory management:


=======================

memory management means "memory allocation and

deallocation"

memory allocation means "allocating the memory to the python

objects"

memory deallocation means "removing the objects and making

the memory as free"

python supports "dynamic memory allocation"

giving the memory to the objects at run-time

in python, memory management will never done or manage by

the programmer or developer

in python, we will uses a concept called "garbage collector"

"garbage collector" is a program, which calls automatically for

every program, to manage the objects in the memory, garbage

collector will identifies every time in the program, which objects

are "used or unused", if any unused object find in the memory,


it simply remove, to remove the any object from the memory

python uses a concept called "reference counting"

any object reference count is zero, then garbage collector

simply remove the "object"

when a object keep on using in program, then the object

reference count will be "incremented"

when a object not keep on using in program, then the object

reference count will be "decremented"

when a object reference count is zero, then the object is

removed from the memory by the garbage collector

example-1:
=========

import sys
a=10
b=20
c=a
print(a,id(a))
print(b,id(b))
print(c,id(c))
print(sys.getrefcount(a))
print(sys.getrefcount(b))
print(sys.getrefcount(c))
d=a+b
print(sys.getrefcount(a))
e=a
print(sys.getrefcount(a))
f=b
print(sys.getrefcount(b))
print(sys.getrefcount(c))

example-2
========
import sys
a=10
print(sys.getrefcount(a))
b=20
c=a
d=1.234
print(sys.getrefcount(d))
g=a
b=c
print(sys.getrefcount(a))
print(sys.getrefcount(c))
print(sys.getrefcount(b))
print(sys.getrefcount(d))
result=d
print(sys.getrefcount(d))
#removing object using del
del b
print(sys.getrefcount(a))
del a
print(sys.getrefcount(c))

how to set the recursion limit for any program using python:
===============================================

recursion limit means "how many times a function can call

itself and we are setting the limit where maximum number of

times a function can call itself using recursion limit"

using recursion limit,we "Can able control the no of recursions"

for that python provides two fucntions in sys module,those are:

sys.getrecursionlimit()<=== it is used to get the recursion count

limit or depth

sys.setrecursionlimit()<=== it is used to set the recursion count

limit or depth(minimum:32)
example-1:
=========
import sys
print(sys.getrecursionlimit())
sys.setrecursionlimit(50)
print(sys.getrecursionlimit())

example-2:
=========

import sys
num=1
print(sys.getrecursionlimit())
sys.setrecursionlimit(100)
print(sys.getrecursionlimit())

python data structures:


==================

data structures are used to "organize the data in some form,

with data structure we can able perform any operation like

insertion, updation, deletion and retrieval become so efficient

in python, we will have the following data structures:


=========================================

1.list:
=====

when we are working with variable, variable can hold only one

value under single name

when we want to store "multiple values under single name", in

python we will use data structure called "list"

list is collection of objects under single name

list can have duplicate objects(values)

list can be empty

list can be mutable(we can able to perform insertion, update

and delete)

list can be sequence type(list can follow both indexing and

slicing like range() function)

list can be known as ordered collection(the way we store, in the

same way all values can be stored in list)

list can have any type of values/objects

list can have any number of values/objects

to create the list, in python we will use "[]" or list() constructor

example-1:
=========

l1=[1,2,3,4,5,6,7]
print(l1)
l2=[]
print(l2)
l3=[1,2,1,2,1,2]
print(l3)
l4=[1,2,3,4,1.2,3.4,5.6,7.8,"hello"]
print(l4)
l5=list(range(10,110,10))
print(l5)
l6=list("hello")
print(l6)
l7=list((1,))
print(l7)

example-2:
=========

"""print the list using for loop""""

l1=[1,2,3,4,5,6,7]
for i in l1:
print(i,end=" ")
print()
l4=[1,2,3,4,1.2,3.4,5.6,7.8,"hello"]
for i in l4:
print(i,end=" ")

example-3:
=========
"""indexing with lists in python"""
l1=[1,2,3,4,5,6,7]
print(l1[0])
print(l1[-1])
print(l1[4])
l7=[10,20,30,40,50,60,70,80,90,100]
print(l7[-1])
print(l7[4])
print(l7[3])
print(l7[9])

example-4:
=========
"""slicing with lists in python"""
l1=[1,2,3,4,5,6,7]
print(l1[0:])
print(l1[3:])
print(l1[:9])
print(l1[3:8])
l7=[10,20,30,40,50,60,70,80,90,100]
print(l7[-5:-1])
print(l7[4:-3])
print(l1[::-1])
print(l7[::-2])

operations on the lists:


==================

on list, we can able to perform the following operations:


============================================

1.insertion

2.updation

3.deletion

insertion on python lists:


====================

to perform insertion operation on the lists, python provides the

following functions:
=================================================

1.append()<=== it is used to insert the given element at end

2.insert(position, element)<== it is used to insert the given

element at given position


example-1:
=========

l1=[1,2,3,4,5,6,7]
l1.append(100)
print(l1)
l1.append(200)
print(l1)
l1.append(300)
print(l1)
l1.insert(2,2000)
print(l1)
l1.insert(1000,4000)
print(l1)
l1.insert(-10000,10000)
print(l1)

2.updation:
=========

to update the any element of the list, we will use "indexing"

based on the index, we will change the elements in the list

example:
=======

l1=[1,2,3,4,5,6,7]
l1[3]=300
print(l1)
l1[-1]=1000
print(l1)
l1[4]=600
print(l1)

3.deletion:
========

to delete the elements from the list, in python we will use the

following functions:
=================================================

1.pop()<=== it is used to remove the element from the end of

list

2.remove()<=== it is used to remove the element which is

given in the function

3.clear()<=== it is used to remove the all elements in the list

4.del keyword<== it is used to remove the element based on

index
example:
=======

l1=[1,2,3,4,5,6,7,8,9,10,100]
l1.pop()
print(l1)
l1.pop()
print(l1)
l1.pop(3)#it remove element at index 3
print(l1)
l1.remove(9)#it remove element 9
print(l1)
del l1[0]
del l1[2]
print(l1)
l1.clear()
print(l1)

other functions on list:


==================

1.index()<=== it used to find the given element index

example:
=======

l1=[1,2,3,4,5,6,7,8,9,10,100]
print(l1.index(1))
print(l1.index(100))
print(l1.index(5))

2.count()<=== it used to find the given element how many

times repeated in the list

example:
=======

l1=[1,2,3,4,5,6,7,8,9,10,100,1,5,100]
print(l1.count(1))
print(l1.count(100))
print(l1.count(5))
print(l1.count(1000))

3.sort()<=== it used to sort the given list either in ascending or

descending order
example:
========

l1=[1,2,3,4,5,-6,-7,-8,9,10,100,1,5,100]
l1.sort()#ascending order
print(l1)
l1.sort(reverse=True)#descending order
print(l1)

4.copy()<=== it is used to the given list


example:
=======
l1=[1,2,3,4,5,-6,-7,-8,9,10,100,1,5,100]
l2=l1.copy()
print(l2)

5.reverse()<=== it is used to reverse the list

example:
========

l1=[1,2,3,4,5,-6,-7,-8,9,10,100,1,5,100]
l1.reverse()
print(l1)

sorted():
=======

using this we can able to sort the given list data "either in

ascending order or descending order"

example:
=======

l1=[1,2,3,900600,-10,-23,90,87,654]
print(l1)
print(sorted(l1))
print(sorted(l1,reverse=True))

reversed():
========

it is a "built-in function" asn using this we can reverse all

elements in the list

example:
=======

l1=[1,2,3,900600,-10,-23,90,87,654]
print(l1)
print(list(reversed(l1)))

nested lists in python:


=================

nested list means we can create a "list inside another list"

example:
=======

l1=[[1,2,3,4],[5,6,7,8],[10,11,12,13]]
print(l1)
print(len(l1))#3
for i in l1:
print(i)
print(l1[0])#[1,2,3,4]
print(l1[1])#[5,6,7,8]
print(l1[2])#[10,11,12,13]
for i in l1:
for j in i:
print(j,end=" ")
print()
print(l1[2][3])
print(l1[1][3])

list comprehension in python:


=======================

it allows the programmer or developer can create the list from

given iterable (list,tuple,set,range(),string)

syntax:
=====

list_name=[variable_name for variable_name in iterable_name if condition]

example:
=======
l1=[i for i in range(10,110,10)]
print(l1)
l1=[i for i in "hello world"]
print(l1)
l1=[i for i in (1,2,3,4,5,6,7,8,9,10)]
print(l1)
l1=[i for i in {1,2,3,4,5,6,7,8,9,10}]
print(l1)
l1=[i for i in [1,2,3,4,5,6,7,8,9,10]]
print(l1)
l1=[i for i in range(1,11) if i%2==0]
print(l1)
l1=[[j for j in range(1,i+1)] for i in range(2,11,2)]
print(l1)

extend():
=======

using this we can merge the two lists in python

using "+" operator we can merge the two lists

example:
=======
l1=[i for i in range(10,110,10)]
l2=[i for i in "hello world"]
print(l1+l2)
l1.extend(l2)
print(l1)

the following are the important list functions/methods:


============================================

len(), list(), count(), index(), insert(), append(), pop(), remove()


clear(), sort(), copy(), reverse(), sorted(), reversed(), extend()

2.tuple:
======
when we want to store "multiple values under single name", in

python we will use data structure called "tuple" like list

tuple is collection of objects under single name

tuple can have duplicate objects(values)

tuple can be empty

tuple can be immutable(we can not able to perform insertion,

update and delete)

tuple can be sequence type(tuple can follow both indexing and

slicing like range() function)

tuple can be known as ordered collection(the way we store, in

the same way all values can be stored in tuple)

tuple can have any type of values/objects

tuple can have any number of values/objects

to create the tuple, in python we will use "[]" or list() constructor

example:
=======
t1=()
print(t1)#empty tuple
t1=(1,2,3,4,5,6,7,8,9,10)
print(t1)
t2=(1,2,3,4,12.34,5.678,9.0123)
print(t2)
t3=(1,2,3,1.234,"hello","hai")
print(t3)
t4=tuple(range(1,10,3))
print(t4)
t5=1,2,3,4,5,6,7,8,9,10,11
print(t5)
t6=1,2,3,1.345,"abc","hello"
print(t6)
print(t2[0])
print(t2[-1])
print(t3[1:5])

the following functions we can apply on tuple in python:


============================================

1.index()<=== it is used to find the given element index in tuple

2.len()<=== it is sued to find the number of elements in tuple


3.count()<=it is used to find the given element is how many

times repeated
4.sorted()<=== it used to tuple elements in the form of list

5.reversed() <== it used to reverse tuple elements in the form

of list

example:
=======
t1=(10,20,30,40,50,60,70,80,90,100)
print(t1)
print(t1.index(100))
print(t1.index(30))
print(t1.index(60))
print(t1.count(10))
print(t1.count(100))
print(t1.count(1000))
print(sorted(t1,reverse=True))
print(tuple(reversed(t1)))
print(len(t1))
t2=list(t1).copy()
print(t2)

nested tuples:
===========

example:
=======

t1=((10,20,30,40),(50,60,70),(80,90,100))
print(t1)
print(t1[0])
print(t1[1])
print(t1[2])
for i in t1:
print(i)
print(len(t1))#3
print(t1[2][2])

tuple into list, set:


===============

example:
=======
t1=((10,20,30,40),(50,60,70),(80,90,100))
print(list(t1))
print(set(t1))
print(tuple([1,2,3,4,5]))
print(tuple({1,2,3,4,5}))

3.string:
=======

string is used to "Store the collection of characters"

in python, string is stored in single/double/triple quotes


string can be empty

string can have any type of data

string is immutable in python(we can not update, insert, delete)

string is sequence type(it follows both indexing ans slicing like

list or tuple)

string is a ordered collection(the way we give in the same it

can store in the memory)

to create the string in python, we will use single/double or

triple quotes or str() constructor

if string is created using triple quotes, then the string is known

as "doc string"

example-1:
=========

s1=""
s2='hello'
s3="hello world"
s4='''hello'''
s5="""hello"""
print(s1)
print(s2)
print(s3)
print(s4)
print(s5)
for i in s3:
print(i)

example-2:
=========
s3="hello world"
print(s3[0])
print(s3[-1])
print(s3[5])
print(s3[-5])
print(s3[4:])
print(s3[:6])
print(s3[-5:-2])
print(s3[::-1])

the following are the important functions o string:


=======================================

1.len()===>it is used to find the "number of characters in the

string"

2.count()===>it is used to "count the given chracter is


repeated how many times in the string"

3.index()===>it is used to "find the given character index"

4.lower()==>it is used to convert the given string characters

into lower case

5.upper()===>it is used to convert the given string characters

into upper case

6.swapcase()===>it is used to convert the lower to upper or

upper to lower in the string chracters

7.find()===>it is used to check given string is there or not

if the string is there, it simply return string starting

index, otherwise "-1"

8.isupper()==>it is used to check all "characters of the string

are uppercase or not"

if all are uppercase, it will return "True"

if all are lower case, it will return "False"

9.lstrip()===>it is used to "remove the spaces or any given

character from the begin or left side or starting

of the string

10.rstrip()===>it is used to "remove the spaces or any given

character from the end or right side or ending

of the string

11.strip()===>it is used to "remove the spaces or any given

character from the begin and end or left side and

right side or starting and ending of the string

strip()=lstrip()+rstrip()

12.replace()===>it used to replace the given string in the string

13.islower()===>it used to check "all characters of the string are


lower case or not"

if all are lower case, then it return True

other wise, it return False

14.isdigit()==>it used to check "all characters of the string

are digits or not"

if all are digits, then it return True

other wise, it return False

15.isalpha()==>it used to check "all characters of the string

are alphabets or not"

if all are alphabets, then it return True

other wise, it return False

16.isalnum()==>it used to check "all characters of the string

are digits and alphabets or not"

if all are digits and alphabets, then it return

True

other wise, it return False

17.isidentifier()==>it used to check "all characters of the string

are digits and alphabets and underscore or not"

if all are digits and alphabets, then it return

True

other wise, it return False

18.isspace()==>it used to check "all characters of the string

are spaces or not"

if all are spaces, then it return True

other wise, it return False

19.istitle()==> it used to check "starting character or first

character of the each word of the string is


upper case or not"

if each word starting character is upper case,

then it return True

other wise, it return False

20.title()===>this function will make "each word of the string,

starting character is "uppercase"

21.capitalize()===>this function will make "the starting

character of the string is uppercase"

22.join()===>it will join the "given character" in the string,after

every character of the string,it will work only

character data

23.split()===>it used to break the string into "n" number of

substrings based on the given delimeter

24.startswith()==>it is used to check the given string is starting

string or not in the string

if it is the starting string, function will return

"True"

25.endswith()==>it is used to check the given string is ending

string or not in the string

if it is the starting string, function will return

"True"

example-3:
=========
s3="hello world hello hello"
print(len(s3))
print(len(''))
print(len(" "))
print(s3.lower())
print(s3.upper())
print(s3.swapcase())
print(s3.count("hello"))
print(s3.index("hello"))
print(s3[0].upper()+s3[1:])

example-4:
=========
s3="hello world hello hello"
s4=s3[::-1]
print(s3)
print(s4)
s2="hello world hello world"
print(s2.replace("hello","Hello",1))
s1=" hellp"
print(s1)
print(len(s1))
s1=s1.lstrip()
print(s1)
print(len(s1))
s1="hello "
print(s1)
print(len(s1))
s1=s1.rstrip()
print(s1)
print(len(s1))
s1=" hello "
print(len(s1))
s1=s1.strip()#lstrip()+rstrip()
print(s1)
print(len(s1))

example-5:
=========

s3="hello hello world hello hello"


s3=s3.lstrip("hello")
print(s3)
s3="hello world hello hello"
s3=s3.rstrip("hello")
print(s3)
s3="hello world hello hello"
s3=s3.strip("hello")
print(s3)

example-6:
=========

s3="hello hello world hello hello"


print(s3.find("hello"))
print(s3.find("z"))
print(s3.find("Hello"))
print(s3.find("world"))
print(s3.islower())
print("Hello".islower())
print(s3.isupper())
print("HELLO".isupper())
print("1234".isdigit())
print("h1234".isdigit())
print("hello".isalpha())
print("hello234".isalpha())
print("hello1234".isalnum())
print("hello1234#".isalnum())

example-7:
=========

s3="hello hello world hello hello"


print(s3.isspace())
print(" ".isspace())
print(s3.title())
print(s3.capitalize())
print(s3.istitle())
print("Hello World".istitle())
print(s3.startswith("hello"))
print(s3.startswith("world"))
print(s3.endswith("world"))

example-8:
=========

s3="hello hello world hello hello"


print(" ".join(s3))
print("".join(s3))
print("-".join(s3))
print(s3.split(" "))
print(s3.split("o"))
print(s3.split(" ",2))
print(s3.split(" ",1))

example-9:
=========

h1="i am from india"


print(h1.split())
print(h1.split(" ",1))
print(h1.split(" ",2))
print(h1.split("f"))
print("-".join(h1))
print("123".join(h1))

example-10:
==========

write a python program to remove the duplicate digits in the

given number

example:
=======
11223344678====>1234678

code:
====

num=int(input("number:"))
res=''
for i in str(num):
if i not in res:
res+=i
print(res)

write a python program "to remove the duplicate elements in


the list"

example:
=======

[1,2,3,4,5,6,10,2,3,4,5,6,7,8]

ouput:
======

[1,2,3,4,5,6,10,7,8]

code:
====

l1=[1,2,3,4,5,6,10,2,3,4,5,6,7,8]
res=[]
for i in l1:
if i not in res:
res+=[i]
print(res)

write a python program to "add the element into list at given

position, without using any built-in function"


================================================

code:
====
l1=[10,20,30,40,50,60,70,80]
pos=int(input("enter the position:"))
ele=int(input("enter the element:"))
if pos<=len(l1):
l1=l1[:pos-1]+[ele]+l1[pos-1:]
print(l1)
else:
print("given position is out of the range")

4.set:
=========
set is a "collection of unique or distinct elements"

set can be empty

set will never duplicate elements like list or tuple

set can store any kind of elements

set can mutable(we can able to peform insert,update and delete)

set can not follow indexing and slicing like list or tuple
set is a un-orderd collection(it will not store the element in

any order, the way we given in the set)

set can be any size

on sets, we will perform the following operations:


=======================================

1.union

2.intersection

3.difference(complement)

4.symmetric difference

5.comparision of the sets

in python,we can also have "Frozen set",in this we can able

to store elements same like set, but frozen set is a immutable

to create the set, we will use {} or set() foncstructor

to create the frozen set, we will use "frozenset()" function

example-1:
=========

s1={1,2,3,4,5,6,7,8,9,10}
s2={}
s3={1,2,3,1.2,3.56,"hello","hai"}
s4={1,2,1,2,1,2}
s5=set()
print(s1)
print(s2)
print(s3)
print(s4)
print(len(s1))
print(len(s3))
print(type(s2))
print(type(s5))
print(type(s1))
print(len(s5))

example-2:
=========

"""sets with for loop"""


s1={1,2,3,4,5,6,7,8,9,10}
for i in s1:
print(i)
#set comprehension
s1={i for i in range(1,10)}
print(s1)
print(type(s1))
example-3:
=========
"""set operations """
s1={1,2,3,4,5,6,7,8,9,10}
#insertion
s1.add(100)
s1.add(200)
s1.add(300)
print(s1)
s1.update({10,20,30})
print(s1)
s1.update((11,12,13))
print(s1)

example-4:
=========

"""set operations """


s1={1,2,3,4,5,6,7,8,9,10}
#deletion
"""
in the case of discard(),if element
is not there,it simply ignore,but not
give any error like remove()
"""
s1.discard(10)
print(s1)
s1.discard(3)
print(s1)
s1.discard(100)
print(s1)
s1.remove(6)
print(s1)
s1.clear()#it will remove all elements
print(s1)

example-5:
========

"""set operations """


s1={1,2,3,4,5,6,7,8,9,10}
s2={4,5,6,7,10,11,12,13,14}
#union
#union using "|"
print(s1|s2)
#union using "union()"
print(s1.union(s2))
#union using list() or tuple() with set()
print(set(list(s1)+list(s2)))
print(set(tuple(s1)+tuple(s2)))

example-6:
=========

"""set operations """


s1={1,2,3,4,5,6,7,8,9,10}
s2={4,5,6,7,10,11,12,13,14}
#intersection
#intersection using "&"
print(s1&s2)
#intersection using "intersection()"
print(s1.intersection(s2))
#intersection using "intersection_update()"
s2.intersection_update(s1)
print(s2)

example-7:
=========

"""set operations """


s1={1,2,3,4,5,6,7,8,9,10}
s2={4,5,6,7,10,11,12,13,14}
#difference
#intersection using "-"
print(s1-s2)
#intersection using "difference()"
print(s2.difference(s1))
#intersection using "difference_update()"
s1.difference_update(s2)
print(s1)

example-8:
=========

"""set operations """


s1={1,2,3,4,5,6,7,8,9,10}
s2={4,5,6,7,10,11,12,13,14}
#symmetric difference
#symmetric difference using "^"
print(s1^s2)
#intersection using "symmetric_difference()"
print(s2.symmetric_difference(s1))
#intersection using "symmetric_difference_update()"
s1.symmetric_difference_update(s2)
print(s1)

example-9:
=========

print({1,2,3,4,5}>{6,7,8,9})
print({1,2,3,4,5,6,7,8,9}>{6,7,8,9})
print({6,7,8,9}<{1,2,3,4,5,6,7,8,9,10,11,12})
print({6,7,8,9}<{1,2,3,4,5,6,10})
print({1,2,3,4}=={4,3,2,1})

example-10:
==========
print({1,2,3,4,5}.issuperset({6,7,8,9}))
print({1,2,3,4,5,6,7,8,9}.issubset({6,7,8,9}))
print({6,7,8,9}.issubset({1,2,3,4,5,6,7,8,9,10,11,12}))
print({6,7,8,9}.isdisjoint({1,2,3,4,5,6,10}))
print({1,2,3,4}.isdisjoint({14,13,21,11}))
5.dictionary

6.array from python array module

16.exception handling

You might also like