0% found this document useful (0 votes)
8 views97 pages

Python Notes

The document outlines a syllabus for learning Python programming, covering topics such as features, data types, operators, and object-oriented programming concepts. It includes detailed explanations of Python's syntax, data structures, and various operators, along with example programs for practical understanding. Additionally, it provides exercises for hands-on practice with input/output formatting and arithmetic operations.

Uploaded by

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

Python Notes

The document outlines a syllabus for learning Python programming, covering topics such as features, data types, operators, and object-oriented programming concepts. It includes detailed explanations of Python's syntax, data structures, and various operators, along with example programs for practical understanding. Additionally, it provides exercises for hands-on practice with input/output formatting and arithmetic operations.

Uploaded by

nijammawa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Syllabus

1. Features of python
2. Tokens
3. Data types
4. Operators
5. Type conversion (Type casting)
6. Conditional statements
7. Looping statements
8. Jumping statements
9. List
10. Strings
11. Sets
12. Tuples
13. Dictionaries
14. Functions

OOPS PYTHON
“object oriented programming structure”
1. Class
2. Object
3. Constructors
4. Inheritance
5. Polymorphism
6. Data Encapsulation
7. Abstract class &Abstract Method
8. [Link] Handling
1. Features of python
1. Its is a object oriented programming language because in python we are having class,
object ,inheritance.
2. It is a high level language ,because now a days what the programming language we
have to done all the are consider ae a high level language.
3. In python there is “NO COMPAILATION PROCESS” because an interpreter will execute
the program line by line [in C language the compiler can compiler the entire program
at a time
4. Coding is very simple(compare to C )
5. In python there is no data type declaration ,because at the time a of execution an
interpreter will decide based on the value; that which data type
Ex: a=0 [python]
Int a=10 [C]
6. it is a case-sensitive
Ex: Breakwrong
break correct
7. python is a “plat form independent” because in any operating system in python will
work like, windows, …etc.
8. it is a “GUI” (graphical user interface).
1. How to write and execute the program in python.
2. Tokens
Def: it is a smallest unit of any programming language.
NAME = SRIDHAR

STD = [Link]

AGE = 20

HAVE_A ADHAR = TRUE

Print ( name, std , age, have_aadhar)

1. Identifiers (variables)
A python identifiers is a “name” used to identify a variable, function, class, module or other object.

Rules :

I. It is mode up letters , special character.

II. First character should not be a number

Ex:

III. It must not be a key word.

IV. We can not use special symbols expect underscore ( _ ).

Ex:

2. Literal :Literal is “raw data” given in a variable are constant.

Types of literals:

a) Numerical literals

b) String literals

c) Boolean literals

d) Special literals
3. Punctuators

Punctuator are symbols that are used in programming languages to organize sentence and

programming structure.

4. Key words

1. None 20. Del

2. True

3. False 21. class

4. And 22. Non local

5. Or 23. Global

6. Not 24. except

7. Is 25. Try

8. In 26. As

9. If 27. Assert

10. Else 28. with

11. Elif 29. from

12. For 30. import

13. While 31. yield

14. Break 32. raise

15. Continuous [Link]

16. Pass

17. Def

18. Return

19. Lambda
3.D ATA TYPES

Python Supports the Dynamic data type. that is at the time of execution of program

Data type of threat of a variable will be decided based on the data which is assigned to that

variable.

“ Static”at the time of Compilation (in'c').

*** It is used to Specified what type of data has to be Stored into the variable. There

are 3 types of data types There are,

1. None (null)

2. Numeric data type

I. int ( integer )

II. Float

III. Complex

IV. Bool (Boolean)

1. Sequence data type:

I. List

II. String

III. Set Dictionary Tuple


Data types:
Python has following standard Data Types:

1. Int
 Integer, is a whole number, positive or negative, without decimals, of unlimited
length.
 It is Immutable (un- changeable)
Example:
i=45
type(i)
<class 'int'>
print(i)
45

2. Float
 “Floating point number" is a number, positive or negative, containing one or more
decimals.
 It is Immutable.
Example:
f=(45.5)
type(f)
<class 'float'>
print(f)
45.5
3. complex
 Complex numbers Form: x+yj
x: real part
y: imaginary part
 it is Immutable
Example:
cl=(45+77.7j)
type(cl)
<class 'complex'>
print(cl)
(45+77.7j)
[Link]
 Boolean: True or False
 It is Immutable
Example:
b=True
type(b)
<class 'bool'>
print(b)
True

[Link]
 List is a sequence of ordered homogeneous elements. Symbol: [ ]
 Supports indexing (positive, negative).
 It is Mutable

Example:
list=[10,20,30,40]
type(list)
<class 'list'>
print(list)
[10, 20, 30, 40]
6 . str
 Strings: combination of characters.
 Each character in string can be accessed by index.
 Positive index starts from ‘0’(left to right).
 Negative index starts from’-1’(right to left).
 It is Immutable
Example:
str="sridhar"
type(str)
<class 'str'>
print(str)
sridhar

[Link]
 tuple is a sequence of ordered heterogeneous objects
 Symbol: ( ) Supports indexing (positive, negative).
 It isimmutable
Example:
type(t)
<class 'tuple'>
print(t)
(45, 77, 10, 46)
[Link]
 Set is a collection of un- ordered elements.
 Symbol: { }
 Discards the duplicates
 It is mutable
Example:
s={11,23,35,65}
type(s)
<class 'set'>
print(s)
{65, 35, 11, 23}
[Link]
 Dictionaries are used for mapping (key,value) pairs.
 It is mutable.
Example:
d={1:'s',2:'r',3:'i'}
type(d)
<class 'dict'>
print(d)
{1: 's', 2: 'r', 3: 'i'}
4. Operators in python
Following are the basic operators in python
1. Arithmetic operators
2. Bitwise operators
3. Logical operators
4. Relational Operators
5. Assignment operators:
6. Special operators: Identity operators and Membership operators

Arithmetic operators:
 Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication and division.
OPERATOR NAME SYNTAX

+ Addition x+y

Subtraction x-y
-
Multiplication x*y
*
Division (float) x/y
/
Division (floor) x // y
//
Modulus x%y
%
Example program:

a=5
b=2
print('a+b=',a+b)
print('a-b=',a-b)
print('a*b=',a*b)
print('a/b=',a/b)
print('a//b=',a//b)
print('a**b=',a**b)
OPU

OUTPUT
a+b= 7
a-b= 3
a*b= 10
a/b= 2.0
a//b= 2
a**b= 25
Bitwise Operators:
 Bitwise operators acts on bits and performs bit by bit operation.
OPERATOR NAME SYNTAX

Bitwise AND x&y


&
Bitwise OR x|y
|
Bitwise NOT ~x
~
Bitwise XOR x^y
^
Bitwise right shift x>>
>>
Bitwise left shift x<<
<<
Example Program:
a=11
b=12
print('a&b=',a&b)
print('a|b=',a|b)
print('~a ',a)
print('a^b=',a^b)
print('a<<b=',a<<b)
print('a>>b=',a>>b)

OUTPUT:
a&b= 8
a|b= 15
~a 11
a^b= 7
a<<b= 45056
a>>b= 0
Logical Operators:
 Logical operators perform Logical AND, Logical OR and Logical NOT operations.
OPERATOR NAME SYNTAX

And Logical x and y


AND

Or Logical OR x or y

Not Logical not x


NOT

Example program:

a=10
b=5
print((a<b)and(a<b))
print((a>b)or(a>b))
print(not(a<b))

output:
False
True
True
Relational Operators:
 Relational operators compares the values. It either returns True or False
according to the condition
OPERATOR NAME SYNTAX

> Greater than x>y

< Less than x<y

== Equal to x == y

!= Not equal to x != y

>= Greater than or equal x >= y


to

<= Less than or equal to x <= y

Example Program:

a=10
b=5
print('a<b=',a<b)
print('a>b=',a>b)
print('a<=b=',a<=b)
print('a>=b is',a>=b)
print('a==b=',a==b)
print('a!=b=',a!=b)
output:
a<b= False
a>b= True
a<=b= False
a>=b is True
a==b= False
a!=b= True
Assignment operators:
 Assignment operators are used to assign values to the variables.
OPERATOR DESCRIPTION SYNTAX

= Assignment x=y+z

Add AND: Add right side operand with left side operand and

+= then assign to left operand a+=b a=a+b

Subtract AND: Subtract right operand from left operand and then

-= assign to left operand a-=b a=a-b

Multiply AND: Multiply right operand with left operand and

*= then assign to left operand a*=b a=a*b

Divide AND: Divide left operand with right operand and then

/= assign to left operand a/=b a=a/b

Modulus AND: Takes modulus using left and right operands

%= and assign result to left operand a%=b a=a%b

Divide(floor) AND: Divide left operand with right operand

//= and then assign the value(floor) to left operand a//=b a=a//b

Exponent AND: Calculate exponent(raise power) value using

**= operands and assign value to left operand a**=b a=a**b

Performs Bitwise AND on operands and assign value to left

&= operand a&=b a=a&b

Performs Bitwise OR on operands and assign value to left

|= operand a|=b a=a|b

Performs Bitwise xOR on operands and assign value to left

^= operand a^=b a=a^b

Performs Bitwise right shift on operands and assign value to left

>>= a>>=b a=a>>b


operand

Special Operators:
 Identity Operators:
is and is not are the identity operators both are used to check if two values are located
on the same part of the memory. Two variables that are equal does not imply that
they are identical.

is True if the operands are identical


is True if the operands are not
not identical

Example program
a=10

b=5

print(a is b)

print(a is not b)

output
True

False

 Membership Operators:.
in and not in are the membership operators; used to test whether a value or
variable is in a sequence.

in True if value is found in the sequence


not True if value is not found in the
in sequence

Example program
a=' triveni '
b='indu'
print('a' in b)
print('i' not in b)
output
True

false
5. Type Conversion functions:
 Python defines type conversion functions to directly convert one data type to
another which is useful in day to day and competitive programming.
 Following are some conversion functions.
int(a, base) : This function converts any data type to integer. ‘Base’ specifies the base in
which string is if data type is string.
float() : This function is used to convert any data type to a floating point number

Program 1 :
(before type casting)
a=input("enter a number1")
b=input("enter a number2")
c=a+b
print(c)

output
enter a number1199
enter a number2111
199111

Program 2 :
(after type casting)
a=int(input("enter a number 1"))
b=int(input("enter a number 2"))
c=a+b
print(c)

output
enter a number 1100
enter a number 2200
300

ord() : This function is used to convert a character to integer.


hex() : This function is to convert integer to hexadecimal string.
oct() : This function is to convert integer to octal string.

Example program

a=int(input("enter a number 1"))


print(hex(a))

output
enter a number 156
0x38
num=int(input("enter a number 1"))
print(oct(num))

output
enter a number 118
0o22

num=input("enter a number")
print(ord(num))

output
enter a numbera
97

Hacker rank
 Print the output with a new line
Write a program to print the below-give output.

Case 1
Input (stdin)
Hello!
Welcome to Python Programming

Output (stdout)
Hello!
Welcome to Python Programming
 Write a program to get a float value from the user and display it in the below-
mentioned format.
INPUT & OUTPUT FORMAT:
Input consists of 1 float value.
Output must display the given input and also display the input with one, two and three
decimal points.
SAMPLE INPUT:
23.115
SAMPLE OUTPUT:
23.115000
23.115
23.11
23.1

Test case 1
Input
23.115
Output
23.115000
23.115
23.11
23.1

Test case 2
Input
345.67
Output
345.670000
345.670
345.67
345.7
 Round Off
Write a program to get a float value from the user and display it in the below-mentioned format.
HINT: Use ceil() and floor() functions from header file.
INPUT & OUTPUT FORMAT:
Input consists of one float value.
Output consists of one integer, its highest round off value and its lowest round off value.

Case 1
Input (stdin)
54.5

Output (stdout)
54
55.0
54.0

 Print ASCII Values


Write a program to generate the equivalent ASCII value for a given character.

Case 1
Input (stdin)
A

Output (stdout)
65

Case 2
Input (stdin)
a

Output (stdout)
97
 Arithmetic operator
Write a program to perform arithmetic operations such as addition, subtraction, multiplication,
modulo division and division.
INPUT & OUTPUT FORMAT:
Input consists of two integers
Output consist of integers

Case 1
Input (stdin)
5
2

Output (stdout)
7
3
10
1
2
25

Case 2
Input (stdin)
9
3

Output (stdout)
12
6
27
0
3
343

 Cricket Stadium
There was a large ground in center of the city which is rectangular in shape. The Corporation decides
to build a Cricket stadium in the area for school and college students, But the area was used as a car
parking zone. In order to protect the land from using as an unauthorized parking zone , the corporation
wanted to protect the stadium by building a fence. In order to help the workers to build a fence, they
planned to place a thick rope around the ground. They wanted to buy only the exact length of the rope
that is needed. They also wanted to cover the entire ground with a carpet during rainy season. They
wanted to buy only the exact quantity of carpet that is needed. They requested your help. Can you
please help them by writing a program to find the exact length of the rope and the exact quantity of
carpet that is required?
Input format:
Input consists of 2 integers. The first integer corresponds to the length of the ground and the second
integer corresponds to the breadth of the ground. Output Format:
Output Consists of two integers. The first integer corresponds to the perimeter. The second integer
corresponds to the quantity of carpet required.
Case 1
Input (stdin)
50
20
Output (stdout)
140
1000

Case 2
Input (stdin)
70
40
Output (stdout)
220
2800

 Dept Repay
Alice wanted to start a business and she was looking for a venture capitalist. Through her friend Bob,
she met the owner of a construction company who is interested to invest in an emerging business.
Looking at the business proposal, the owner was very much impressed with Alice's work. So he
decided to invest in Alice's business and hence gave a green signal to go ahead with the project. Alice
bought Rs.X for a period of Y years from the owner at R% interest per annum. Find the rate of
interest and the total amount to be given by Alice to the owner. The owner impressed by proper
repayment of the financed amount decides to give a special offer of 2% discount on the total interest
at the end of the settlement. Find the amount given back by Alice and also find the total amount.
(Note: All rupee values should be in two decimal points).
INPUT FORMAT:
Input consists of 3 integers. The first integer corresponds to the principal amount borrowed by Alice.
The second integer corresponds to the rate of interest The third integer corresponds to the number of
years.
OUTPUT FORMAT:
The output consists of 4 floating point values. The first value corresponds to the interest. The second
corresponds to the amount. The third value corresponds to the discount. The last value corresponds to
the final settlement. All floating point values are to be rounded off to two decimal places

Case 1
Input (stdin)
100
1
10
Output (stdout)
10.00
110.00
0.20
109.80
Case 2
Input (stdin)
10000
10
5

Output (stdout)
5000.00
15000.00
100.00
14900.00

 The newspaper Agency


Each Sunday, a newspaper agency sells w copies of a special edition newspaper for Rs.x per copy.
The cost to the agency of each newspaper is Rs.y. The agency pays a fixed cost for storage, delivery
and so on of Rs.100 per Sunday. The newspaper agency wants to calculate the profit which it obtains
only on Sundays. Can you please help them out by writing a program to compute the profit if w, x,
and y are given.
INPUT FORMAT:
Input consists of 3 integers: w, x, and y. w is the number of copies sold, x is the cost per copy and y is
the cost the agency spends per copy.
OUTPUT FORMAT:
The output consists of a single integer which corresponds to the profit obtained by the newspaper
agency.

Case 1
Input (stdin)
1000
2
1

Output (stdout)
900

Case 2
Input (stdin)
900
5
3

Output (stdout)
1700
 Four musketeers
'Artagnan joined the group of 3 Musketeers and now their group is called four Musketeers.
Meanwhile, d'Artagnan also moved to a new house in the same locality nearby to the other three.
Currently, the houses of Athos, Porthos and Aramis are located in the shape of a triangle. When the
three musketeers asked d'Artagnan about the location of his house, he said that his house is
equidistant from the houses of the other 3. Can you please help them find out the location of the
house? Given the 3 locations {(x1,y1), (x2,y2) and (x3,y3)} of a triangle, write a program to
determine the point which is equidistant from all the 3 points.
INPUT FORMAT:
Input consists of 6 integers. The first integer corresponds to x1. The second integer corresponds to y1.
The third and fourth integers correspond to x2 and y2 respectively. The fifth and sixth integers
correspond to x3 and y3 respectively.
OUTPUT FORMAT:
The output consists of two floating point numbers (with one decimal place) which correspond to the
location of the house.

Case 1
Input (stdin)
2
4
10
15
5
8

Output (stdout)
5.7
9.0

Case 2
Input (stdin)
1
1
1
1
1
1
1

Output (stdout)
1.0
1.0
 Treasure Hunter
Though there have been more successful pirates, Blackbeard is one of the best-known and widely-
feared of his time. He commanded four ships and had a pirate army of 300 at the height of his career
and defeated the famous warship, HMS “Scarborough” in sea-battle. He was known for barreling into
battle clutching two swords with several knives and pistols at the ready. He captured over forty
merchant ships in the Caribbean and without flinching killed many prisoners. Now, Blackbeard and
his three pirates found a treasure of gold coins. Long Ben too joined them. They decided to share the
treasure. Blackbeard agreed to give x% share for Long Ben. He then decided to take y% share from
the remaining treasure. His other pirates will share the remaining gold coins equally. Write a program
to compute their share's. INPUT FORMAT:
Input consists of 3 integers. The first input corresponds to the number of gold coins in the treasure.
The second input corresponds to Ben's share percentage and the last input is Blackbeard's share
percentage.
OUTPUT FORMAT:
The output consists of three integers. The first output integer corresponds to Long Ben's share. The
second integer corresponds to Blackbeard's share. The last integer corresponds to other pirates share.

Case 1
Input (stdin)
729
65
87

Output (stdout)
473
222
11
 Booka the alien
Booka is an alien. He couldn't understand how to measure days, weeks, months and years. Make
Booka understand what is meant by days, weeks, months and years. Teach him about the conversion
of days into years, months and weeks using a program.
INPUT FORMAT:
Input consists of an integer which corresponds to the number of days.
OUTPUT FORMAT:
The output consists of three integers. The first integer corresponds to the total years. The second
integer corresponds to the total months. The third integer corresponds to the total days.

Case 1
Input (stdin)
373

Output (stdout)
1
0
8

Case 2
Input (stdin)
365

Output (stdout)
1
0
0
Unit-2
[Link] Statements (or)Decision Making
Statements:
 Conditional statements in programming languages decides the direction of flow of
program execution.
 Conditional statements are also called as Decision making statements.
 if statement
 if-else statements
 nested if statements
 if-elif ladder
o

if statement:
 if statement is the simple decision-making statement.
 It is used to decide whether a certain statement or block of statements will be executed
or not i.e if a certain condition is true then a block of statement is executed otherwise
not.
Syntax:
if condition:
#statements (Or)
if(condition)
#statements

if statement accepts boolean values – if the value is true then it will execute the block of
statements below it otherwise not.
python uses indentation to identify a block. So the block under an if statement will be
identified as shown in the below example:

if (condition):
#statement1
#statement2
Example program
a=45
if a>30:
print('the given number is less')
print('number is found')
output
the given number is less
number is found
: if-else
 The if statement alone tells us that if a condition is true it will execute a block
of statements and if the condition is false it won’t.
 But what if we want to do something else if the condition is false. Here comes the else
statement. We can use the else statement with if statement to execute a block of code
when the condition is false.
 Syntax:
if (condition):
#statements
else:
#statements

Example programs :
 write a python program whether the given number is even or odd.

num=int(input("enter a number"))

if num%2==0:
print("the given number even")
else:
print("the given number odd")
print("program is over")

output
enter a number45
the given number odd
program is over

 write a python program whether the given number is +ve or –ve.

num=int(input('enter the number'))


if(num>0):
print('number1 is positive number')
else:
print('number2 is negative number')

OUTPUT:

enter the number5


number1 is positive number
enter the number-5
number2 is negative number
 write a python program whether the given number is leap year or not.

year=int(input("enter a year"))
if year%4==0:
print("its is leap year")
else:
print("its is not leap year")
print("program is over")

output:
enter a year2025
its is not leap year
program is over

 write a python program largest of two numbers.

num1=int(input("enter a number"))
num2=int(input("enter a number"))
if num1>num2:
print("num1 given number is less")
else:
print("num2 given number is high")
print(" program is over")

output
enter a number15
enter a number3
num1 given number is less
program is over

Nested if-else:
 A nested if is an if statement that is the target of another if statement.
 Nested if statements means an if statement inside another if statement.
Yes, Python allows us to nest if statements within if statements. i.e, we can
place an if statement inside another if statement.
 Syntax:
if (condition1):
if (condition2):
#statements
else:
#statements
Example program:
i=20
if i>0:
if i>15:
print("i is greater than 15")
else:
print("i is smaller than 15")
else:
print("i is negative number")

OUTPUT:
i is greater than 15

 if-elif-else ladder:
The if statements are executed from the top down. As soon as one of the
conditions controlling the if is true, the statement associated with that if is executed, and the
rest of the ladder is bypassed. If none of the conditions is true, then the final else
statement will be executed.
Syntax:
if (condition1):
#statements
elif
(condition2):
#statements
else:
#statements

Example program

Example:
i = 20
if (i == 10):
print ("i is 10")
elif (i == 15):
print ("i is 15")
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")

Output:
i is 20
Example program:
 write a python program based on age.

age=int(input("enter the age"))


if(age<18):
print("you are kid")
elif(age<30):
print("you are young")
elif(age<50):
print("you are middle age")
elif(age<70):
print("you are old")
else:
print("you are alive")
print("program is over")

output
enter the age20
you are young
program is over

 write a python program based on marks.

marks=int(input("enter the marks"))


if(marks<35):
print("you are fail")
elif(marks<50):
print("you are in C grade")
elif(marks<70):
print("you are in B grade")
elif(marks<80):
print("you are in A grade")
elif(marks<90):
print("you are in A+ grade")
else:
print("you are in pass")
print("program is over")

output:
enter the marks77
you are in A grade
program is over
[Link] Statements:
 Python programming language provides following types of loops to handle looping
requirements.
 while
 for
while loop:
 A while loop implements the repeated execution of code based on a given
Boolean condition.
 The code that is in a while block will execute as long as the while statement evaluates to True.
 As opposed to for loops that execute a certain number of times, while loops are
conditionally based, so we don’t need to know how many times to repeat the code going in.
 Syntax:
while (expression):
#statements
 Example:
count = 0
while (count < 3):
print("Hello Python")
count = count+1

Output:
Hello Python
Hello Python
Hello Python

EXAMPLE PROGRAMS
 Write a python program to print the odd numbers upto 20.
i=1
while(i<=20):
print(i)
i=i+2
print("loop is closed")

output:
1
3
5
7
9
11
13
15
17
19
loop is closed

 Write a python program to print the even numbers upto 20.


i=2
while(i<=20):
print(i)
i=i+2
print("loop is closed")

output:
2
4
6
8
10
12
14
16
18
20
loop is closed

1)WHILE:
Example 1: : write a python program whether the given number is armstrong or not.

num=int(input("enter a number"))
sum=0
temp=num
while (temp>0):
rem=temp%10
sum=sum+rem**3
temp=temp//10
if (sum==num):
print("it is a armstrong number")
else:
print("it is not a armstrong number")
Output:
enter a number153
it is a armstrong number
enter a number407
it is a armstrong number

Example 2: write a python program whether the given number is palindrome or not.

num=int(input("enter the number"))


rev=0
temp=num
while (temp>0):
rem=temp%10
rev=rev*10+rem
temp=temp//10
if (rev==num):
print("it is a palindrome number")
else:
print("it is not a palindrome number")

Output:
enter the number1221
it is a palindrome number
enter the number143
it is not a palindrome number

Example 3: write a python program whether the given number is spy or not.

num=int(input('enter a number:'))
sum=0
prod=1
temp=num
while(temp>0):
rem=temp%10
sum=sum+rem
prod=prod*rem
temp=temp//10
if sum==prod:
print('it is a spy number')
else:
print('it is not a spy number')
Output:
enter a number:132
it is a spy number
enter a number:1432
it is not a spy number

Example 5: write a python program whether the given number is neon or not.
num=int(input('enter a number:'))
sum=0
sqr=num**2
while(sqr>0):
rem=sqr%10
sum=sum+rem
sqr=sqr//10
if sum==num:
print('it is a neon number')
else:
print('it is not a neon number')

Output:
enter a number:9
it is a neon number
enter a number:23
it is not a neon number

Example 6: write a python program whether the given number is harshad or not.

num=int(input('enter a number:'))
sum=0
temp=num
while(temp>0):
rem=temp%10
sum=sum+rem
temp=temp//10
if num%sum==0:
print('it is a harshad number')
else:
print('it is not a harshad number')

Output:
enter a number:18
it is a harshad number
enter a number:81
it is a harshad number

Example7: write a python program whether the given number is perfect or not.

num=int(input('enter a number:'))
sum=0
i=1
while(i<=num//2):
if(num%i==0):
sum=sum+i
i=i+1
if sum==num:
print('it is perfect number')
else:
print('it is not a perfect number')

Output:
enter a number:6
it is perfect number
enter a number:32
it is not a perfect number

Example 7:
a=0
b=1
i=1
value=int(input("enter a given range"))
list=[0,1]
while(i<=value-2):
result=a+b
[Link](result)
a=b
b=result
i=i+1
print(list)

output:
enter a given range6
[0, 1, 1, 2, 3, 5]

Nested while
write a python program whether the given number is strong or not.
num=int(input("enter a number"))
sum=0
temp=num
while(temp>0):
i=1
fact=1
rem=temp%10
while(i<=rem):
fact=fact*i
i=i+1
sum=sum+fact
temp=temp//10
if(sum==num):
print("strong number")
else:
print("it is not strong number")

output
enter a number145
strong number

for loop:
 A for loop implements the repeated execution of code based on a loop counter or loop
variable.
 For loops are used most often when the number of iterations is known before entering the
loop, unlike while loops which are conditionally based.
 In Python, for loops are constructed like so:
 Syntax:
for iterating_var in sequence:
statements

 Example:
for i in range(0,5):
print(i)
Output
0
1
2
3
4

 This for loop sets up i as its iterating variable, and the sequence exists in the range of 0
to 5.
 Then within the loop we print out one integer per loop iteration. Keep in mind that in
programming we tend to begin at index 0, so that is why although 5 numbers are printed
out, they range from 0-4.
For Loops using range()
 One of Python’s built-in immutable sequence types is range().
 In loops, range() is used to control how many times the loop will be repeated.
 When working with range(), you can pass between 1 and 3 integer arguments to it:
1. start states the integer value at which the sequence begins, if this is not
included then start begins at 0
2. stop is always required and is the integer that is counted up to but not included
3. step sets how much to increase (or decrease in the case of negative numbers) the
next iteration, if this is omitted then step defaults to 1
 Example-1: range(stop)

for i in range(6):
print(i)

Output
0
1
2
3
4
5

Example programs

FOR:
EX:1 : print even number upto 20
for i in range(2,20,2):
print(i)

O/P:
2
4
6
8
10
12
14
16
18

EX:2 print even number upto 15

for i in range(1,15):
print(i)

O/P:
1
2
3
4
5
6
7
8
9
10
11
12
13
14

EX:3
for i in range(10):
print(i)

O/P:
0
1
2
3
4
5
6
7
8
9
 write a python program whether the given number is fascinating number or not.

num=int(input("enter a number"))
if num<100:
print("fasinating is not defined")
else:
result=str(num)+str(num*2)+str(num*3)
expected_list=['1','2','3','4','5','6','7','8','9']
if sorted(result)==expected_list:
print("it is fasinating number")
else:
print("it is not fasinating number")

output:
enter a number192
it is fasinating number

 write a python program to find factorial of given number.

num=int(input('enter a number:'))
fact=1
if num<0:
print('factorials are not defined by negative values')
elif num==0:
print('factorial of 0 is 1')
else:
for i in range(1,num+1):
fact=fact*i
print('factorial of',num,'is',fact)

output:
enter a number:5
factorial of 5 is 120

 write a python program to find the is fibonacci in a given range.

a=0
b=1
value=int(input("enter a given range"))
list=[0,1]
for i in range(value-2):
result=a+b
[Link](result)
a=b
b=result
print(list)

output:
enter a given range5
[0, 1, 1, 2, 3]

 write a python program to find the automarphic number or not.

num=int(input('enter the number'))


sqr=num**2
temp=sqr
if(temp>0):
rem=temp%10
sqr=temp//10
if num==rem:
print('it is automorphic')
else:
print('it is not a automorphic')

output:
enter the number5
it is automorphic

 write a python program to find the triomorphic number or not.


num=int(input('enter the number'))
temp=num
cube=num**3
flag=0
while(cube>0):
rem=cube%10
if num==rem:
flag=1
break
cube=cube//10
if flag==1:
print('triomorphic')
else:
print('not triomorphic')

O/P:
enter the number5
triomorphic
enter the number6
triomorphic
enter the number9
triomorphic

 write a python program to find the prime series in given range.

start=int(input('enter the value'))


end=int(input('enter the value'))
for i in range(start,end):
for j in range(2,i):
if i%j==0:
break
else:
print(i,end=",")

O/P:
enter the value10
enter the value40
11,13,17,19,23,29,31,37

 write a python program to find the given number is prime or not.

num=int(input('enter a number:'))
flag=0
for i in range(2,num):
if(num%i==0):
flag=1
break
if flag==1:
print('it is not a prime number')
else:
print('it is prime number')

O/P:
enter a number:5
it is prime number
enter a number:23
it is prime number
range function
a=0
b=1
value=int(input("enter the range:"))
x=[0,1]
for i in range(1,value-1):
result=a+b
[Link](result)
a=b
b=result
print(x)

O/P:
enter the range:4
[0, 1, 1, 2]
enter the range:7
[0, 1, 1, 2, 3, 5, 8]

For Loops using Sequential Data Types:


 Lists and other data sequence types can also be leveraged as iteration parameters in for
loops. Rather than iterating through a range(), you can define a list and iterate through that
list.
 Example:
cities = ['Hyderabad', 'Vizag', 'Bangalore', 'Chennai']
for city in cities:
print(city)

Output
Hyderabad Vizag
Bangalore
Chennai

Nested Loops:
 Loops can be nested in Python, as they can with other programming languages.
 A nested loop is a loop that occurs within another loop, structurally similar to nested
if statements.
 Syntax:

for iterating_var1 in outer_loop_seq: # Outer loop


Statements # Optional
for iterating_var in nested_loop_seq: # Nested loop
Statements

 The program first encounters the outer loop, executing its first iteration. This first iteration
triggers the inner, nested loop, which then runs to completion. Then the program returns
back to the top of the outer loop, completing the second iteration and again triggering the
nested loop.
 Again, the nested loop runs to completion, and the program returns back to the top of the
outer loop until the sequence is complete or a break or other statement disrupts the
process.

 Example-1:
num_list = [1, 2, 3]
alpha_list = ['a', 'b'] for
number in num_list:
print(number)
for letter in alpha_list:
print(letter)

Output:
1
a b 2
a b 3
a b

 Example-2:
list_of_lists = [['a', 'i', 'm'],[0, 1, 2],[9.9, 8.8, 7.7]]
for list in list_of_lists:
for item in list:
print(item)

Output:
a i m 0

1
2
9.9

8.8
7.7

Example: write a python program whether the given number is strong or not.

num=int(input("enter a number"))
sum=0
temp=num
while(temp>0):
i=1
fact=1
rem=temp%10
while(i<=rem):
fact=fact*i
i=i+1
sum=sum+fact
temp=temp//10
if(sum==num):
print("strong number")
else:
print("it is not strong number")

output:
enter a number145
strong number

[Link] Statements:(JUMPING
STATEMENT)
 Using for loops and while loops in Python allow you to automate and repeat tasks in an
efficient manner.
 But sometimes, an external factor may influence the way our program runs. When this occurs,
we may want our program to exit a loop completely, skip part of a loop before continuing, or
ignore that external factor. we can perform these actions with break, continue, and
pass statements.

break:
In Python, the break statement provides with the opportunity to exit out of a loop when an external
condition is triggered. We will put the break statement within the block of code under loop statement,
usually after a conditional if statement.
 It is used to terminate the loop.

*JUMPING STATEMENTS:
Example program:
1)BREAK:
for i in range(10):
if i==6:
break
print(i)
print('program over')

output:
0
1
2
3
4
5
program over

EX:2
num=int(input('enter a number:'))
flag=0
for i in range(2,num):
if(num%i==0):
flag=1
break
if flag==1:
print('it is not a prime number')
else:
print('it is prime number')

O/P:
enter a number:5
it is prime number
enter a number:23
it is prime number

continue:
 The continue statement gives the option to skip over the part of a loop where an external
condition is triggered, but to go on to complete the rest of the loop.
 That is, the current iteration of the loop will be disrupted, but the program will return to the
top of the loop.
 The continue statement will be within the block of code under the loop statement, usually
after a conditional if statement.
 We can use the continue statement to avoid deeply nested conditional code, or to
optimize a loop by eliminating frequently occurring cases that you would like to reject.
 The continue statement causes a program to skip certain factors that come up within a loop,
but then continue through the rest of the loop.

CONTINUE:
for i in range(10):
if(i==3):
continue
print(i)
print('sridhar')

O/P:
0
1
2
4
5
6
7
8
9
Sridhar

pass:
 When an external condition is triggered, the pass statement allows to handle the condition
without the loop being impacted in any way; all of the code will continue to be read unless a
break or other statement occurs.
 As with the other statements, the pass statement will be within the block of code under the
loop statement, typically after a conditional if statement.
PASS:
for i in range(1,10):
if i==5:
print('sridhar')
pass
print(i)
print('program over')

O/P:
1
2
3
4
sridhar
5
6
7
8
9
program over

Some example programs:


1. Write a python program to print multiplication table of given
number.

Program:
num=int(input('Enter any value:'))
print('multiplication table of',num,'is:') for i
in range(1,11):
print(num,'*',i,'=',num*i)

Output:
Enter any value:5 multiplication
table of 5 is:
5 *1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

2. Write a python program to print all even and odd numbers in


given range.

Program:
num=int(input('Enter any positive number:'))
even_list=[]
odd_list=[]
for i in range(0,num): if(i
%2==0):
even_list.append(i) else:
odd_list.append(i) print('Even
numbers are:',even_list) print('Odd
numbers are:',odd_list)
Output:
Enter any positive number:20

Even numbers are: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]


Odd numbers are: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

9. LIST
 Python lists are ordered sequences of items. For instance, a sequence of n numbers might be
called S:
S = s0, s1, s2, s3, …, sn-1

 A list or array is a sequence of items where the entire sequence is referred to by a single
name (i.e. s) and individual items can be selected by indexing (i.e. s[i]).
 Python lists are dynamic. They can grow and shrink on demand.
 Python lists are also heterogeneous, a single list can hold arbitrary data types.
 Python lists are mutable sequences of arbitrary objects.

CREATING A LIST:
 In Python programming, a list is created by placing all the items (elements) inside a
square bracket [ ], separated by commas.
 It can have any number of items and they may be of different types (integer, float,
string etc.).
Ex:
l=[]
type(l)
<class 'list'>
print(l)
[]
Ex
l=[10,20,30,40,50]
type(l)
<class 'list'>
print(l)
[10, 20, 30, 40, 50]
Ex
l=[10,"sridhar",4.5]
type(l)
<class 'list'>
print(l)
[10, 'sridhar', 4.5]
 Also, a list can even have another list as an item. This is called nested
Ex
l=[10,20,[1,2,3,4],30]
type(l)
<class 'list'>
print(l)
[10, 20, [1, 2, 3, 4], 30]
l[2]
[1, 2, 3, 4]
 List() Method To Create A List
 Python includes a built-in list() method.
 It accepts either a sequence or tuple as the argument and converts into a
Python list.
Ex:
List = list() empty list len(List)
0
ACCESSING ELEMENTS OF A LIST:
There are various ways in which we can access the elements of a list.
1. List Index
 We can use the index operator [] to access an item in a list. Index starts from 0. So, a list
having 5 elements will have index from 0 to 4.
Ex:
list = ['s','r','i','d','h'’a’,’r’]
print(list[0])
Output: s
print(list[2])
Output: i
print(ist[4])
Output: h
 Trying to access an element other that this will raise an Index Error. The index must be an
integer. We can't use float or other types, this will result into Type Error.
Ex:
list[4.0]Error! Only integer can be used for indexing
 Nested list are accessed using nested indexing.
Ex:
list = ["sridhar", [2,0,1,5]]
print(list[0][1])
Output: s
print(list[1][3])
Output: 5
 Python allows negative indexing (Reverse Indexing) for its sequences. The index of
-1 refers to the last item, -2 to the second last item and so on.
Ex:
List=['s','r','i','d','h',’a’,r’]
Print(list[-1])
Output: r

print(list[-5])
Output: i

3.2.1. OPERATIONS ON LISTS:


 Concatenation:
We can concatenate lists by using + or extend method.
Example:
list_a = [1, 2, 3, 4]
list_b = [5, 6, 7, 8]
list_c = list_a+lis_b
print list_c
Output: [1, 2, 3, 4, 5, 6, 7, 8]

Extend operator can be used to concatenate one list into another. It is not possible to store
the value into the third list. One of the existing list has to store the concatenated result.

Example:
list_c =list_a.extend(list_b) print
list_c
Output: NoneType

print list_a
Output: [1, 2, 3, 4, 5, 6, 7, 8]
print list_b
Output: [5, 6, 7, 8]

Slicing:
 Given a string s, the syntax for a slice is:
s[ startIndex : pastIndex ]
 The startIndex is the start index of the string. pastIndex is one past the end of the slice.
Ex:
List = [1, 2, 3, 4, 5, 6, 7, 8]
List[2:5]
Output
[3,4,5]
Since Python list follows the zero-based index rule, so the first index starts at 0.
 In slicing, if you leave the start, then it means to begin slicing from the 0th index.
Ex:
List[:2] [1, 2]
 While slicing a list, if the stop value is missing, then it indicates to perform slicing to the end
of the list. It saves us from passing the length of the list as the ending index.
Ex:
List[2:]
[3, 4, 5, 6, 7, 8]
 Reverse A Python List Using The Slice Operator
o It is effortless to achieve this by using a special slice syntax (::-1). But please remember that
reversing a list this way consumes more memory than an in-place reversal.
o Here, it creates a shallow copy of the Python list which requires long enough space for holding
the whole list.
Ex:
List[::-1]
[8, 7, 6, 5, 4, 3, 2, 1]
 Iteration:
 Python provides a traditional for-in loop for iterating the list. The for statement makes it super
easy to process the elements of a list one by one.
for element in List:
print(element)
 If you wish to use both the index and the element, then call the enumerate () function.
for index, element in enumerate(List): print(index,
element)
 If you only want the index, then call the range() and len() methods.
for index in range(len(List)):
print(index)
Ex:
List = ['Python', 'C', 'C++', 'Java', 'CSharp']

for language in List: print("I like", language)

Output –
I like Python I like C
I like C++ I like Java
I like CSharp

List methods:
 [Link](elem) -- adds a single element to the end of the list. Common error:
does not return the new list, just modifies the original.
 [Link](index, elem) -- inserts the element at the given index, shifting elements to
the right.
 [Link](list2) -- adds the elements in list2 to the end of the list. Using + or += on
a list is similar to using extend().
 [Link](elem) -- searches for the given element from the start of the list and
returns its index. Throws a ValueError if the element does not appear (use "in"
to check without a ValueError).
 [Link](elem) -- searches for the first instance of the given element and
removes it (throws ValueError if not present)
 [Link]() -- sorts the list in place (does not return it). (The sorted() function shown
later is preferred.)
 [Link]() -- reverses the list in place (does not return it)
 [Link](index) -- removes and returns the element at the given index. Returns the
rightmost element if index is omitted (roughly the opposite of append()).
 Examples:
AIR PIC SRCC
A  APPEND
I  INSERT
R REMOVE
P POP
I INDEX
C COPY
S SORT
R REVERS
C COUNT
C CLEAR
1)APPEND ( ): adds a single element to the end of the list.
Ex :
l=[10,20,30,40,50]
[Link](60)
print(l)
output:
[10, 20, 30, 40, 50, 60]

2)INSERT ( ): insert an element at a specified position


Ex:
l=[10,20,30,40,50]
[Link](2,"sridhar")
print(l)
output:
[10, 20, 'sridhar', 30, 40, 50]

3)REMOVE ( ): remove an element from the list.

EX:l=[1,2,3,4,5,6,7]

[Link](5)
l
output:
[1, 2, 3, 4, 6, 7]
4)POP ( ): remove and return an element at the specicfied position.

Ex:
l=[12,13,14,1516]
[Link](3)
1516
l
Output:
[12, 13, 14]

5)INDEX ( ): returns the indexof the first matched element.

Ex:
l=[21,22,23,34,45,67]
[Link](23)
2
[Link](67)
5

6)COUNT ( ): returns the number of elements with specified value.

Ex:
l=[11,22,33]
l=l*10
print(l)
[11, 22, 33, 11, 22, 33, 11, 22, 33, 11, 22, 33, 11, 22, 33, 11, 22, 33, 11, 22, 33, 11, 22, 33, 11, 22, 33, 11, 22,
33]
[Link](11)
output:
10

7)SORT ( ): sort the items in a list in ascending order.

Ex:
l=['s','r','i','d','h','a','r']
[Link]()
print(l)
output:
['a', 'd', 'h', 'i', 'r', 'r', 's']
8)REVERSE ( ): reverse the order of element in a list.

Ex:
l=['a', 'd', 'h', 'i', 'r', 'r', 's']
[Link]()
l
output:
['s', 'r', 'r', 'i', 'h', 'd', 'a']

9)COPY ( ): returns a copy of a list.


Ex:
l=[123456789]
[Link]()
l
output
[123456789]

10)CLEAR ( ): clear all the elements in a list .

Ex:
l=[123456789]
[Link]()
l
output
[]
functions of List

Function Description

Return True if all elements of the list are true (or if the list is empty).

list1=[1,2,3,4]
all()
list2=[10,11,0,14]

print(all(list1)) # True

print(all(list2)) #False

Return True if any element of the list is true. If the list is empty, return False.

any() list=[1,2,0,4]

print(any(list)
True
Return the length (the number of items) in the
len()
list. Print(len(list)) 4
Convert an iterable (tuple, string, set, dictionary) to a

list() list. t=(1,2,3,4)

print(list(t))
[1,2,3,4]
Return the largest item in the list.
max()
print(max(list)) 4

Return the smallest item in the list


min()
print(min(list)) 0

Return a new sorted list (does not sort the list

sorted() itself). list=[6,3,8,4,1]

print(sorted(list))
[1,3,4,6,8]
Return the sum of all elements in the list.
sum()
print(sum(list))

22

List comprehension:
Syntax:
l =[expression,[Link]]
 to find the squares up to 10
sqr=[i**2 for i in range(10)]
print(sqr)
output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

 to find the cubes up to 10


cube=[i**3 for i in range(11)]
print(cube)

O/P:
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
10. String
 A string is a sequence of characters.
 In Python, string is a sequence of Unicode character.
 Python strings are "immutable" which means they cannot be changed after they are
created.
CREATING STRINGS:
 Creating Strings is easy, and it is done simply by enclosing the characters in single or
double quotes.
 The strings in Python consider both single and double quotes as the same.
Ex:
String_var = 'sridhar' String_var =
"sridhar" String_var = """sridhar"""

ACCESSING CHARACTERS:
 Python allows to index from the zeroth position in Strings.
 But it also supports negative indexes. Index of ‘-1’ represents the last character of the String.
Similarly using ‘-2’ we can access the penultimate element of the string and so on. Example:

P Y T H O N – S T R I N G

0 1 2 3 4 5 6 7 8 9 10 11 12

-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

sample_str = 'Python String'


print (sample_str[0])
# return 1st characte output: P
print (sample_str[-1])
# return last character # output: g
print (sample_str[-2])
# return last second character # output: n

 To retrieve a range of characters in a String we use ‘slicing operator’, the colon ‘:’. With the
slicing operator, we define the range as [a:b].
sample_str = 'Python String'
print (sample_str[3:5])
#return a range of character # ho
print (sample_str[7:])
# return all characters from index 7 # String
print (sample_str[:6])
# return all characters before index 6
# Python
print (sample_str[7:-4]) # St

3.1.1. INVALID USAGE OF STRINGS:

1. If we try to retrieve characters at out of range index then ‘IndexError’ exception will be
raised.
Ex:
sample_str= "Python Supports Machine Learning."
print (sample_str[1024])
#index must be in range #
IndexError: string index out of range

2. String index must be of integer data type. You should not use a float or any other data type for
this purpose. Otherwise, the Python subsystem will flag a TypeError exception as it detects a
data type violation for the string index.
Ex:
sample_str = "Welcome post"
print (sample_str[1.25])
#index must be an integer
# TypeError: string indices must be integers

3.1.2. STRING OPERATORS

Operator Operation Description Example Code

+ Concatenation Combining two Strings into var1 = ‘sridhar’


one. var2 = ‘civil’
print (var1+var2)
# sridharcivil
* Repetition Creates new String by var1 = ‘Python’
repeating the String given print (var1*3)
number of times. # PythonPythonPython

[] Slicing Prints the character at given var1 = ‘Python’


index. print (var1[2])
#t

[:] Range Slicing Prints the characters present var1 = ‘Python’


at the given range . print (var1[2:5])
# tho

in Membership Returns ‘True’ value if var1 = ‘Python’


character is present in the print (‘n’ in var1)
given String. # True

not in Membership Returns ‘True’ value if var1 = ‘Python’


character is not present in print (‘N’ not in var1)
given String. # True

#t
#h
#o
#n
for Iterating Using for we can iterate var1 = 'Python'
through all the characters of for var in var1:
the String. print (var)
#P
#y

r/R Raw String Used to ignore the actual print (r’\n’)


meaning of Escape # \n
characters inside a string. print (R’\n’)
For this we add ‘r’ or ‘R’ in # \n
front of the String.

STRING FORMATTING OPERATORS:


1. Escape Characters.
 An Escape sequence starts with a backslash (\) which signals the compiler to treat it
differently. Python subsystem automatically interprets an escape sequence be it in a single
quoted or double quoted Strings.
 Suppose we have a string like –“Python is “widely” used language”.
 The double-quote around the word “widely” disguise python that the String ends up there.
 We need a way to tell Python that the double-quotes inside the string are not the string
markup quotes. Instead, they are the part of the String and should appear in the output.
 To resolve this issue, we can escape the double-quotes and single-quotes as:
Ex:
print ("Python is "widely" used language")
# SyntaxError: invalid syntax
# After escaping with double-quotes
print ("Python is \"widely\" used language")
# Output: Python is “widely” used language

Escape Character Used To Print


\\ Backslash (\)
\” Double-quote (“)
\a ASCII bell (BEL)
\b ASCII backspace (BS)
\cx or \Cx Control-x
\f ASCII Form feed (FF)
\n ASCII linefeed (LF)
\N{name} Character named name in the Unicode database (Unicode only)
\r Carriage Return (CR)
\t Horizontal Tab (TAB)
\uxxxx Character with 16-bit hex value xxxx (Unicode only)
\Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (Unicode only)
\v ASCII vertical tab (VT)
\ooo Character with octal value ooo
\xnn Character with hex value nn where n can be anything from the
range 0-9, a-f or A-F.
2. Python Format Characters ‘%’
 String ‘%’ operator issued for formatting Strings. This operator is used with print()
function.
print ("Employee Name: %s,\nEmployee Age:%d" % ('Ashish',25)) #
Employee Name: Ashish,
# Employee Age: 25
Format Symbol Conversion
%c Character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPER-case letters)
%e exponential notation (with lowercase ‘e’)
%E exponential notation (with UPPER-case ‘E’)
%f floating point real number
%g the shorter of %f and %e
%G the shorter of %f and %E

STRING METHODS
1)CAPITALZE():First letter capitalized in first word.

str="chithada sridhar civil branch"

print([Link]())

CHITHADA SRIDHAR CIVIL BRANCH

2)SWAPAGE():converts the lower cases into upper cases and vice versa.

str="chithada sridhar civil branch"

print([Link]())

CHITHADA SRIDHAR CIVIL BRANCH

3)REPLACE():replaces old value with new value.

str="chithada sridhar civil branch"

print([Link]('a','m'))

CHITHMDM SRIDHMR CIVIL BRMNCH

4)STARTSWITH():returns the boolean value

str="chithada sridhar civil branch"

print([Link]("chi"))

True

5)ENDSWITH():returns the boolean value

str="chithada sridhar civil branch"

print([Link]("nch"))

True
6)FIND():returns the index of the first occurrence of an element.

str="chithada sridhar civil branch"

print([Link]("h"))

7)RFIND():returns the index of the last occurrence of an element.

str="chithada sridhar civil branch"

print([Link]("i"))

20

8)COUNT():returns the no of occurrences in a string.

str="chithada sridhar civil branch"

print([Link]("a"))

9)ISALNUM():means alphabet numeric and returns a Boolean values

str="sridhar 22mt1ao102"

print([Link]())

FALSE

str="sridhar4577"

print([Link]())

TRUE

str="12345"

print([Link]())

TRUE

10)ISDIGIT():returns true if it is digit otherwise false.

str="6302974137"
print([Link]())

TRUE

11)ISALPHA():returns true if it is alphabets otherwise false.

str="sridhar"

print([Link]())

TRUE

12)ISSPACE():returns true if it is space otherwise false

str="chithada sridhar civil branch"

print([Link]())

FALSE

13)UPPER():

str="chithada sridhar civil branch"

print([Link]())

CHITHADA SRIDHAR CIVIL BRANCH

14)ISUPPER():returns true if it is space otherwise false

str="chithada sridhar civil branch"

print([Link]())

False

15)LOWER()

str="CHITHADA SRIDHAR CIVIL BRANCH"

print([Link]())

CHITHADA SRIDHAR CIVIL BRANCH

16)ISLOWER():checks the string is lower or not if it is returns true other wise false.
str="CHITHADA SRIDHAR CIVIL BRANCH"

print([Link]())

FALSE

17)JUSTIFY():

str="sridhar"

print([Link](16,"*"))

SRIDHAR*********

str="sridhar"

print([Link](16,"*"))

*********SRIDHAR

18)CENTER()

str="sridhar"

print([Link](16,"*"))

****SRIDHAR*****

19)STRIP():removes the spaces from left and right sides

str=" SRIDHAR "

print([Link]())

SRIDHAR

str=" SRIDHAR "

print([Link]())

SRIDHAR

20)JOIN(): it is used to join the element from the iterable.


str=["attitude","ka","bap","king"]

print(".".join(str))
[[Link],[Link]]

21)ZFILL():fills with zeros

str="sridhar"

print([Link](10))

000SRIDHAR

22)INDEX():returns the index of an element.

str="chithada sridhar civil branch"

print([Link]("a"))

print([Link]("z"))

Traceback (most recent call last):

File "<pyshell#55>", line 1, in <module>

print([Link]("z"))

ValueError: substring not found

23)ISDECIMAL():returns true if it is digit otherwise false

str="45.7"

print([Link]())

FALSE

24)LENGTH MAX():

str="chithada sridhar civil branch"


print(max(str))

25)LENGTH MIN():

str="1235"

print(min(str))

1
11. Set
Sets:
 A set is an unordered collection of items. Every element is unique (no
duplicates) and must be immutable (which cannot be changed).
 However, the set itself is mutable. We can add or remove items from it.
 Sets can be used to perform mathematical set operations like union, intersection, symmetric
difference etc.
Creating a set:
 A set is created by placing all the items (elements) inside curly braces {}, separated by comma or
by using the built-in function set().
 It can have any number of items and they may be of different types (integer, float, tuple, string
etc.). But a set cannot have a mutable element, like list, set or dictionary, as its element.
set of integers
set = {1, 2, 3}
set of mixed datatypes
set = {1.0, "Hello", (1, 2, 3)}
set do not have duplicates
set = {1,2,3,4,3,2}
print(set)
o/p:{1, 2, 3, 4

set cannot have mutable items, here [3, 4] is a mutable list


set = {1, 2, [3, 4]}

we can make set from a list


set = set([1,2,3,2])
print(set)
o/p:{1, 2, 3}

Creating an empty set:


 Empty curly braces {} will make an empty dictionary in Python. To make a set without any
elements we use the set() function without any argument.

# initialize a with {}
a = {}
# check data type of a
# Output: <class 'dict'>
print(type(a))

# initialize a with set()


a = set()
# check data type of a #
Output: <class 'set'>
print(type(a))

Changing a set:
 Sets are mutable. But since they are unordered, indexing have no meaning.
 We cannot access or change an element of set using indexing or slicing. Set does not support it.
 We can add single element using the add() method and multiple elements using the update()
method. The update() method can take tuples, lists, strings or other sets as its argument. In all
cases, duplicates are avoided.

# initialize set
set = {1,3}
print(set)
add an element
Output: {1, 2, 3}
[Link](2)
print(set)

add multiple elements #


Output: {1, 2, 3, 4}
[Link]([2,3,4])
print(set)

add list and set


Output: {1, 2, 3, 4, 5, 6, 8}

removing elements from a set:


 A particular item can be removed from set using methods, discard() and remove().
 The only difference between the two is that, while using discard() if the item does not exist in the
set, it remains unchanged. But remove() will raise an error in such condition.
 The following example will illustrate this.

set = {1, 3, 4, 5, 6}
print(set)
discard an elemen
Output: {1, 3, 5, 6}

[Link](4)
print(set)
remove an element
Output: {1, 3, 5}

[Link](6)
print(set)
discard an element
not present in set
Output: {1, 3, 5}

[Link](2)
print(set)

 Similarly, we can remove and return an item using the pop() method.
 Set being unordered, there is no way of determining which item will be popped. It is
completely arbitrary.
 We can also remove all items from a set using clear().
initialize my_set
Output: set of unique elements
set = set("HelloWorld")
print(set)
pop an element
Output: random element
print([Link]())

pop another element


Output: random element
[Link]()
print(set)

clear set
Output:set()
[Link]()
print(set)

Python Set Operations:


Sets can be used to carry out mathematical set operations like union, intersection, difference and
symmetric difference. We can do this with operators or methods.
Operation Symbol Method Description
Union | union() Union of A and B is a set of all elements from
both sets.
Intersection & intersection() Intersection of A and B is a set of elements that
are common in both sets.
Difference - difference() Difference of A and B (A - B) is a set of elements
that are only in A but not in B. Similarly, B - A
is a set of element in B but not in A.
Symmetric ^ symmetric_difference() Symmetric Difference of A and B is a set of
Difference elements in both A and B except those that are
common in both.

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

B = {4, 5, 6, 7, 8}

Union:

print(A|B) # {1, 2, 3, 4, 5, 6, 7, 8}
print(B|A) # {1, 2, 3, 4, 5, 6, 7, 8}
[Link](B) # {1, 2, 3, 4, 5, 6, 7, 8}
[Link](A) # {1, 2, 3, 4, 5, 6, 7, 8}
Intersection:
print(A&B) #{4, 5}
print(B&) #{4, 5}
A. intersection(B) #{4, 5}
B. intersection(A) #{4, 5}
Difference:
print(A-B) # {1, 2, 3}
print(B-A) # {8, 6, 7}
A. difference(B) # {1, 2, 3}
B. difference(A) # {8, 6, 7}

Symmetric Difference:
print(A^B) # {1, 2, 3, 6, 7, 8}
print(B^A) # {1, 2, 3, 6, 7, 8}
A. symmetric_difference(B) # {1, 2, 3, 6, 7, 8}
Methods of set:
[Link] IPS ADD ICU ICU ICU
DDIFFERENCE
SSYMMETRIC DIFFERENCE
IINTERSECTION
R REMOVE
IINTERSECTION UPDATE
I IS DISJOINT
PPOP
SSYMMETRIC UPDATE
AADD
DDIFFERENCE UPDATE
DDISCARD
IIS SUBSET
CCOPY
UUNION
IIS SUPER SET
CCLEAR
UUPDATE

SET METHODS
DEFINATION:
A) A SET IS A COLLECTION OF UNORDERED ELEMENTS.
B) IT IS A MUTABLE(WE CAN ADD & REMOVE THE ELEMENTS.
C) WE REPRESENT THE SET IN CURLY BRACES { }.
D) IN SET EVERY ELEMENT IS UNIQUE(NO DUPILCATES).
E) THE SET ARE USING FOR MATHEMATICAL OPERATIONS LIKE ,

1)UNION
s1={1,2,3,4}

s2={5,6,7,8}

print(s1|s2)

{1, 2, 3, 4, 5, 6, 7, 8}

2)INTERSECTION
s1={'a','b','c','d'}

s2={'c','d','f','e'}

print(s1&s2)

{'d', 'c'}

3) DIFFERENCE
s1={1,2,3,4}

s2={4,5,6,7,8}

print(s1-s2)
{1,2,3}

4)SYMMTRICAL DIFFERANCE
s1={10,20,30,40}

s2={40,50,60,70}

print(s1^s2)

{70, 10, 50, 20, 60, 30}

5)ADD
s1={11,13,15,16}

[Link](20)

print(s1)

{11, 13, 15, 16, 20}


6)POP
s={1, 2, 3, 4, 5, 6, 7, 8}

[Link]()

[Link]()

print(s)

{3, 4, 5, 6, 7, 8}

7)REMOVE
s={'a','b','c','d'}

[Link]('d')

print(s)

{'b', 'a', 'c'}


PRINT(W)

TRACEBACK (MOST RECENT CALL LAST):

FILE "<PYSHELL#31>", LINE 1, IN <MODULE>

PRINT(W)

NAMEERROR: NAME 'W' IS NOT DEFINED

8)DISCARD
s={70, 10, 50, 20, 60, 30}

[Link](50)

print(s)

{20, 70, 10, 60, 30}

[Link](90)

print(s)

{20, 70, 10, 60, 30}

9)COPY
s={11, 13, 15, 16, 20}

[Link]()
{16, 20, 11, 13, 15}

10)UPDATE

s={1, 2, 3, 4, 5, 6, 7, 8}

s1={'a','b','c'}

[Link](s1)

print(s)

{1, 2, 3, 4, 5, 6, 7, 8, 'c', 'b', 'a'}

11)IS DISJOINT
s1={1,2,3,4}

s2={4,5,6,7,8}

[Link](s2)

False

12)IS SUBSET
s1={1,2,3,4}

s2={4,5,6,7,8}

[Link](s2)

False

13)IS SUPERSET
s1={4,5,6,7,8}

s2={1,2,3,4}

[Link](s2) False

14)CLEAR
s={1, 2, 3, 4, 5, 6, 7, 8}

s1={'a','b','c','d'}

[Link]()

set()
12. Tuples
 Tuple is a sequence of elements. A tuple is immutable, unlike a list in Python. By immutable,
we mean that it is not possible to update a tuple after declaring one. The elements inside a
tuple can be any Python object such a string, integer etc. Tuples are surrounded by
parenthesis.
 Examples:
t1 = (1, "sridhar", 3.0)

t1
(1, 'srishar', 3.0)
type(t1)

<type 'tuple'>

Declaring a Tuple:
 Empty Tuple is declared by empty parenthesis.
t2 = ()
t2 ()
type(t2)

<type 'tuple'>
 It is important to note that declaring a tuple consisting a single element requires a comma after
the first element.
t3 = (1,)
t3
(1,)

type(t3)
<type 'tuple'>

 If we miss out on that comma, t3 would become an integer because 1 itself is an integer.
t3 = (1)
type(t3)
<type 'int'>
t3 = ('abc')
type(t3)
<type 'str'>

Accessing elements of a Tuple:


 We use square brackets along with the index which we want to access.
 Examples:
t1 = (1, "sridhar", 3.0)
t1[0] 1
t1[1]
'sridhar'
t1[2]
3.0
t1[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

 If you try accessing some index that doesn’t exist, Python raises appropriate error. We can
also access elements using negative indexing.

>>> t1[-1]
3.0
>>> t1[-2]
'abc'

 Index table indicating positive and negative index values.

+ ve Index 0 1 2
Tuple=
- ve -3 -2 -1
(1, "abc", 3.0)

Index

Updating elements of a Tuple:


 We saw in the definition of a tuple that tuples are immutable. It is not possible to update them
once declared. but what happens if we try to do so?

t1 = (1, "sridhar", 3.0)


t1[1] = 'xyz'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

 If we try to update the element by using index, it raises an error saying that ‘tuple’ object does
not support item assignment.
 However, if you add mutable elements such as a list inside a tuple, we can mutate them. For
example:
a = [1, 2]

b = [4, 5]
t = (a, b)
t
([1, 2], [4, 5])
[Link](3)
t

([1, 2, 3], [4, 5])


 A tuple can also be nested, i.e. just like a list inside a tuple, we can have tuples inside a tuple.
a = (1, 2)
b = (4, 5)
t = (a, b)
t

((1, 2), (4, 5))

 However, now that tuples are not mutable, we cannot update the tuple inside a tuple either.

 If we really want to update a tuple, we can use that tuple to create another tuple.
t2 = (t[0], (3), t[1])
t2
((1, 2), 3, (4, 5))

Deleting a Tuple:
 Since tuples are immutable, it is not possible to delete individual elements of a tuple,
however, we can delete the whole tuple itself.

t = (1, "sridhar", 3.0)

del t
t #If we try to access the tuple after deleting it, python will raise an error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 't' is not defined
Slicing a Tuple:
 Tuple slicing is similar to string slicing. Using slicing we can extract out elements of any tuple. We
have to provide the starting index and the ending index i.e. tuple[start:end]

t = ('s', 'u', 's', 'a', 'n')


t[1:4]
('u', 's', 'a')

 It starts from start and ends right before end. It won’t print the element at the index
end. As in the example above, we have n at the 4th index of tuple t, however, it printed
only tilla.
 If the start is out of the range of the tuple, then it prints empty tuple.

t[5:7] ()

 If you don’t provide start, then it will print from start till end-1 element.

t[:3]
('s', 'u', 's')

 Similarly, if end is not provided, it prints till the last element of the tuple.

t[2:]
('s', 'a', 'n')

 If there is no start and end It prints the whole tuple as is.

t[:]
('s', 'u', 's', 'a', 'n')

Operations on tuple:
 Addition:
Using the addition operator, with two or more tuples, adds up all the elements into a new tuple. For
example,
t = (2, 5, 0) + (1, 3) + (4,)
print t
(2, 5, 0, 1, 3, 4)

 Multiplication
Multiplying a tuple by any integer, x will simply create another tuple with all the elements from the
first tuple being repeated x number of times. For example, t*3 means, elements of tuple t will be
repeated 3 times.
t = (2, 5)
print t*3

(2, 5, 2, 5, 2, 5)

Member ship operation(in keyword):


in keyword, can not only be used with tuples, but also with strings and lists too. It is used to check, if
any element is present in the sequence or not. It returns True if the element is found, otherwise False.
For example,
t = (1, 2, 3, 6, 7, 8)
2 in t
True
5 in t
False

Iterating Through a Tuple:


Using a for loop we can iterate though each item in a tuple.

for name in
('sridhar','civil'):
print("Hello",name)

Output:
Hello Sridhar
Hello civil

Functions of Tuple:
len() function
As you might have already guessed, this function is used to get the number of elements inside any
tuple.
t = 1, 2, 3
print len(t) 3

cmp() function
This is used to compare two tuples. It will return either 1, 0 or -1, depending upon whether the
two tuples being compared are similar or not.

The cmp() function takes two tuples as arguments, where both of them are compared.
If T1 is the first tuple and T2 is the second tuple, then:
 if T1 > T2, then cmp(T1, T2) returns 1
 if T1 = T2, then cmp(T1, T2) returns 0
 if T1 > T2, then cmp(T1, T2) returns -1

 max() and min() function


To find the maximum value in a tuple, we can use the max() function, while for finding
the minimum value, min() function can be used.
t = (1, 4, 2, 7, 3, 9)
print max(t) 9
print min(t) 1

Methods of tuple:
 Methods that add items or remove items are not available with tuple. Only the
following two methods are available.

Method Description

count(x) Return the number of items that is equal to x

index(x) Return index of first item that is equal to x

 Some examples of Python tuple methods:


tuple = ('a','p','p','l','e',)

Count
print([Link]('p'))
Output: 2
Index
print([Link]('l'))
Output: 3
Advantages of Tuple over List
Since, tuples are quite similar to lists, both of them are used in similar situations as well.
However, there are certain advantages of implementing a tuple over a list. Below listed are some
of the main advantages:
 We generally use tuple for heterogeneous (different) datatypes and list for
homogeneous (similar) datatypes.
 Since tuple are immutable, iterating through tuple is faster than with list. So there is a
slight performance boost.
 Tuples that contain immutable elements can be used as key for a dictionary. With list,
this is not possible.
 If you have data that doesn't change, implementing it as tuple will guarantee that it
remains write-protected.

Tuple vs List:

 The key difference is that tuples are immutable . This means that you cannot change the
values in a tuple once you have created it. As a list is mutable , it can't be used as a key
in a dictionary, whereas a tuple can be used.
 The literal syntax of tuples is shown by parentheses ( ) whereas the literal syntax of lists
is shown by square brackets [ ] .
 Tuples are heterogeneous data structures (i.e., their entries have different meanings),
while lists are homogeneous sequences.
 Lists are for variable length , tuples are for fixed length .
 Tuples show structure whereas lists show order

[Link]
 Python dictionary is an unordered collection of items. While other compound data
types have only value as an element, a dictionary has a key: value pair.
 Dictionaries are optimized to retrieve values when the key is known.
Creating Dictionary:
 Creating a dictionary is as simple as placing items inside curly braces {} separated by
comma.
 An item has a key and the corresponding value expressed as a pair, key: value.
 While values can be of any data type and can repeat, keys must be of immutable type
(string, number or tuple with immutable elements) and must be unique.

empty dictionary
dict = {}
#dictionary with integer keys
dict = {1: 'sridhar', 2: 'civil'}
dictionary with mixed keys
dict = {'name': 'sridhar', 1: [2, 4, 3]}
using dict()
dict = dict({1:'sridhar', 2:'civil'})
from sequence having each item as a pair
dict = dict([(1,'sridhar'), (2,'civil')])

 we can also create a dictionary using the built-in function dict().

Accessing elements from Dictionary:


 While indexing is used with other container types to access values, dictionary uses keys. Key can
be used either inside square brackets or with the get() method.
 The difference while using get() is that it returns None instead of Key Error, if the key is not found.

dict = {'name':'sridhar', 'age': 20}


print(dict['name'])
print([Link]('age'))

output:
sridhar2
0

Changing Elements of Dictionary:


 Dictionary are mutable. We can add new items or change the value of existing items using
assignment operator.
 If the key is already present, value gets updated, else a new key: value pair is added to the
dictionary.
dict = {'name':'sridhar', 'age': 20}

update value
dict['age'] = 27
print(dict)

Output: {'age': 27, 'name': 'sridhar'}

add item
dict['address'] ='Downtown'
print(dict)

Output: {'address': 'Downtown', 'age': 27, 'name': 'sridhar'}

 We can remove a particular item in a dictionary by using the method pop(). This method
removes as item with the provided key and returns the value.
 The method, popitem() can be used to remove and return an arbitrary item (key, value) form
the dictionary. All the items can be removed at once using the clear() method.
 We can also use the del keyword to remove individual items or the entire dictionary itself.
create a dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
remove a particular item
print([Link](4))
Output: 16
print(squares)

Output: {1: 1, 2: 4, 3: 9, 5: 25}

remove an arbitrary item


print([Link]())
print(squares)
Output: (1, 1)
Output: {2: 4, 3: 9, 5: 25}
delete a particular item
del squares[5]
print(squares)

Output: {2: 4, 3: 9}
remove all items
[Link]()
print(squares)
Output: {}

delete the dictionary itself


del squares
print(squares)
Throws Error
Methods of Dictionary:

PICK UP GF SVC.
P  POP()
I  ITEMS()
C COPY()
KKEYS()
U UPDATE()
PPOPITEM()
G GET()
FFROM KEYS()
S SET DEFAULT()
VVALUES()
CCLEAR()

1)POP
d={"name":"sridhar","rno":102,"branch":"civil"}
[Link]("rno",102)
102

2)ITEMS
d={"name":"sridhar","rno":102,"branch":"civil"}
[Link]()
dict_items([('name', 'sridhar'), ('rno', 102), ('branch', 'civil')])
3)COPY
d={"name":"sridhar","rno":102,"branch":"civil"}
[Link]()
{'name': 'sridhar', 'rno': 102, 'branch': 'civil'}

4)KEYS
d={"name":"sridhar","rno":102,"branch":"civil"}
[Link]()
dict_keys(['name', 'rno', 'branch'])

5)UPDATE
d={"name":"sridhar","rno":102,"branch":"civil"}

[Link]({"per":100})
print(d)
{'name': 'sridhar', 'rno': 102, 'branch': 'civil', 'per': 100}

6)POPITEM
d={"name":"sridhar","rno":102,"branch":"civil"}
[Link]()
('branch', 'civil')
print(d)
{'name': 'sridhar', 'rno': 102}

7)GET
d={"name":"sridhar","rno":102,"branch":"civil"}
[Link]("rno")
102

8)FROMKEYS
d={"name":"sridhar","rno":102,"branch":"civil"}
a=("x","y","z")
[Link](a,"sri")
{'x': 'sri', 'y': 'sri', 'z': 'sri'}

9)SET DEFAULT
d={"name":"sridhar","rno":102,"branch":"civil"}
[Link]("rno",100)
102
[Link]("rno")
102
print(d)
{'name': 'sridhar', 'branch': 'civil'}
[Link]("rno",100)
100
print(d)
{'name': 'sridhar', 'branch': 'civil', 'rno': 100

10)VALUES
d={"name":"sridhar","rno":102,"branch":"civil"}
[Link]()
dict_values(['sridhar', 102, 'civil'])

11)COPY
d={"name":"sridhar","rno":102,"branch":"civil"}
[Link]()
print(d)
{}
Functions of Dictionary:

all(iterable) s = {0: 'False', 1: 'False'}


Return True if all keys of the
print(all(s))#False
all() dictionary are true (or if the
s = {1: 'True', 2: 'True'}
dictionary is empty).
print(all(s))#True

Return True if any key of the any(iterable) d = {0: 'False'}


dictionary is true. If the print(any(d))#False
any()
dictionary is empty, d = {0: 'False', 1: 'True'}
return False. print(any(d))#True

len(iterable) d = {1: 'one', 2: 'two'}


Return the length (the number
len() print(d, 'length is', len(d))
of items) in the dictionary.
# {1: 'one', 2: 'two'} length is 2

sorted(iterable[, d= {'e': 1, 'a': 2, 'u': 3, 'o': 4, 'i': 5}


Return a new sorted list
sorted() key][, reverse]) print(sorted(d, reverse=True))
of keys in the
# ['u', 'o', 'i', 'e', 'a']
dictionary.

Other Dictionary Operations


Dictionary Membership Test:
We can test if a key is in a dictionary or not using the keyword in. Notice that membership test is
for keys only, not for values.
 Example:
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(1 in squares)
print(2 not in
squares) print(49 in
squares) Output:
True
True
False
Iterating Through a Dictionary:
Using a for loop we can iterate though each key in a dictionary.
Example:
squares = {1: 1, 3: 9, 5: 25, 7: 49}
for i in squares:
print(squares[i])
Output:
1

9
81
25

Dictionary Comprehension:
 Dictionary comprehension is an elegant and concise way to create new dictionary from
an iterable in Python.
 Dictionary comprehension consists of an expression pair (key: value) followed by for
statement inside curly braces {}.
 Here is an example to make a dictionary with each item being a pair of a number and
its square.
 Example:
squares = {x: x*x for x in range(6)}
print(squares)
Output:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

 The above code is equivalent


to squares = {}
for x in range(6):
squares[x] = x*x
14. Functions
Functions
I. Def: A function is defined as a block of code which can be used to perform an action.
Function will not be executed automatically.
Function will be executed when ever we make a function call.
We can call one function for ‘n’ number of times.
Python supports two types of functions:
1)Built-in functions
2)User defined functions

1)Built-in functions:
The functions which comes along with python software are known as Built-in functions or
Predefined functions.

2)User defined functions:


The functions which are developed by the “Programmers” explicitly according to their
business requirements.
Implementation of user defined functions:
1)Function Definition:
Syntax: def function name(Parameters):
Statements
________
_________
return value (optional)
1 .Function calling:
Syntax:
function name(values)

Definition:
A function is nothing but collection of instructions for solving a particular task is
known as a function.
Advantages:
1)By using functions, we can understand the program very easily.
2)Reduce the time.
3)Solve the complex problems easily.
4)Reduce the lines of code.

Functions are categorised into:

1)++(with argument, with return value)


def add(a,b):
return a+b
sum=add(100,200)
print(sum)
2) - - (without argument , without return value)
def add():
a=100
b=200
sum=a+b
print(sum)
add()
3)- +(without argument , with return value)

def add():
a=100
b=200
return a+b
print(add())
4)+ - (with argument , without return value)
def add(a,b):
sum=a+b
print(sum)
add(100,200)

II. TYPE OF VARIABLES (OR) SCOPE AND LIFETIME VARIABLES

Variable: It is a name of storage location.


X=10
Types of variables:
[Link] Variables:
The variable defined with in the body of a function (or) a block are
called the Local variables.
The scope of local variable is local to that particular function (or) block in
which it is defined
def robo():
x=100 x
print(x) 10
0
robo(x)
 Once we come out of the function where the variable is declared , the
variable will be removed from the memory and is not available any more.
[Link] Variables:
The variables defined outside of any function are called Global Variables.
 The scope of Global variables is global , that is they are accessible through
out of program.
 These variables can be accessed by all the functions in the program

X=100
def robo(): x
print(x) 1
robo() 0
def chitti(): 0 output:100
print(x)
chitti()

III. Recursive function in python:


A Function that calls itself is known as Recursive function and this
technique is known as recursion.

 There should be atleast one if statement used to terminate recursion.

 It does not contain any looping statements.

EX: def robo():

Print(“Hai”)

robo()

robo()

Output:

Hai
Hai

Program:

Factorial program by using Recursion:


def factorial(n):

if n == 0 or n==1:
return 1
else:
return n * factorial (n-1)
print(factorial(5))

IV. Types of Function arguments:

1. Required (or) Positional arguments:

These are the arguments which are passed to a function in absolute


positional order.

 The total number of arguments used in a function should be equivalent


to the arguments used in function definition.

 If they are not equal, then the function return a type error.
EX: def add (x,y):
Sum=x + y
Print (sum)
Add (100,200) => 300 (values are stored in orderwise)
Add (200,400,600) => type error (does not match)

2. Default arguments:
These are the arguments for which default values are assigned during function
declaration.
These values are used, only when the values of such arguments are not provided
in the function call.
Ex: def add (x=100, y=200):
Sum=x + y (Order)
Print(sum)
add (10,20) => 30
add (10) =>10
add ( ) => 300

3. KEYWORD ARGUMENTS:
These are the arguments which can be identified by the caller of the
function using their parameter names.
It allows the caller of the function to specify only few arguments and In any
order.
EX:

def add (x, y=20, z=30):


sum = x +y +z (No Order)
print(sum)
add (10,20,30) => 60
add (10, y=40) => 10+40+30 = 80
Add (10, z=20) => 10+20+20= 50
Add (20, z=10, y=60) = 20+10+60 = 90

[Link] LENGTH (OR) ARBITRARY ARGUMENTS:


These are the arguments whose length is not known before runtime (or) even
during execution are referred to as “variable length arguments.”
 we can pass ‘n’ number of values.

Ex:
def robo (* no): (* : n number of values accept)
Print(no)
robo (10,20,30,40) => 10,20,30,40.
robo (“work”, ”dream” , ”achieve”) => work , dream , achieve.
EX:

def add (x, y=20, z=30):


sum = x +y +z (No Order)
print(sum)
add (10,20,30) => 60
add (10, y=40) => 10+40+30 = 80
Add (10, z=20) => 10+20+20= 50
Add (20, z=10, y=60) = 20+10+60 = 90

[Link] LENGTH (OR) ARBITRARY ARGUMENTS:


These are the arguments whose length is not known before runtime (or) even
during execution are referred to as “variable length arguments.”
 we can pass ‘n’ number of values.

Ex:

def robo (* no): (* : n number of values accept)


Print(no)
robo (10,20,30,40) => 10,20,30,40.
robo (“work”, ”dream” , ”achieve”) => work , dream , achieve.

V . Anonymous Function (or) Lambda Function:


The function which are not defines in a standard way using define key
word are called anonymous (or) Lambda function.
 These functions can be created by using Lambda keyword.
Syntax: Lambda arguments : expression
 A lambda function can take any number of arguments, but can have only
one expression.
 It is a one line function.
Note: Generally we use the lambda function whenever we want to pass one
function as parameters to another function.

Ex:-
def add(a,b):
return a+b
print(add(10,20))

add=lambda a,b : a+b


print(add(10,20))

Example-1:

def grade(marks):
If(marks>90):
return “excellent”
elif(marks>70):
return “good”
elif(marks>60):
return “average”
else:
return “fail”
Print(grade(75))

Example-2:
print((lambda marks:"excellent" if marks>90 else ("good" if marks>70
else ("average" if marks>60 else "fail")))(75))

output:
good

function use of lambda in python:


[Link]() function in python:

This function is used to reduce a sequence of elements to a single value by


processing the elements,according to a function supplied.
• It returns a single value.
• This function is a part of functions modules you have to import it before
using

Syntax:
From Functions import reduce
reduce(function name, sequence variable)

Ex:-
Sum of first 10 natural numbers
From functions import reduce
L= [1,2,3,4,5,6,7,8,9,10]
Result=reduce (Lambda x , y: x+y , l)
Print(result)

You might also like