Core Python by Vikash Sarraf
Core Python by Vikash Sarraf
:- 8804321194
Telegram Id :-@vksarraf
‘Give a man a fish and you feed him for a day.Teach a man to fish and to feed him for a lifetime.’
1. Python Introduction
Introduction
Brief introduction of Python
Application areas of Python
Features of Python
Limitation of Python
Version of Python
Installing of Python
Setup path
Structure of Python Program
Working with Python
Basics Of Programming
2. Identifiers
Introduction
Rules for defining identifiers
3. Reserve words/Keywords
Introduction
uses
4. Variable
Global Variable
Local Variable
5. Data Types:
int
float
complex
bool
str
base conversion
type casting
bytes
bytearray
list
tuple (range())
set
dict
6. Operators:
Arithmatic
Relational
Eqaulity
Logical
Bitwise:
Assignment
Special
identity
membership
8. Control Flow:
Conditional Statements:
If
If- else
Nested if-else
Iterative Statements:
For
While
Nesting
Transfer Statements:
Break
Continue
Pass
9. String Handling
Accessing Strings
indexing
slice operator
String slices
Basic Operations
Function and Methods
10. Lists
Introduction
creation of list
Accessing list
Operations
Working with lists
Function and Methods
List Comprehension
Nested List
11. Tuple
Introduction
Accessing tuples
Operations
Working
Functions and Methods
12. Dictionaries
Introduction
Accessing values in dictionaries
Working with dictionaries
Properties
Functions
13. Set
Introduction
Accessing set
Operations
Working
Functions and Methods
13. Functions
Defining a function
Calling a function
Types of functions
Function Arguments
Anonymous functions
Recursion function
Global and local variables
filter()
reduce()
map()
Introduction (I)
Computer
Any Calculating device is called Computer.
Definition - What does Computer mean?
Full Form
C= Common
O= Oriented
M= Machine
P= Particularly
U= United and used under
T= Technical and
E= Educational
R= Research
Brain Vs. Computer
Speed
Accuracy
Processing
Size and Complexity
Storage
Control Mechanism
Automation
Versatile
Diligency
Reliability
Software
Collection of programs is called Software.
Program
Collection of instructions is called pragram.
Programing
Solving the problem step by step is called is called Programming.
Algorithm
An algorithm (pronounced AL-go-rith-um) is a procedure or
formula for solving a problem, based on conductiong a sequence
of specified actions. A computer program can be viewed as an
elaborate algorithm. In mathematics and computer science, an
algorithm usually means a small procedure that solves a recurrent
problem.
Flow Chart
A flowchart is a formalized graphic representation of a logic
sequence, work or manufacturing process, organization chart, or
similar formalized structure. The purpose of a flow chart is to
provide people with a common language or reference point when
dealing with a project or process.
Programming Languages
There are two types of programming language.
1. Low level language (L.L.L)
2. High level language (H.L.L)
Translators
There are three types of translators
1. Assembler
2. Interpreter
3. Compiler
Assembler
Interpreter
It converts the program written in High Level Language into Low Level
Language line by line if any error in any line then Execution process will
terminate.
Compiler
It converts the program written in High Level Language into Low Level
Language at one go. If there is any syntax error in program ,program won’t
be execute.
Python
Father Of Python
Introduction
Python is a general purpose, high level,dynamically typed
programming language. It is developed by Guido Van Rossum in
1989 at NRI(National Research Institute) in Netherlands but
Python was available in 1991.
Comparision
C
/* print hello world */
#include<stdio.h>
void main()
{
printf("Hello world ")
}
/* Output=Hello world */
Java
public class HelloWorld{
Python
print('Hello world')
# Output
Hello world
#include<stdio.h>
int main()
{
int a, b, c;
printf("Enter two numbers to add\n");
scanf("%d%d", &a, &b);
c = a + b;
printf("Sum of the numbers = %d\n", c);
return 0;
}
Python
import java.util.Scanner;
class AddNumbers
{
public static void main(String args[])
{
int x, y, z;
x = in.nextInt();
y = in.nextInt();
z = x + y;
“There are many languages but there are approx 256 programming
languages known in the world.”
https://www.tiobe.com/tiobe-index/programming-languages-
definition/#instances
Features of Python
1. Simple
2. Easy to learn
3. Functional programming
4. Object Oriented programming ( C++ )
5. Open source
6. Free ware
7. Dynamically typed language
8. Interpreted language
9. Extensiblle
10.Plateform independent
Limitations of python:
Performance is low incomparison with C and C++
Python Version
1.X ( 1994)
2.X ( 2000)
3.X ( 2008)
Identifiers ( II )
A name in program which, can be used for identification purpose is called an
Identifier.
It can be function name, variable name, method name, class name, module
name.
i.e. addition=20
def shoaib():
a,b=10,20
print("Learning Python is Very Easy")
# here 'addition, shoaib, a, b and print() 'are identifiers
Except following 3
True, False, None
1. int
2. float
3. complex
4. bool
5. str
6. bytes
7. bytearray
8. list
9. tuple
10 set
11. dict
range() function
1. integral value
ie. a=500
type(a)
O/p--- <class 'int'>
ie. a=1.752
b=1.5326
syntax
a+bj where a is real part b is imaginary part
i.e
3+5j
5+4j
2.5+6.25j
a=3+5j
a.real-------------->3
a.imag-------------->5
bool
it is used represent boolean value
Allowed value True and False
ie.
a=True (Valid)
type(a)
<class 'bool'>
a=False (Valid)
type(a)
<class 'bool'>
a=true (InValid)
a=false (InValid)
str
str is is used to represent String
String is collection of characters enclosed with either single quotes ('') or in
double quotes ("")
ie.
abc='Techavera Solutions Pvt Ltd'
type(abc)
<class 'str'>
abc="Techavera Solutions Pvt Ltd"
type(abc)
<class 'str'>
Multiline Strings
we can represent multiline string either triple single quotes (''' Techavera Python
Trainer ''') or in triple double quotes (""" Techavera Python Trainer""")
i.e
abc='''Welcome To
techavera
Solutions
Pvt. Ltd.'''
print(type(abc))
#<class 'str'>
print(abc)
# Welcome To
techavera
Solutions
Pvt. Ltd.
abc="""Welcome To
techavera
Solutions
Pvt. Ltd."""
type(abc)
#<class 'str'>
print(abc)
#Output
Welcome To
techavera
Solutions
Pvt. Ltd.
( * imp ) Note-
1. int,float,str, bool,complex are fundamental data type.
2. All fundamental data types are immutabel
3. In Python everything is an object.
Base Conversion
Base conversion is used to convert one base to another base(ie. binary to
decimal)
1. bin() function
It is used to convert any base (decimal, octal, hexa decimal)to binary
ie. bin(7) ------- 0b111
bin(0o7)------- 0b111 { please fill output in all cases }
bin(0XA)-------0b1010
2. oct() function
It is used to convert any base (decimal, binary, hexa decimal)to octal
ie. oct(7)--------
oct(0b111)----0o7 { please fill output in all cases }
oct(0xA)------
3. hex() function
It is used to convert any base (decimal, octal, hexa decimal)to hexa decimal
ie. hex(7)--------
hex(0b111)---- { please fill output in all cases }
hex(0o777)------
(V) Type Casting
Type Casting
Python defines type conversion functions to directly convert one data type to
another which is useful in day to day and competitive programming. This article
is aimed at providing the information about certain conversion functions.
int()
It is used to convert another type to int.
bool()
It is used to
convert another type to bool.
non-zero ------------------->True
zero ----------------------->False
non-zero ------------------->True
zero ----------------------->False
for complex
complex()
It is used to convert another type to complex.
syntax
str()
It is used to convert another type to str.
range()
It is used to generate some sequence of value.
It is applicable only for integer.
range(end)
|
end=end-1
range(9)--------> output------>0,1,2...........,9
range(begin,end)
| |
0 end-1
ie range(1,10)
1,2,3..........9
ie range(10,20)
10,20,30,..........19
range(begin,end,step)
ie. range(1,10,2)
(VI) Operators
Operators are symbols used to perform certain operations
There are variouos operators in Python
1. Arithmatic Operators
2. Relational Operators/Comparison Operators
3. Equality Operator
4. Logical Operators
5. Bitwise Operators
6. Assignment Operators
7. Special operators
1. Arithmatic Operators
If both operands are float then result is float but in nearest to the int
ie. 82//32.5
30.5//2
power operator(**)
If 1 operand is string & another is int then it work as String repetition operator
order is not important
4. Special operators
identity operator (is , is not)
membership operator (in, not in)
Identity operator
It is used for address comparision
ie. a=50
b='Koirala'
id(a) -------->154415454
id(b) -------->603564235
a is b ------False
a is not b ---------->True
a=20
b=50
print(a!=b)
print(a is b)
print(id(a))
print(id(b))
a=257
b=257
print(a==b)
print(a is b)
print(id(a))
print(id(b))
( * imp )
Q- Difference between (is) operator and (==) operator ?
Ans- 'is' operator is used for address comparision while '==' is used for content
comparasion
Note-
Reusability of is operator
a=10
b=10
print(a==b)
print(a is b)
print(id(a))
print(id(b))
# Output
True
True
93962259520320
93962259520320
a=1.57
b=1.57
print(a==b)
print(a is b)
print(id(a))
print(id(b))
# Output
True
False
139977416780032
139977416780176
a=True
b=True
print(a==b)
print(a is b)
print(id(a))
print(id(b))
# Output
True
True
93962259520320
93962259520320
a='Python'
b='Python'
print(a==b)
print(a is b)
print(id(a))
print(id(b))
# Output
True
True
93962259520320
93962259520320
# Output
True
False
and
if all conditions are True then result is True
or
not
if conditions is True then result is False
1 | 0 ---------->1
1 | 1 ----------->1
0 | 0 ------------>0
1 ^ 0 ----------> 1
1 & 1 -----------> 0
imp--------------------
~4 --------------> -5
(imp) Note-
-----------------
+ve number directly stored in memory but -ve number is stored in 2's
compliment form
a,b,c,d=10,20,30,True
compound Assignment
ie. a+=10 ----------- a=a+10
a*=5 ------------a=a*5
a/=6 ------------- a=a/6
Operator precedence
()
**
~,
*, /, %, //
+, -
<<, >>,
&
^
|
<, >= <, <=, == ,!=
=,+=,
is , is not,
in , not ins
not
and
or
(VII) Input/Output
Python2
raw-input()
This function always reads the data from the keyboard in the form of
String Format. We have to convert that string type to our required type by
using the corresponding type casting methods.
input()
input() function can be used to read data directly in our required format.We
are not required to perform type casting.
Python3
input()
It will take input in str form so we have to require type casting.
int()
# wap to input two no print their sum
# Output
Enter first number:10
Enter 2nd number:20
The sum: 30
float()
number1=float(input("Enter first number:"))
number2=float(input("Enter 2nd number:"))
print('The sum:',number1+number2)
# Output
Enter first number:10
Enter 2nd number:58.65
The sum: 68.65
eval()
eval() can evaluate the Input to list, tuple, set, etc based the provided Input.
# Output
Enter first number:10
Enter 2nd number:3+45j
The sum: (13+45j)
Q. Write a program to read Employee data from the keyboard and
print that data.
The argument which are passes at the time of execution are called command
line arguments
* argv hold command line arguments in python
* argv is list type
* argv present in sys module
print()
We can use print() function to display output.
print(str)
print('Maneesha Yadav')
name1='Diksha'
name2='Manisha'
name3='Abha'
print('{0} {1} {2} are studying at Techavera'.format(name1,name2,name3))
%i ------------------ int
%d ------------------ int
%f ------------------ float
%s ----------------------------str
ie
a,b,c=1,2,3
print('a value is %i'%a)
print('b vales is %d'%b)
print('c vales is %d'%c)
# Output
a value is 1
b vales is 2
c vales is 3
(IX) Control Flow
It describe the order of program.
It describe in which order statements are executed at runtime
Conditional Statement
if
syntax
if condition:
statement
statement
statement
statement
.
.
statement
ie.
# Output
Enter a number: -10
-10 Number is negative
if-else
syntax
if condtion:
statement
statement
statement
statement
.
.
statement
else:
statement
statement
statement
statement
.
.
statement
# Output
Enter a number: 10
10 is Even
Rerun
Enter a number: 15
15 is Odd
# wap to input two no & print greater
# Output
Enter first number: 10
Enter second number: 20
20 is greater than 10
syntax
if condition:
statement
statement
statement
statement
.
.
statement
elif condtion:
statement
statement
statement
statement
.
.
statement
else:
statement
statement
statement
statement
.
.
statement
# Output
Enter first number: 10
Enter second number: 10
10 and 10 are equals
Rerun
Enter first number: 10
Enter second number: 20
10 is lesser than 20
# Output
Enter first number: 10
Enter second number: 10
10 is equal to 10
Rerun
Enter first number: 50
Enter second number: 60
60 is larger than 50
# Output
Enter a number: 10
Enter a number: 20
Enter a number: 30
30 is greater number
# Output
Enter a number: 10
Enter a number: 10
Enter a number: 10
All are equals
# Output
Enter a number: 10
Enter a number: 10
Enter a number: 10
All are equals
Rerun
Enter a number: 10
Enter a number: 20
Enter a number: 20
20 and 20 are equal
Rerun
Enter a number: 10
Enter a number: 20
Enter a number: 5
20 is greater number
Ternary Operator in Python
Variable1= var2 if condition else var3
# Output
Enter a number: 10
Enter a number: 20
Greater number is 20
# Output
Enter a number: 10
Enter a number: 20
Enter a number: 5
smaller no is 5
# Output
Enter any Year:2016
2016 Year is leap
Rerun
Enter any Year:100
100 Year is not leap
Rerun
Enter any Year:2000
2000 Year is leap
if-elif
syntax
if condition:
statement
statement
statement
statement
.
.
statement
elif condition:
statement
statement
statement
statement
.
.
statement
# Output
Enter first number: 50
Enter second number: 60
60 is larger than 50
# Output
Enter marks of the first subject: 80
Enter marks of the second subject: 85
Enter marks of the third subject: 90
Enter marks of the fourth subject: 91
Enter marks of the fifth subject: 92
Grade: B
Note-
for loop
while loop
syntax
# Output
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# wap to print 20 to 1
for a in range(20,0,-1):
print(a,end=' ')
# Output
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
# W.A.P to input a number and print their table
# Output
Please enter a number to print the table of :
5
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
s='Shreya Khirwal'
for x in s:
print(x)
# output
S
h
r
e
y
a
K
h
i
r
w
a
l
s='Shreya Khirwal'
for x in s:
print(x,end='')
# Output
Shreya Khirwal
while loop
if we want to execute a group of statements iteratively until some condition
false,then we should use while loop
syntax
while condition:
statement
statement
statement
statement
.
.
statement
ie.
i=1
while i<=100:
print(i,end=' ')
i+=1
# Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
94 95 96 97 98 99 100
n=int(input("Enter a number:"))
tot=0
while(n>0): #187>0 18>0 1>0 0>0
dig=n%10 #7
tot=tot+dig # 0+7+8+1
n=n//10 #187//10 18//10 1//10
print("The total sum of digits are:",tot)
# Output
Enter a number:187
The total sum of digits are: 16
n=int(input("Enter a number:"))
tot=1
while(n>0): #187>0 18>0 1>0 0>0
dig=n%10 #7
tot=tot*dig # 0+7+8+1
n=n//10 #187//10 18//10 1//10
print("The total Product of digits are:",tot)
# Output
Enter a number:187
The total Product of digits are: 56
# Wap to input a number & print their digits sum at each stage.
# Output
Enter number 187
The sum of given number at each stage 7
The sum of given number at each stage 15
The sum of given number at each stage 16
The sum of given number is 16
# Output
Enter number: 154
Reverse Number of given Number is 451
# Output
Enter number: 121
121 is Palindrome
Rerun
Enter number: 143
143 is not Palindrome
# Output
Enter number: 153
153 is Armstrong Number
Rerun
Enter number: 143
143 is Armstrong Number
# Output
Enter number: 23
23 Number is prime
Rerun
Enter number: 20
20 Number isn't prime
infinite loop
i=0
while True:
i+=1
print("Hello I am Your Python Trainer at Techavera Solutions Pvt. Ltd")
# Output
Hello I am Your Python Trainer at Techavera Solutions
Pvt. Ltd
Hello I am Your Python Trainer at Techavera Solutions
Pvt. Ltd
Hello I am Your Python Trainer at Techavera Solutions
Pvt. Ltd
Hello I am Your Python Trainer at Techavera Solutions
Pvt. Ltd
Hello I am Your Python Trainer at Techavera Solutions
Pvt. Ltd
Hello I am Your Python Trainer at Techavera Solutions
Pvt. Ltd
Hello I am Your Python Trainer at Techavera Solutions
Pvt. Ltd
Hello I am Your Python Trainer at Techavera Solutions
Pvt. Ltd
Hello I am Your Python Trainer at Techavera Solutions
Pvt. Ltd
Hello I am Your Python Trainer at Techavera Solutions
Pvt. Ltd
Hello I am Your Python Trainer at Techavera Solutions
Pvt. Ltd
Hello I am Your Python Trainer at Techavera Solutions
Pvt. Ltd
Hello I am Your Python Trainer at Techavera Solutions
Pvt. Ltd
.
.
.
.
Nested Loop
Loop inside loop is called nested loop.
1 2 3 4
$ 1 1 1
$$ 12 22 23
$$$ 123 333 456
$$$$ 1234 4444 7 8 9 10
$$$$$ 1 2 3 4 5 55555 11 12 13
#1
#Output
enter number of rows:7
$
$ $
$ $ $
$ $ $ $
$ $ $ $ $
$ $ $ $ $ $
$ $ $ $ $ $ $
#2
#3
#Output
enter number of rows:7
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7 7
#4
row=int(input("enter number of rows:"))
a=1
for i in range(1,row+1):
for j in range(1,i+1):
print(a,end=' ')
a+=1
print()
#Output
enter number of rows:7
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
$ $ $ $ $
$ $ $ $
$ $ $
$ $
$
#Output
enter number of rows:7
$ $ $ $ $ $ $
$ $ $ $ $ $
$ $ $ $ $
$ $ $ $
$ $ $
$ $
$
$
$ $
$ $ $
$ $ $ $
$ $ $ $ $
def pypart2(n):
# number of spaces
k = 2*n - 2
# outer loop to handle number of rows
for i in range(0, n):
# inner loop to handle number spaces
# values changing acc. to requirement
for j in range(0, k):
print(end=" ")
# printing stars
print('$ ', end="")
# Driver Code
n=5
pypart2(n)
#Output
$
$ $
$ $ $
$ $ $ $
$ $ $ $ $
# print following pattern
$
$$
$$$
$$$$
$$$$$
n=int(input('enter rows:'))
for i in range(0,n):
for j in range(0,n-i-1):
print(end=' ')
for j in range(0,i+1):
print('$',end=' ')
print()
#Output
enter rows:7
$
$ $
$ $ $
$ $ $ $
$ $ $ $ $
$ $ $ $ $ $
$ $ $ $ $ $ $
$
$$
$$$
$$$$
$$$$$
n=int(input('enter rows:'))
for i in range(0,n):
for j in range(0,n-i-1):
print(end=' ')
for j in range(0,i+1):
print('$',end='')
print()
#Output
enter rows:7
$
$$
$$$
$$$$
$$$$$
$$$$$$
$$$$$$$
Transfer statements
break
It used to break statement inside loops to break loop execution based on some
condition.
i.e.
for r in range(10):
if r==7:
break
print(r)
print('outside of loop')
#Output
0
1
2
3
4
5
6
outside of loop
continue
It is used to skip current iteration and continue next iteration.
for r in range(10):
if r%2==0:
continue
print(r)
print('outside of loop')
#Output
1
3
5
7
9
outside of loop
for r in range(100,0,-1):
if r%2==0:
continue
print(r,end=' ')
print()
print('outside of loop')
99 97 95 93 91 89 87 85 83 81 79 77 75 73 71 69 67 65
63 61 59 57 55 53 51 49 47 45 43 41 39 37 35 33 31 29
27 25 23 21 19 17 15 13 11 9 7 5 3 1
outside of loop
pass
it is empty statement in python
i.e.
def m1():
pass
print('Sign out')
#Output
Sign out
def sanjay():
print('Hello')
pass
class Sumit:
def ajay(self):
print('HI')
s=Sumit()
s.ajay()
sanjay()
x=[1,2,3]
print(x)
x=None
print(x)
del x
print(x)
#Output
[1, 2, 3]
None
-----------------------------------------------------
----------------------
NameError Traceback
(most recent call last)
<ipython-input-16-6d068b616fba> in <module>()
4 print(x)
5 del x
----> 6 print(x)
7
8 #Output
copy_number=number
count=0
#*************************Caluculations***************************
************
while number>0:
if number%10==digit:
count+=1
number//=10
#***************************************************************
**************
if count!=0:
print(digit," is present in ",copy_number," | ",count," times.")
else:
print(digit," is not present in ",copy_number)
# Output
Please enter number of minimum 2 digits : 456
Please enter digit : 5
5 is present in 456 | 1 times.
print()
print("Largest number from ",num1,",",num2,",",num3,",",num4," is : ",largest)
print()
print("Smallest number from ",num1,",",num2,",",num3,",",num4," is :
",smallest)
# Output
print('******************************************************************')
print("--------------STUDENT ACADEMIC MANAGEMENT SYSTEM------------------")
print('******************************************************************')
print("Please enter enrollment number of student : ")
student_enrollment=input()
print("Please enter name of the student : ")
student_name=input()
print("Please enter the marks of HINDI : ")
hindi=input()
print("Please enter the marks of ENGLISH : ")
english=input()
print("Please enter the markts of MATH : ")
math=input()
print("Please enter the marks of SCIENCE : ")
science=input()
print("Please enter the marks of HISTORY : ")
history=input()
print('******************************************************************')
print("------------------RESULT OF ",student_name.upper(),"--------------")
print('******************************************************************')
percentages=(total*100)/500
#float(percentages)
print("Total marks are : ",total)
print("Percentages : ",percentages)
if percentages > 33 :
print(student_name.upper()," is Passed ")
else :
print(student_name.upper()," is Failed ")
#Output
*********************************************************
*********
--------------STUDENT ACADEMIC MANAGEMENT
SYSTEM------------------
*********************************************************
*********
Please enter enrollment number of student :
101
Please enter name of the student :
Tushar
Please enter the marks of HINDI :
95
Please enter the marks of ENGLISH :
90
Please enter the markts of MATH :
98
Please enter the marks of SCIENCE :
98
Please enter the marks of HISTORY :
80
*********************************************************
*********
------------------RESULT OF TUSHAR --------------
*********************************************************
*********
Total marks are : 461
Percentages : 92.2
TUSHAR is Passed
# Output
**********SIMPLE INTEREST CALCULATION SYSTEM********
PLEASE ENTER THE LOAN AMOUNT : 65000
PLEASE ENTRE THE ANNUAL RATE : 13
PLEASE ENTER THE TIME PERIOD IN YEARS : 1
**************CALCULATION METHOD****************
HOW DO YOU WANT TO CALCULATE THE SI ?
1.YEARLY
2.HALF YEARLY
3.QUATERLY
4.MONTHLY
YOUR CHOICE : 1
**************************************************
# Inventory System
def choice(menu_choice):
while menu_choice==0 or menu_choice>2:
menu_choice=int(input("INVALID CHOICE! PLEASE CHOOSE
VALID ONE : "))
return menu_choice
#--------------------------------SALE
PRODUCT---------------------------------------------
elif menu_choice==2 and added!=0:
customer_name=input("CUSTOMER NAME \t\t:\t ")
product=int(input("ENTER PRODUCT ID \t\t:\t "))
sale_product(customer_name,product)
else:
print("PLEASE ADD ITEM FIRST")
print("*********************************************************")
print("\t\tADD PRODUCT TO INVENTORY")
print("*********************************************************\n
")
to_be_added=int(input("HOW MANY PRODUCTS YOU WANT TO
ADD : "))
items=dict()
for x in range(1,to_be_added+1,+1):
product_id=int(input("PRODUCT ID\t\t:\t"))
product_name=input("PRODUCT NAME\t\t:\t")
product_brand=input("PRODUCT BRAND\t\t:\t")
product_model=product_brand+"-"+input("PRODUCT
MODEL\t\t:\t")
in_stock=int(input("ENTER QUANTITY\t\t:\t"))
print("Product have been added successfully...!")
item={'PRODUCT_ID ':product_id,'PRODUCT_NAME
':product_name,'PRODUCT_BRAND ':product_brand,'PRODUCT_MODEL ':
product_model,'AVAILABLE ':in_stock}
items.update({x:item})
add+=1
print(items)
return add
#*********************************SALE PRODUCT FUNCTION
DEFINITION AND DECLARATION****************************
def sale_product():
print("Executed")
#^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -- MAIN --
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
def main_menu():
added=0;
print("*********************************************************")
print("\t\tINVENTORY SYSTEM")
print("*********************************************************")
print("1. ADD PRODUCT")
print("2. SALE PRODUCT\n")
menu_choice=int(input("PLEASE ENTER YOUR CHOICE : "))
menu_choice=choice(menu_choice)
if menu_choice==1:
added=add_product(added)
main_menu()
elif menu_choice==2 and added!=0:
print("EXECUTED")
else:
print("NOT PRODUCT AVAILABLE PLEASE ADD FIRST")
main_menu()
main_menu()
# Output
(X) String Handling
String
str is is used to represent String
String is collection of characters enclosed with either single quotes ('') or in
double quotes ("")
ie.
abc='Techavera Solutions Pvt Ltd'
type(abc)
<class 'str'>
abc="Techavera Solutions Pvt Ltd"
type(abc)
<class 'str'>
Multiline Strings
we can represent multiline string either triple single quotes (''' Techavera Python
Trainer ''') or in triple double quotes (""" Techavera Python Trainer""")
i.e
abc='''Welcome To
techavera
Solutions
Pvt. Ltd.'''
type(abc)
#<class 'str'>
print(abc)
# Welcome To
techavera
Solutions
Pvt. Ltd.
abc="""Welcome To
techavera
Solutions
Pvt. Ltd."""
type(abc)
#<class 'str'>
print(abc)
# Welcome To
techavera
Solutions
Pvt. Ltd.
Indexing
In python both +ve and -ve indexes are available
s='PYTHON'
print(s[0])
print(s[-1])
print(s[-3])
print(s[2])
#print(s[110]) error
ie <<<< .......--------3-2-1
s= 'Vikash kumar sarraf Techavera solutions Pvt Ltd Python Trainer'
0123456789.................................................>>>>
print(s[4]) #---->e
print(s[-3]) # ---->n
slicing
syntax
end=end-1
|
var[begin : end : step]
| | |
Note
* if step is +ve then we should move in forword direction (Left to Right)
* if step is -ve then we should move in backward direction (Right to Left)
* if step is +ve then we should move in forword direction (begin to end)
* if step is -ve then we should move in backward direction (begin to end)
In step is +ve
default value for begin -------->0
default value for end -------->length of string
In step is -ve
default value for begin -------->-1
default value for end -------->(length of string+1)
# Output
Enter string: NitiN
NitiN
NitiN is palindrome
Rerun
Enter string: Vikash
peednaS
Vikash is not palindrome
Access of string
1. By using indexing
s='PYTHON'
print(s[4])
print(s[-4])
# Output
O
T
2. By using slicing
s='Manisha Yadav'
s[2:7:]
# Output
'nisha'
l='Learning Python is very Easy'
print(l[9:15:1])
print(l[-1:-10:-1])
# Output
Python
ysaE yrev
3. By using loops
pytag_line='We Can Develop Any Type Of Application By using Python '
a=len(pytag_line)
i=0
while i<a:
print(pytag_line[i],end='')
i=i+1
# Output
We Can Develop Any Type Of Application By using
Python
# Output
Learning Python is very Easy
# Output
Forward direction
L e a r n i n g P y t h o n i s v e r y e a s
y ! ! !
Backward direction
! ! ! y s a e y r e v s i n o h t y P g n i
n r a e L
# Output
Welcome To techavera
Solutions Pvt. Ltd. Noida
# Output
We can develop Any type of application by using
Python
Method of String
# Output
WE CAN DEVELOP ANY TYPE OF APPLICATION BY USING
PYTHON
we can develop any type of application by using
python
We can develop any type of application by using
python
3. replace(str,str)
s= 'Vikash kumar sarraf'
print(s.replace('sharma','verma'))
# Output
Vikash kumar verma
# Output
Learning python is very hard
4. split( )
# Output
['S', 'ndeep kum', 'r sh', 'rm', '']
# Output
['We', 'can', 'develop', 'any', 'type', 'of',
'application', 'by', 'using', 'python']
# Output
['W', ' can d', 'v', 'lop any typ', ' of application
by using python']
# Output
Enter password 'Sandeep': Sandeep
Please enter Your Correct Pasword
With strip()
# Output
Enter password 'Sandeep': Sandeep
Hello Sandeep Welcome
6. lstrip()
s=input("""Enter 'Sandeep':""")
a=s.lstrip()
if a=='Sandeep':
print("Hello class GM")
else:
print("Please enter Sandeep")
# Output
Enter 'Sandeep': Sandeep
Hello class GM
7. rstrip()
# Output
Enter password 'Sandeep': Sandeep
Hello Sandeep Welcome
8. capitalize()
s='python programming Language'
print(s.capitalize())
# Output
Python programming language
9. index(obj)
s='python Programming language'
print(s.index('P'))
# Output
7
# Output
1
# Output
22
10.count(obj)
s='python programming language'
print(s.count('python'))
# Output
1
# Output
1
# Output
4
# Output
Enter string:Vikash kumar sarraf
Number of vowels are:
7
# Output
Enter any string to remove vowels: Shyam Babu Sharma
Removing vowels from the given string
New string after removed all the vowels:
Shym Bb Shrm
# Output
Enter Some String:Shyam babu Sharma
['Shyam', 'babu', 'Sharma']
Sharma babu Shyam
# Output
Enter Some String:Vikash kumar sarraf
peednaS ramuK amrahS
1.
# Output
Enter Some String:Vikash Characters
at Even Position: Snep Characters
at Odd Position: ade
2.
# Output
Enter Some String:Vikash
Characters at Even Position:
S,n,e,p,
Characters at Odd Position:
a,d,e,
# Output
Enter First String:Vikash Enter
Second String:Techavera
STaencdheaevpera
(XI) List
List is the colletion of hetrogenious object where insertion order is preserved &
duplicates are allowed.
It is mutable & represented by [ ]
C ---------- Create
R ----------- Read
U ----------- Update
D ---------- Delete
list1=[1,2,True,"Python",1.5,3+4j,1,2,1,2]
print(list1)
print(type(list1))
# Output
[1, 2, True, 'Python', 1.5, (3+4j), 1, 2, 1, 2]
<class 'list'>
Creation of list
1. by using [ ]
l=eval(input('Enter List Element:'))
print(l)
#Output
Enter List Element:[10,20,21,11,11,2,3]
[10, 20, 21, 11, 11, 2, 3]
list1=[1,2,True,"Python",1.5,3+4j,1,2,1,2]
print(list1)
#Output
[1,2,True,"Python",1.5,3+4j,1,2,1,2]
2 by using list()
i=(10,20,True,'python')
print(type(i))
l=list(i)
print(l)
print(type(l))
#Output
‘’’<class 'tuple'>
[10, 20, True, 'python']
<class 'list'>’’’
tup=(1,2,True,"Python",1.5,3+4j,1,2,1,2,'Barish')
print(type(tup))
print(tup)
lis=list(tup)
print(type(lis))
print(lis)
# Output
<class 'tuple'>
(1, 2, True, 'Python', 1.5, (3+4j), 1, 2, 1, 2,
'Barish')
<class 'list'>
[1, 2, True, 'Python', 1.5, (3+4j), 1, 2, 1, 2,
'Barish']
3. By using list comprehension
List comprehension
Write the logic to generate list Element is called List Comprehension.
# Output
[1, 4, 27, 256, 3125, 46656, 823543, 16777216,
387420489]
4. By using split()
# Output
['Learning', 'Python', 'is', 'Very', 'easy']
Accessing of list
2. By using indexing
i=[10,20,True,'python']
print(i[2])
# Output
True
list1=[1,2,True,"Python",1.5,3+4j,1,2,1,2,'Barish']
print(list1[5])
# Output
3+4j
3. By using slicing
i=[10,20,True,'python']
print(i[1:3])
# Output
[20, True]
list1=[1,2,True,"Python",1.5,3+4j,1,2,1,2,'Barish']
print(list1[2:50:2])
# Output
[True, 1.5, 1, 1, 'Barish']
[ ]:
list1=[1,2,True,"Python",1.5,3+4j,1,2,1,2,'Barish']
print(list1[::-1])
# Output
['Barish', 2, 1, 2, 1, (3+4j), 1.5, 'Python', True,
2, 1]
4. By using loop
i=[10,20,True,'python']
for x in i:
print(x)
# Output
‘’’10
20
True
python’’’
i=[10,20,True,'python']
x=0
while(x<len(i)):
print(i[x])
x+=1
# Output
‘’’10
20
True
python’’’
n=[0,1,2,3,4,5,6,7,8,9,10]
for n1 in n:
if n1%2==0:
print(n1)
# Output
0
2
4
6
8
10
l=["A","B","C"]
x=len(l)
for i in range(x):
print(l[i],"is available at index: ",i,"and at index: ",i-x)
# Output
A is available at index: 0 and at index: -3
B is available at index: 1 and at index: -2
C is available at index: 2 and at index: -1
Built-in-function of list
max(Object)
min(obj)
len(obj)
list(obj)
i=[10,20,1,50,500,-600]
print(max(i))
print(min(i))
print(len(i))
# Output
500
-600
6
j=['A','P','z']
print(max(j))
# Output
z
Method of list
i=[10,20,1,50,500,-600]
i.append('Hankit')
print(i)
# Output
[10, 20, 1, 50, 500, -600, 'Python']
# Output
[10, 20, 'Python', 1, 50, 500, -600]
# Output
[1, 2, 'Python', 'Ajgar wale gupta', 'Tabish', True,
'A', 'Saurabh']
3. remove(obj) take exactly one argument
i=[10,20,1,50,500,-600,1]
i.insert(2, 'Python')
print(i)
i.remove(1)
print(i)
# Output
[10, 20, 'Python', 1, 50, 500, -600, 1]
[10, 20, 'Python', 50, 500, -600, 1]
# Output
[10, 20, 1, 50, 500]
i=[10,20,1,50,500,-600]
i.pop()
print(i)
i.pop(2)
print(i)
# Output
[10, 20, 1, 50, 500]
[10, 20, 50, 500]
# Output
[1, 2, 'Python', 'Ajgar wale gupta', 'Tabish',
True, 'A', 'Saurabh']
[1, 2, 'Python', 'Ajgar wale gupta', 'Tabish',
True, 'Saurabh']
Saurabh
Ajgar wale gupta
[1, 2, 'Python', 'Tabish', True]
i=[10,20,1,50,500,-600,'Uttkarsh','Prachi']
uttkarsh= i
print(id(uttkarsh))
print(id(i))
prachi= i.copy() # no arg
print(id(prachi))
print(prachi)
print(i)
# Output
140362773960392
140362773960392
140362773906824
[10, 20, 1, 50, 500, -600, 'Uttkarsh', 'Prachi']
[10, 20, 1, 50, 500, -600, 'Uttkarsh', 'Prachi']
list1=[1,2,'Python','Python wale gupta',True,1,2,34]
sl1=list1
print(id(sl1))
print(id(list1))
print(sl1)
dp1=list1.copy()
list1.append('Tanmay')
print(id(dp1))
print(dp1)
print(sl1)
# Output
140362834039816
140362834039816
[1, 2, 'Python', 'Python wale gupta', True, 1, 2,
34]
140362773909064
[1, 2, 'Python', 'Python wale gupta', True, 1, 2,
34]
[1, 2, 'Python', 'Python wale gupta', True, 1, 2,
34, 'Tanmay']
# Output
[]
7. reverse() no-arg
i=[10,20,1,50,500,-600,'Uttkarsh','Prachi']
i.reverse()
print(i)
# Output
['Prachi', 'Uttkarsh', -600, 500, 50, 1, 20, 10]
8. sort() no-arg
i=[10,20,1,50,500,-600]
i.sort()
print(i)
# Output
[-600, 1, 10, 20, 50, 500]
i=['A','python']
i.sort()
print(i)
# Output
['A', 'python']
i2=['Ujjwal','Shivesh']
i2.sort()
print(i2)
# Output
['Shivesh', 'Ujjwal']
9 count(obj)
i=[10,20,1,1,1,1,2,2,2,50,500,-600]
print(i.count(1))
# Output
4
10. index(obj)
i=[10,20,1,1,1,1,2,2,2,50,500,-600]
print(i.index(500))
11. extend(obj)
x = [1, 2, 3]
x1=[4,5,6,7]
x.extend(x1)
print (x)
# Output
[1, 2, 3, 4, 5, 6, 7]
Nested List
l =[10,20,30,[True,'Phython']]
print(len(l))
print(l)
Accessing of list
# Output
[10, 20, 30, [True, 'Phython']]
by using indexing
l =[10,20,30,[True,'Phython']]
l[3]
# Output
[True, 'Phython']
l =[10,20,30,[True ,[1,2,3]],'Phython']
print(l)
print(l[3][1][0])
# Output
[10, 20, 30, [True, [1, 2, 3]], 'Phython']
1
by using slicing
l =[10,20,30,[True,'Phython']]
print(l[3::2])
# Output
[[True, 'Phython']]
l =[[10,20,30],
[40,50,60],
[60,70,80]]
print(l)
print(l[0])
print(l[1])
print(l[2])
Tuple
Tuple
Tuple is the colletion of hetrogenious object where insertion order is preserved
& duplicates are allowed.
It is immutable & represented by ()
tuple1=(1,2,True,"Python",1.5,3+4j,1,2,1,2)
print(tuple1)
print(type(tuple1))
# Output
(1, 2, True, 'Python', 1.5, (3+4j), 1, 2, 1, 2)
<class 'tuple'>
tuple1=(1,2,True,"Python",1.5,3+4j,1,2,1,2)
print(tuple1)
tuple1[2]= 'program'
# Output
(1, 2, True, 'Python', 1.5, (3+4j), 1, 2, 1, 2)
--------------------------------------------------
-------------------------
TypeError
Traceback (most recent call last)
<ipython-input-34-d45483c92703> in <module>()
1
tuple1=(1,2,True,"Python",1.5,3+4j,1,2,1,2)
2 print(tuple1)
----> 3 tuple1[2]= 'program'
4
5 # Output
Cretion of tuple
1. by using ( )
# Output
Enter tuple Elements:(1, 2, True, 'Python', 1.5,
(3+4j), 1, 2, 1, 2)
(1, 2, True, 'Python', 1.5, (3+4j), 1, 2, 1, 2)
tuple1=(1,2,True,"Python",1.5,3+4j,1,2,1,2)
print(tuple1)
# tuple[1]=5 immuatable behaviour
# Output
(1, 2, True, 'Python', 1.5, (3+4j), 1, 2, 1, 2)
2 . by using tuple()
i=[10,20,True,'python']
print(type(i))
l=tuple(i)
print(l)
print(type(l))
# Output
<class 'list'>
(10, 20, True, 'python')
<class 'tuple'>
Accessing of tuple
# Output
(10, 20, True, 'python')
2. By using loop
i=(10,20,True,'python')
for x in i:
print(x)
# Output
10
20
True
python
While loop
i=[10,20,True,'python']
x=0
while x<len(i):
print(i[x])
x+=1
# Output
10
20
True
python
3. By using indexing
i=(10,20,True,'python')
print(i[-1])
# Output
python
4. By using slicing
i=(10,20,True,'python')
print(i[1:3])
# Output
(20, True)
Built-in-function of tuple
max(Obj)
min(obj)
len(obj)
tuple(obj)
i=(10,20,1,50,500,-600)
print(max(i))
print(min(i))
print(len(i))
# Output
500
-600
6
method of tuple
count(obj)
i=(10,20,True,'python',20,20,30,40,50,True,10,10,10)
print(i.count(10))
# Output
4
index(obj)
i=(10,20,True,'python',20,20,30,40,50,True,10,10,10)
print(i.index(True))
# Output
2
Tuple Comprehension
Not supported
Tuple Packing and Unpacking:
Packing
a=10
b=20
c=30
d=40
t=a,b,c,d
print(type(t))
print(t)
# Output
<class 'tuple'>
(10, 20, 30, 40)
Unpacking
t=(10,20,30,40)
a,b,c,d=t
t=(10,20,30,40)
a,b,c,d=t
print(a)
print(b)
# Output
10
20
Q. Write a program to take a tuple of numbers from the
keyboard and print its sum and average?
# Output
Enter Tuple of Numbers:(10,20,30,40,50,60)
The Sum= 210
The Average= 35.0
Set
set
set is the collection of hetrogenois object where insertion order is not preserved
and duplicate are not allowed.
It is mutable & represented by { }
Note-
indexing & slicing concept is not applicable for set
(Q) Why indexing & slicing concept is not applicable for sets
d={100,'Python','Abhi',101,100,101,104,105,True}
print(d)
# d[5]=10 Indexing not applicable for set
print(d)
# Output
{True, 100, 101, 104, 105, 'Python', 'Abhi'}
{True, 100, 101, 104, 105, 'Python', 'Abhi'}
Creation of set
1. By using { }
# Output
d=eval(input('Enter set Elements:'))
print(d)
d={100,'Python','Abhi',101,100,101,104,105,True}
print(d)
# Output
{True, 100, 101, 104, 105, 'Python', 'Abhi'}
<class 'set'>
Note-
{ & } represent dict not set.
b=set()
print(type(b))
print(b)
b.add(10)
print(b)
# Output
<class 'set'>
set()
{10}
2. By using set() function
a=set()
a.add(10)
print(type(a))
print(a)
# Output
<class 'set'>
{10}
l=[10,20,30,40]
s=set(l)
print(s)
# Output
{40, 10, 20, 30}
Accessing of set
d={100,'Python','Abhi',101,100,101,104,105,True}
print(d)
# Output
{True, 100, 101, 104, 105, 'Python', 'Abhi'}
2. By using loops
d={100,'Python','Abhi',101,100,101,104,105,True}
for x in d:
print(x)
# Output
True
100
101
104
105
Python
Abhi
Methods of set
# Output
{'Python', 100, 'Rajkumari', 'Abhi'}
# Output
{'Python', 'Abhi'}
# Output
{'Python', 100, 'Abhi'}
# Output
{100, 'Python'}
5. difference(obj)
d={100,10,3,2,5,6}
e={100,101,104,105,1,3,4}
print(d.difference(e)) #10,5,2,6
# Output
{2, 10, 5, 6}
6. intersection(obj1,obj2,obj3............)
d={100,10,3,2,5,6,4}
e={100,101,104,105,1,3,4}
f={1,5,6,8,7,10,4}
g=d.intersection(e,f)
print(g)
# Output
{4}
7. union(obj1,obj2,obj3............)
d={100,10,3,2,5,6,4}
e={100,101,104,105,1,3,4}
f={1,5,6,8,7,10,4}
g=d.union(e,f)
print(g)
# Output
{1, 2, 3, 100, 5, 6, 4, 101, 104, 10, 105, 7, 8}
8. clear() no-arg
d={100,'Python','Abhi'}
print(d)
d.clear()
print(d)
# Output
{'Abhi', 100, 'Python'}
set()
9. copy() no-arg
d={100,'Python','Abhi'}
print(d)
e=d.copy()
print(e)
# Output
{'Abhi', 100, 'Python'}
{'Abhi', 100, 'Python'}
10 update(obj)
d={100,'Python','Abhi'}
e={1,2,3}
d.update(e)
print(d)
# Output
{'Abhi', 1, 2, 100, 3, 'Python'}
d={100,'Python','Abhi'}
e={1,2,3}
f={10,20,30}
print(d)
d.update(e,f)
print(d)
# Output
{'Abhi', 100, 'Python'}
{1, 2, 3, 100, 20, 'Python', 'Abhi', 10, 30}
# Output
Enter list elements: [10,10,10,2,2,3,3,4,5,6.5]
[2, 3, 4, 5, 6.5, 10]
w = input('Enter A Word:')
s= set(w)
v= {'a','e','i','o','u'}
d=s.intersection(v)
print(d)
# Output
Enter A Word:Vikash
{'e', 'a'}
Dictionary
dict
dict is the collection of key, value pairs where insertion order is not preserved
and duplicate keys are not allowed while value can be duplicate.
Syntax
ref var={key1:value,key2:value,............keyn:value}
d={'Abhi':101,100:100,104:105,1:'Vikash',1:100}
print(d)
print(type(d))
# Output
{'Abhi': 101, 100: 100, 104: 105, 1: 100}
<class 'dict'>
reference_var[key]=value
reference_var[key]
del reference_var[key]
del reference_var
d={100:'Python','Abhi':101,104:105}
d[106]='soni'
d[100]='Manisha'
d['Anurag']='soni'
print(d)
i.e 2
d={}
d[106]='soni'
d[100]='soni'
d['Anurag']='vinod'
print(d)
d[100]=100
print(d)
d={100:'Python','Abhi':101,104:105}
d[106]='Vinod'
d[100]='soni'
print(d)
d[100]='Tabish'
del d[104]
print(d)
# Output
{100: 'soni', 'Abhi': 101, 104: 105, 106: 'Vinod'}
{100: 'Tabish', 'Abhi': 101, 106: 'Vinod'}
d={'Abhi':101,100:101,104:105,3+4j:'Vikash'}
d['Satyam']='Satyam'
print(d)
print(d[100])
del d['Abhi']
print(d)
del d
print(d)
# output
{'Abhi': 101, 100: 101, 104: 105, (3
+4j): 'Vikash', 'Satyam': 'Satyam'}
101
{100: 101, 104: 105, (3+4j): 'Vikash', 'Satyam':
'Satyam'}
--------------------------------------------------
-------------------------
NameError
Traceback (most recent call last)
<ipython-input-54-b58282aad346> in <module>()
6 print(d)
7 del d
----> 8 print(d)
9
10 # Output
Creation of dict
By using { }
# Output
Enter Dict Elements:
{10:20,'Satyam':101,101:102,102:102}
{10: 20, 'Satyam': 101, 101: 102, 102: 102}
<class 'dict'>
d={'Abhi':101,100:101,104:105,3+4j:'Vikash'}
print(d)
# Output
{'Abhi':101,100:101,104:105,3+4j:'Vikash'}
Accessing of dict
# Output
{'Abhi':101,100:101,104:105,3+4j:'Vikash'}
2. By using key
d={100:'Python','Abhi':101,104:105}
print(d[100])
print(d['Abhi'])
# Output
Python
101
3. By using loops
d={100:'Python','Abhi':101,104:105}
for x in d:
print(x)
print(d[100])
print(d['Abhi'])
# Output
100
Abhi
104
Python
101
rec={}
n=int(input("Enter number of students: "))
i=1
while i <=n:
name=input("Enter Student Name: ")
marks=input("Enter % of Marks of Student: ")
rec[name]=marks
i=i+1
print("Name of Student","\t","% of marks")
for x in rec:
print("\t",x,"\t\t",rec[x])
# Output
Enter number of students: 2
Enter Student Name: Sandy
Enter % of Marks of Student: 80
Enter Student Name: Mandy
Enter % of Marks of Student: 85
Name of Student % of marks
Sandy 80
Mandy 85
rec={}
n=int(input("Enter number of students: "))
for a in range(1,n+1):
name=input("Enter Student Name: ")
marks=input("Enter % of Marks of Student: ")
rec[name]=marks
print("Name of Student","\t","% of marks")
for x in rec:
print("\t",x,"\t\t",rec[x])
Methods of dict
1. get(key,deafult)
i.e 1
d={100:'Python','Abhi':101,104:'Pratiksha'}
print(d.get(104,'Please enter valid key'))
print(d)
# Output
Pratiksha
{100: 'Python', 'Abhi': 101, 104: 'Pratiksha'}
ie. 2
d={100:'Python','Abhi':101,104:105}
print(d.get('Anurag','Please enter valid key'))
print(d)
# Output
Please enter valid key
{100: 'Python', 'Abhi': 101, 104: 105}
2. setdefault(key,value)
d={100:'Python','Abhi':101,104:'Pratiksha'}
print(d.setdefault(104,'B.tech'))
print(d)
# Output
Pratiksha
{100: 'Python', 'Abhi': 101, 104: 'Pratiksha'}
d={100:'Python','Abhi':101,104:'Pratiksha'}
print(d.setdefault('Hina','B.tech'))
print(d)
# Output
B.tech
{100: 'Python', 'Abhi': 101, 104: 'Pratiksha',
'Hina': 'B.tech'}
d={100:'Python','Abhi':101,104:105}
print(d.setdefault(104,'Please enter valid key'))
print(d)
# Output
105
{100: 'Python', 'Abhi': 101, 104: 105}
# Output
dict_items([(100, 'Python'), ('Abhi', 101), (104,
105)])
# Output
dict_keys([100, 'Abhi', 104])
# Output
dict_values(['Python', 101, 105])
6. pop(key)
d={100:'Python','Abhi':101,104:105}
print(d.pop(104))
print(d)
# Output
105
{100: 'Python', 'Abhi': 101}
7. clear() no-arg
d={100:'Python','Abhi':101,104:105}
print(d.clear())
print(d)
# Output
{}
# Output
{100: 'Python', 'Abhi': 101, 104: 105}
{100: 'Python', 'Abhi': 101, 104: 105}
9. update(dictobj)
d={100:'Python','Abhi':101,104:105}
a={1:2,2:3,3:4}
d.update(a)
print(d)
# Output
{100: 'Python', 'Abhi': 101, 104: 105, 1: 2, 2: 3,
3: 4}
Functions
functions
If a group of statements is repeatedly required then it is not recommended to
write these statements everytime seperately.We have to define these statements
as a single unit and we can call that unit any number of times based on our
requirement without rewriting.
This unit is nothing but function.
The main advantage of functions is code Reusability.
1. Built in Functions:
The functions which are coming along with Python software automatically,are
called built
in functions or pre defined functions
Eg:
id()
type()
input()
eval()
etc..
Syntax
def func_Name(parameter):
'''doc-string''' # optional
function Suite
return expression
def demo():
'doc-string' # optional
print("Hello Class GM")
demo()
#Output
Hello Class GA
Parameter
Parameters are input to the functions. It is also called arguments.
There are various types of argumnets in Python
Types of parameter
def add(a,b):
print(a+b)
print(a-b)
print(a*b)
print(a/b)
add(10,20)
# Output
30
-10
200
0.5
10
The number of arguments and position of arguments must be matched. If we
change the order then result may be changed.
If we change the number of arguments then we will get error.
def satyam(a,b):
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a)
print(b)
x=int(input("Enter Number:"))
y=int(input("Enter Number:"))
satyam(x,y)
# Output
Enter Number:5
Enter Number:6
11
-1
30
0.8333333333333334
2. keyword argument
We can pass argument values by keyword i.e by parameter name.s
Caller identifiy the positioning of required arguments.
def add(a,b):
print(a+b)
print(a-b)
print(a*b)
print(a/b)
add(b=10,a=20)
# Output
30
10
200
2.0
20
def satyam(a,b):
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a)
print(b)
x=int(input("Enter Number:"))
y=int(input("Enter Number:"))
satyam(b=x,a=y)
#Output
Enter Number:5
Enter Number:2
7
-3
10
0.4
2
5
Note-
required argument does not follow keyword argument
positional argument follows keyword argument
def satyam(a,b):
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a)
print(b)
x=int(input("Enter Number:"))
y=int(input("Enter Number:"))
satyam(y,b=x)
3. default argument
Sometimes we can provide default values for our positional arguments.
ie. 1
def add(a=50,b=20):
print(a+b)
print(a-b)
print(a*b)
print(a/b)
add()
# Output
70
30
1000
2.5
Rerun
180
20
8000
1.25
Note-
If we are not passing any name then only default value will be considered.
i.e 2
def add(a=100,b=200):
print(a+b)
print("Hello Class GM")
add(10,20)
# Output
30
Hello Class GM
i.e 3
def add(a=100,b=200):
print(a+b)
print("Hello Class GM")
add(10)
# Output
210
Hello Class GM
def f1(*var):
We can call this function by passing any number of arguments including zero
number.
Internally all these values represented in the form of tuple.
i.e 2
def add(*argu):
print("Hello i am in var-arg parameter")
print("Hello Class GM")
add()
add(1,'Abhi')
add(1,'Abhi',100,1000)
# Output
Hello i am in var-arg parameter
Hello Class GM
Hello i am in var-arg parameter
Hello Class GM
Hello i am in var-arg parameter
Hello Class GM
i.e. 2
def prachi(*prachi):
print("Hello i am in var-arg parameter")
print("Hello Class GM")
print("Hello i am in var-arg parameter")
print("Hello Class GM")
prachi()
prachi(12)
ie 3
def sum(*n):
total=0
for n1 in n:
total=total+n1
print(total)
sum(10,20,30)
# Output
10
30
60
def display(**kwargs):
for k,v in kwargs.items():
print(k,"=",v)
display(n1=10,n2=20,n3=30)
display(rno=100,name="Vikash",marks=70,subject="Python")
Note-
def add(a,b):
return a+b
c=add(10,20)
print('The Sum:',c)
# Output
The Sum: 30
def add(a,b):
return a+b
print('Ajgar wale Gupta g')
print('Aman Wale Gupta g')
c=add(10,20)
print('The Sum:',c)
# Output
The Sum: 30
def tiwari(a,b):
c=a+b
print('Tiwari Abhishek')
return c
x=tiwari(10,50.5)
print(x)
# Output
Tiwari Abhishek
60.5
2. return multiple value
def add_sub(a,b):
return a+b,a-b
c,d=add_sub(10,20)
print('The Sum is :',c,'and Substarction is:',d)
# Output
The Sum is : 30 and Substarction is: -10
def add_sub(a,b):
return a+b,a-b,a*b,a/b
x,y,z,p=add_sub(10,20)
print("Sum:",x,"Sub:",y,'mul:',z,'Div',p)
# Output
Sum: 30 Sub: -10 mul: 200 Div 0.5
def add_sub(a,b):
e=a+b
f=a-b
g=a*b
h=a/b
return e,f,g,h
x,y,z,p=add_sub(10,20)
print("Sum:",x,"Sub:",y,'mul:',z,'Div',p)
# Output
Sum: 30 Sub: -10 mul: 200 Div 0.5
variables
Variables are named memory location used to store data.
There are two types of variables in functional Python.
Local
Global
c=10
d=50
def add(a,b):
x=eval(input('Enter First number for math operations'))
y=eval(input('Enter First number for math operations'))
print(c*d)
print(a*b)
print(a+b)
print(a/b)
print(a-b)
print(x+y)
print(x-y)
print(x/y)
print(x-y)
print("Hello Class GM")
print("Hello")
print("Python")
add(b=10,a=20)
print(c+d)
print(c,d)
print(x+y)
# Output
Enter First number for math operations50
Enter First number for math operations60
500
200
30
2.0
10
110
-10
0.8333333333333334
-10
Hello Class GM
Hello
Python
60
10 50
20
Anonymous function
Syntax
s=lambda a,b:(a+b)
print('The Sum',s(10,20))
# Output
The Sum 30
tiwari=lambda a,b:a-b
print('The Sub',tiwari(10,20))
# Output
The Sub -10
# Output
PLEASE ENTER A NUMBER TO FIND FACT : 5
THE FACTORIAL OF 5 IS : 120
Recursion
A function call itself is called recursion .
def factorial(n):
if(n <= 1):
return 1
else:
result=n*factorial(n-1) #5* 4* 3 *2
return(result)
n = int(input("Enter number:"))
print("Factorial:")
print(factorial(n))
# W.A.P to input a number a print its factorial by using recursion
# Output
Enter number for factorial:5
120
filter() function
We can use filter() function to filter values from the given sequence based
on some condition.
Syntax
filter(function,sequence)
where function argument is responsible to perform conditional check
sequence can be list or tuple or string.
without lambda
def isEven(x):
if x%2==0:
return True
else:
return False
l=[0,5,10,15,20,25,30]
l1=list(filter(isEven,l))
print(l1) #[0,10,20,30]
# Output
[0, 10, 20, 30]
with lambda
l=[5,4,1,2,10,15,9,80,70,80]
l1=list(filter(lambda x:x%2==0,l))
print(l1)
#Output
[4, 2, 10, 80, 70, 80]
l=eval(input('Enter List:'))
l1=list(filter(lambda x:x%2==0,l))
print(l1)
#Output
Enter List:[10,11,12,13,14,15,16]
[10, 12, 14, 16]
l=eval(input('Enter List'))
l1=list(filter(lambda x:x**2,l))
print(l1)
map()
syntax
map(function,sequence)
The function can be applied on each element of sequence and generates new
sequence.
i.e.
l=[5,4,1,2,10,15,9,80,70,80]
l1=list(map(lambda x:3*x,l))
print(l)
print(l1)
# Output
[5, 4, 1, 2, 10, 15, 9, 80, 70, 80]
[15, 12, 3, 6, 30, 45, 27, 240, 210, 240]
l=eval(input('Enter List:'))
l1=list(map(lambda x:x**2,l))
print(l1)
#Output
Enter List:[10,12,13,14,5,45,10,80]
[10, 12, 13, 14, 5, 45, 10, 80]
[100, 144, 169, 196, 25, 2025, 100, 6400]
reduce()
syntax
reduce(function,sequnce)
reduce() function present in functools module and hence we should write import
statement.
i.e
#Output
276
from functools import *
l=eval(input('Enter List:'))
result=reduce(lambda x,y:x+y,l)
print(result)
#Output
Enter List:[10,12,13,14,5,45,10,80]
189
i.e.
# Output
24192000000
Function Aliasing:
For the existing function we can give another name, which is nothing but
function aliasing.
def wish(name):
print("Good Morning:",name)
greeting=wish
print(id(wish))
print(id(greeting))
greeting('Sandy')
wish('Vikash')
# Output
139894472885520
139894472885520
Good Morning: Sandy
Good Morning: Vikash
# Output
Enter Any Name:Vikash
140197875752472
140197875752472
Good Morning: Vikash
Good Morning: Vikash
Note:
In the above example only one function is available but we can call that
function by using either wish name or greeting name.
If we delete one name still we can access that function by using alias name
Nested Functions:
We can declare a function inside another function, such type of functions are
called Nested functions.
def outer():
print("outer function started")
def inner():
print("inner function execution")
print("outer function calling inner function")
inner()
outer()
#inner() Error
# Output
outer function started
outer function calling inner function
inner function execution
Note-
In the above example inner() function is local to outer() function and hence it is
not possible to call directly from outside of outer() function.
def outer():
print("outer function started")
def inner():
print("inner function execution")
print("outer function calling inner function")
return inner()
outer()
# Output
outer function started
outer function calling inner function
inner function execution