Python Programming Language Overview
Python Programming Language Overview
Basics of languages
What is language ?
Why it is required ?
Type of languages ?
What is Low level languages (Machine & assembly language)?
What is high level languages ()?
Python Introduction
Python is a :
1. Free and Open Source
2. General-purpose
purpose
3. High Level Programming language
Features/Advantages of Python:
1. Simple and easy to learn
2. Procedure and object oriented
3. Platform Independent
4. Portable
5. Dynamically Typed
6. Both Procedure Oriented and Object Oriented
7. Interpreted
8. Vast Library Support
Syntex:----
Example 1:-
C:
#include<stdio.h>
void main()
{
print("Hello world");
}
Python:
print("Hello World")
Python:
A,b=10,20
print("The Sum:",(a+b))
Limitations of Python:
1. Performance and Speed: Python is an interpreted language, which
means that it is slower than compiled languages like C or Java. This
can be a problem for certain types of applications that require high
performance, such as real-time systems or heavy computation.
2. Done Not have Support for Concurrency and Parallelism: Python
does not have built-in support for concurrency and parallelism. This
can make it difficult to write programs that take advantage of multiple
cores or processors.
3. Static Typing: Python is a dynamically typed language, which means
that the type of a variable is not checked at compile time. This can
lead to errors at runtime.
4. Web Support: Python does not have built-in support for web
development. This means that programmers need to use third-party
frameworks and libraries to develop web applications in Python
5. Runtime Errors
Python can take almost all programming features from different languages:--
1. Functional Programming Features from C
2. Object Oriented Programming Features from C++
3. Scripting Language Features from Perl and Shell Script
4. Modular Programming Features from Modula-3(Programming Language)
Flavors of Python or types of python interpretors:
1. CPython:
It is the standard flavor of Python. It can be used to work with C lanugage
Applications
2. Jython or JPython:
It is for Java Applications. It can run on JVM
3. IronPython:
It is for C#.Net platform
4. PyPy:
The main advantage of PyPy is performance will be improved because JIT
(just in time)compiler is available inside PVM.
5. RubyPython
For Ruby Platforms
6. AnacondaPython
It is specially designed for handling large volume of data processing.
Python Internal working
Each of these steps occurs behind the scenes, making Python a powerful and
flexible language.
Source Binary_Code /
Byte_Code PVM O/P
Code/Program Machine_Code
Python interpretor
Examples:---
[Link]:---
a = 10
b = 10
print("Sum ", (a+b))
Compilation
The program is converted into byte code. Byte code is a fixed set of instructions that
represent arithmetic, comparison, memory operations, etc. It can run on any operating
system and hardware. The byte code instructions are created in the .pyc file. The .pyc
file is not explicitly created as Python handles it internally but it can be viewed with the
following command:
PS E:\Python_data>
Python_data> python -m py_compile [Link]
-m
m and py_compile represent module and module name respectively. This module is
responsible to generate .pyc file. The compiler creates a directory named __pycache__
where it stores the [Link]
[Link] file.
Interpreter
The next step involves converting the byte code (.pyc file) into machine
ma code.
This step is necessary as the computer can understand only machine code (binary
code). Python Virtual Machine (PVM) first understands the operating system and
processor in the computer and then converts it into machine code. Further, these
machine
ine code instructions are executed by processor and the results are
displayed.
However, the interpreter inside the PVM translates the program line by line thereby
consuming a lot of time. To overcome this, a compiler known as Just In Time (JIT) is
added to PVM. JIT compiler improves the execution speed of the Python program. This
compiler is not used in all Python environments like CPython which is standard Python
software.
view the byte code of the file – [Link] we can type the following command as :
[Link]:
x = 10
y = 10
z=x+y
print(z)
The command python -m dis [Link] disassembles the Python bytecode generated
from the source code in the file [Link].
When you run this command, Python compiles [Link] into bytecode (if not
already compiled), and the dis module disassembles it. This helps you understand
the internal bytecode instructions that Python generates from your source code.
LOAD_CONST: Loads a constant value (like numbers 10 and 20).
STORE_NAME: Stores the value in a variable (like x, y, or z).
LOAD_NAME: Loads the value of a variable from memory.
BINARY_ADD: Adds two values (in this case, the values of x and y).
CALL_FUNCTION: Calls a function (like print).
RETURN_VALUE: Returns from a function (in this case, the main
program).
Token:-
In Python, a token is the smallest unit of the source code that the Python
interpreter recognizes during the process of lexical analysis (the first step in code
compilation or interpretation). Each token represents a meaningful element in
Python, such as
1. Keywords.
2. Punctuation/delimiters.
3. Identifiers.
4. Operators.
5. Literals
Keywords:
Punctuations:-
Operator
ARITHMETIC OPERATORs:
As stated above, these are used to perform that basic mathematical stuff as done in
every programming language. Let’s understand them with some examples. Let’s
assume, a = 20 and b = 12
a = 20
b = 12
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a%b)
print(ab)
print(a//b)
O/P:-
32
8
240
1.6666666666666667
8
4096000000000000
1
print(12//5)
print(12.0//5)
O/P:-
2
2.0
O/P:-
True
True
False
False
False
True
LOGICAL OPERATORS:-
In python, there are three types of logical operators. They are and, or, not. These
operators are used to construct compound conditions, combinations of more than
one simple condition. Each simple condition gives a boolean value which is
evaluated, to return the final boolean value.
Note: In logical operators, False indicates 0(zero) and True indicates non-zero
value. Logical operators on boolean types
1. and: If both the arguments are True then only the result is True
2. or: If at least one argument is True then the result is True
3. not: the complement of the boolean value
a = True
b = False
print(a and b)
print(a or b)
print(not a)
print(a and a)
O/P:-
False
True
False
True
and operator:
‘A and B’ returns A if A is False
‘A and B’ returns B if A is not False
Or Operator in Python:
‘A or B’ returns A if A is True
‘A or B’ returns B if A is not True
Not Operator in Python:
not A returns False if A is True
not B returns True if A is False
ASSIGNMENT OPERATORS:
By using these operators, we can assign values to variables. ‘=’ is the assignment
operator used in python. There are some compound operators which are the
combination of some arithmetic and assignment operators (+=, -=, *=, /=, %=, **=,
//= ). Assume that, a = 13 and b = 5
a=13
print(a)
a+=5
print(a)
O/P:-
13
18
MEMBERSHIP OPERATORS:----
Membership operators are used to checking whether an element is present in a
sequence of elements are not. Here, the sequence means strings, list, tuple,
dictionaries, etc which will be discussed in later chapters. There are two
membership operators available in python i.e. in and not in.
O/P:-
True
False
False
True
Example: Membership Operators
O/P:-
True
False
True
IDENTITY OPERATORS:--
This operator compares the memory location( address) to two elements or variables
or objects. With these operators, we will be able to know whether the two objects
are pointing to the same location or not. The memory location of the object can be
seen using the id() function.
O/P:-
1487788114928
1487788114928
O/P:-
True
2873693373424
2873693373424
Example: Identity Operators
a = 25
b = 30
print(a is b)
print(id(a))
print(id(b))
O/P:-
False
1997786711024
1997786711184
Note: The ‘is’ and ‘is not’ operators are not comparing the values of the objects.
They compare the memory locations (address) of the objects. If we want to
compare the value of the objects. we should use the relational operator ‘==’.
Bit-wise and(&):-----
x = 10
y = 20
print(x & y)
x = 10 0 1 0 1 0
& & & & &
y = 20 1 0 1 0 0
--------------------------
o/p=0 0 0 0 0 0
x =10
Print( x<<2) 32 16 8 4 2 1
x=10 1 0 1 0
40 1 0 1 0 0 0
x =10
x=10 1 0 1 0
o/p= 2 1 0 . 1 0
-----:Literals in Python:-----
Literals in Python are constant values that are assigned to variables or used directly
in code. Python supports several types of literals:
1. String Literals: Enclosed in single ('...'), double ("..."), triple single ('''...'''),
or triple double quotes ("""...""").
2. Numeric Literals:
Integer Literals: Whole numbers, which can be written in decimal,
binary (0b...), octal (0o...), or hexadecimal (0x...) form.
Float Literals: Numbers with a decimal point or in exponential
(scientific) notation.
Complex Literals: Numbers with a real and imaginary part, defined
by a number followed by a j or J.
3. Boolean Literals: True and False, which represent the two truth values of
Boolean logic.
4. Special Literal: None, which represents the absence of a value or a null
value.
5. Collection Literals: Literals for creating collections like lists, tuples,
dictionaries, and sets.
Numeric:------
Integer:---
my_int1 = 10
my_int2 = 10
print(id(my_int1),id(my_int2))
| |
---------------
|
(140707225601224 140707225601224)
Same memory address
|
That means immutable object
Float:----
my_float1 = 10.5
my_float2 = 10.5
print(id(my_float1),id(my_float2))
| |
---------------
|
(1740399292944 1740399292944)
(Same memory address)
|
Immutable object
Complex:---
my_comp1 = 10.5+3j
my_comp2 = 10.5+3j
print(id(my_comp1),id(my_comp2))
| |
| |
---------------
|
(3039707779024 3039707779024)
(Same memory address)
|
Immutable object
String:---
my_str1 = 'Neeraj'
my_str2 = 'Neeraj'
print(id(my_str1),id(my_str2))
| |
---------------
|
Same memory address
(2421953832800 2421953832800)
|
That means immutable object
List:----
my_list1 = ['Neeraj','jai']
my_list2 = ['Neeraj','jai']
print(id(my_list1),id(my_list2))
| |
---------------
|
(2070751895616 2070752043520)
Different memory address
|
That means mutable object
Tuple:---
my_tup1 = ('Neeraj','jai')
my_tup2 = ('Neeraj','jai')
print(id(my_tup1),id(my_tup2))
| |
---------------
|
(1607757822976 1607757822976)
Same memory address
|
That means immutable object
Dictionary:---
my_dict1 = {'name':'Neeraj','age':37}
my_dict2 = {'name':'Neeraj','age':37}
print(id(my_dict1),id(my_dict2))
| |
---------------
|
(2084796816704 2084797210368)
Different memory address
|
That means mutable object
Set: ---
my_set1 = {'name','Neeraj','age',37}
my_set2 = {'name','Neeraj','age',37}
print(id(my_set1),id(my_set2))
| |
---------------
|
(2485072560864 2485072845888)
Different memory address
|
That means mutable object
Frozenset:---
my_fset1 =frozenset({'name','Neeraj','age',37})
my_fset2 = frozenset({'name','Neeraj','age',37})
print(id(my_fset1),id(my_fset2))
| |
---------------
|
(2485072560864 2485072845888)
Different memory address due to unordered collection
|
Immutable object
Boolean:----
my_bool1 = True
my_bool2 = True
print(id(my_bool1),id(my_bool2))
| |
---------------
|
(140707224715696 140707224715696)
(Same memory address)
|
Immutable object
Python Objects
|
________________________________________________
| |
Mutable Immutable
1. list 1. numeric
2. dictinory 2. tuple
3. set 3. string
4. frozenset
5. Boolean
Variable in Python?
All the data which we create in the program will be saved in some memory
location on the system. The data can be anything, an integer, a complex number, a
set of mixed values, etc. A Python variable is a symbolic name that is a reference
or pointer to an object. Once an object is assigned to a variable, you can refer to the
object by that name.
3. Advance examples:-
Example:-
city = ["Bhopal", "Indore", "Jabalpur"]
x, y, z = city
print(x)
print(y)
print(z)
Python Comments:-
1. single line comments:--- ( # ---------------) ctrl+/
print(eval('10+5'))
print(eval('10-5'))
print(eval('10*5'))
print(eval('10/5'))
print(eval('10//5'))
print(eval('10%5'))
O/P:-
15
5
50
2.0
2
0
O/P:
Enter expression: 5+10
15
O/P:
Enter expression: 12-2
10
----: Indexing in Python :---
Index is a stored position of an object from ordered collections like string,list,tuple.
Positive Index 0 1 2 3 4
H E L L O
Negative Index -5 -4 -3 -2 -1
For example, if we have a string "HELLO", we can access the first letter "H" using
its index 0 by using the square bracket notation: string[0]
=> -ve indexing start with -1 => +ve index start with 0
=> -ve indexing read from R to L => +ve index read from L to R
=> -ve indexing write from L to R => +ve indexing write from L to R
=> +ve indexing stop point in (stop+1) => +ve indexing stop point in (stop-1)
Python's built-in index() function is a useful tool for finding the index of a specific
element in a sequence. This function takes an argument representing the value to
search for and returns the index of the first occurrence of that value in the sequence.
If the value is not found in the sequence, the function raises a ValueError. For
example, if we have a list [1, 2, 3, 4, 5], we can find the index of the value 3 by
calling [Link](3), which will return the value 2 (since 3 is the third element in the
list, and indexing starts at 0).
Python Index Examples
The method index() returns the lowest index in the list where the element searched
for appears. If any element which is not present is searched, it returns a ValueError.
Example:--
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
element = 3
print([Link](element))
O/P:-
2
O/P:-
Traceback (most recent call last):
File "e:\DataSciencePythonBatch\[Link]", line 7, in <module>
print([Link](element))
ValueError: 3 is not in list
Example:--(Index of a string element)
list = [1, 'two', 3, 4, 5, 6, 7, 8, 9, 10]
element = 'two'
print([Link](element))
O/P:-
1
What does it mean to return the lowest index?
list = [3, 1, 2, 3, 3, 4, 5, 6, 3, 7, 8, 9, 10]
element = 3
print([Link](element))
O/P:-
0
Find element with particular start and end point:--
Syntax:-
[Link](element, start, stop)
[Link](element)
[Link](element, start)
Example:- index() provides you an option to give it hints to where the value searched
for might lie.
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
element = 7
print([Link](element, 5, 8))
O/P:-
6
-----: Slicing in Python:-----
P R O G R A M M I N G
P R O O G R A R A M M M I N G
Slicing is the extraction of a part of a string, list, or tuple. It enables users to access
the specific range of elements by mentioning their indices.
Step1:-- Need to check step direction by default it’s goes to positive direction.
Ex:-1
var = "I love python"
print(var[::])
O/P:-
I love python
Ex:2
O/P:-
nohtyp evol I
Ex:-3
O/P:-
Ex:-4
O/P:-
Ex:-5
O/P:-
Ilv yhn
Ex:-6
var = "I love python"
print(var[::-2])
O/P:-
nhy vlI
Ex:-7,8,9,10,11,12
Syntax:
range(start,stop/end,step/direction)
Note :-
my_range = range(1,11)
print(list(my_range))
my_range = range(1,11,-1)
print(list(my_range))
my_range = range(-1,-11,-1)
print(list(my_range))
my_range = range(-1,-11,1)
print(list(my_range))
my_range = range(11)
print(list(my_range))
O/P:--
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[]
[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
[]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_range = range(2,11,2)
print(list(my_range))
my_range = range(1,10,2)
print(list(my_range))
my_range = range(-2,-11,-2)
print(list(my_range))
my_range = range(-1,-10,-2)
print(list(my_range))
[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]
[-2, -4, -6, -8, -10]
[-1, -3, -5, -7, -9]
my_range = range(5,2,-1)
print(list(my_range))
my_range = range(-5,-2,1)
print(list(my_range))
my_range = range(5,6,1)
print(list(my_range))
my_range = range(-5,-6,-1)
print(list(my_range))
O/P:--
[5, 4, 3]
[5]
[-5]
Data Types:-
Data Type represent the type of data present inside a variable.
In Python we are not required to specify the type explicitly. Based on value provided,
the type will be assigned automatically. Hence Python is Dynamically Typed
Language.
1. Numeric
1. Integer
2. Complex
3. Float
2. Mapped – Dictionary
3. Ordered
1. String
2. List
3. Tupple
4. Unordered
1. Set
2. Frozenset
5. Boolean
O/P---
emp_id type is: <class 'int'>
name type is: <class 'str'>
salary type is: <class 'float'>
O/P---
emp_id id is: 3146509648432
name id is: 3146515054320
salary id is: 3146510689840
emp_id = 11
name = 'Neeraj'
salary = 50000.40
print("My employee id is: ", emp_id)
print("My name is: ", name)
print("My salary is: ", salary)
O/P---
My employee id is: 11
My name is: Neeraj
My salary is: 50000.4
int data type:
The int data type represents values or numbers without decimal values. In python,
there is no limit for the int data type. It can store very large values conveniently.
a=10
type(a) O/P:- <class ‘int’>
Note: In Python 2nd version long data type was existing but in python 3rd version
long data type was removed.
1. Decimal form(base-10):
It is the default number system in Python. The allowed digits are: 0 to 9
Ex: a =10
2. Binary form(Base-2):
The allowed digits are : 0 & 1
Literal value should be prefixed with 0b or 0B
Eg: a = 0B1111
a =0B123
a=b111
3. Octal Form(Base-8):
The allowed digits are : 0 to 7
Literal value should be prefixed with 0o or 0O.
Ex: a=0o123
a=0o786
Base Conversions:--- Python provide the following in-built functions for base
conversions
# Base Conversions
# bin()
print(bin(15)) # o/p- 0b1111
print(bin(0o11)) # o/p- 0b1001
print(bin(0X10)) # o/p- 0b10000
# oct()
print(oct(10)) # o/p-0o12
print(oct(0B1111)) # o/p-0o17
print(oct(0X123)) # o/p-0o443
# hex()
print(hex(100)) # o/p-0x64
print(hex(0B111111)) # o/p-0x3f
print(hex(0o12345)) # o/p- 0x14e5
salary = 50.5
print(salary)
print(type(salary))
O/P---
50.5
<class 'float'>
O/P----
200.0
200.0
2000.0
20.0
<class 'float'>
O/P---
(3+5j)
(2-5.5j)
(3+10.5j)
A+B= (5-0.5j)
B+C= (5+5j)
C+A= (6+15.5j)
A*B= (33.5-6.5j)
B*C= (63.75+4.5j)
C*A= (-43.5+46.5j)
A+B+C= (8+10j)
A/B= (-0.6277372262773723+0.7737226277372262j)
a = True
b = False
print(a)
print(b)
print(a+a)
print(a+b)
O/P---
True
False
2
1
a = None
print(a)
print(type(a))
O/P------
None
<class 'NoneType'>
Sequences in python:
Sequences in Python are objects that can store a group of values. The below data
types are called sequences.
1. Str---Immutable
2. Bytes (as a list but in range of o to 256 (256 not included))--Immutable
3. Bytearray---- mutable
4. List-----mutable
5. Tuple----Immutable
6. Range
O/P---
Neeraj
Neeraj
Neeraj
O/P---<class 'bytes'>
O/P---
25
150
4
15
Example: Printing the byte data type values using for loop
y = bytes(x)
y = bytes(x)
y[0] = 30
The bytearray data type is the same as the bytes data type, but bytearray is mutable
means we can modify the content of bytearray data type. To create a bytearray
1. We need to create a list
2. Then pass the list to the function bytearrray().
3. We can iterate bytearray values by using for loop.
y = bytearray(x)
print(y[0])
print(y[1])
print(y[2])
print(y[3])
print(y[4])
Example: Printing the byte data type values using for loop
x = [10, 20, 00, 40, 15]
y = bytearray(x)
for a in y:
print(a)
y = bytearray(x)
y = bytearray(x)
----:String in Python:----
O/P:--
Welcome to 'python' learning
Welcome to "python" learning
Welcome "to" 'python' learning
In-built functions:--
str1="Neeraj"
print(max(str1))
print(min(str1))
print(len(str1))
print(type(str1))
# find ACII value of any special symbol(ord() take only one argument)
x='#'
print("ASCII value of X=",ord(x))
O/P:--
r
N
6
<class 'str'>
78
101
101
114
97
106
ASCII value of X= 35
Indexing:
Indexing means a position of string’s characters where it stores. We need to use
square brackets [] to access the string index. String indexing result is string type.
String indices should be integer otherwise we will get an error. We can access the
index within the index range otherwise we will get an error.
Python supports two types of indexing
1. Positive indexing: The position of string characters can be a positive index
from left to right direction (we can say forward direction). In this way, the
starting position is 0 (zero).
name = "Python"
print(name)
print(name[0])
name[0]="X"
O/P:-
Python
P
Traceback (most recent call last):
File "e:\DataSciencePythonBatch\[Link]", line 15, in <module>
name[0]="X"
TypeError: 'str' object does not support item assignment
O/P:--
PythonProgramming
a = "Python"
b = "Programming"
print(a+" "+b)
O/P:--
Python Programming
O/P:--
PythonPythonPython
O/P:--
Length of string is: 6
O/P:--
True
False
True
False
O/P:--
Enter main string:Neeraj
Enter substring:raj
raj is found in main string
Pre-define methods:--
1. upper() – This method converts all characters into upper case
O/P:--
converted to using upper(): PYTHON PROGRAMMING LANGUAGE
converted to using upper (): JAVA PROGRAMMING LANGUAGE
converted to using upper (): WE ARE SOFTWARE DEVELOPER
O/P:--
converted to using lover(): python programming language
converted to using lover (): java programming language
converted to using lover (): we are software developer
O/P:--
converted to using title(): PYTHON PROGRAMMING LANGUAGE
converted to using title(): java PROgRAMMING LAngUAGE
converted to using title(): we are software developer
4. title() – This method converts all character to title case (The first character in
every word will be in upper case and all remaining characters will be in lower
case)
O/P:--
converted to using title(): Python Programming Language
converted to using title(): Java Programming Language
converted to using title(): We Are Software Developer
5. capitalize() – Only the first character will be converted to upper case and all
remaining characters can be converted to lowercase.
str1 = 'python programming language'
print('converted to using capitalize():', [Link]())
O/P:--
converted to using capitalize(): Python programming language
converted to using capitalize (): Java programming language
converted to using capitalize (): We are software developer
6. center():-Python String center() Method tries to keep the new string length
equal to the given length value and fills the extra characters using the default
character (space in this case).
new_str = [Link](40)
# here fillchar not provided so takes space by default.
print("After padding String is: ", new_str)
O/P:--
python programming language .
new_str = [Link](40,'#')
# here fillchar not provided so takes space by default.
print("After padding String is: ", new_str)
O/P:--
######python programming language#######
O/P:--
python programming language
O/P:--
ount of given charactor is: 2
O/P:--
count of given charactor is: 0
8. Join():--- The string join() method returns a string by joining all the elements
of an iterable (list, string, tuple), separated by the given separator.
The join() method takes an iterable (objects capable of returning its members one at a
time) as its [Link] of the example of iterables are: Native data types - List,
Tuple, String, Dictionary and Set.
str = ['Python', 'is', 'a', 'programming', 'language']
# join elements of text with space
print(' '.join(str))
O/P:--
Python is a programming language
str = ['Python', 'is', 'a', 'programming', 'language']
# join elements of text with space
print('_'.join(str))
O/P:-
Python_is_a_programming_language
O/P:--
1, 2, 3, 4
# .join() with tuples
numTuple = ('1', '2', '3', '4')
print([Link](numTuple))
O/P:--
1, 2, 3, 4
s1 = 'abc'
s2 = '123'
# each element of s2 is separated by s1
# '1'+ 'abc'+ '2'+ 'abc'+ '3'
print('[Link](s2):', [Link](s2))
O/P:--
[Link](s2): 1abc2abc3
O/P:--
[Link](s1): a123b123c
O/P:--
2, 3, 1
O/P:--
Ruby->->Java->->Python
O/P:--
mat->that
9. split():-- The split() method splits a string at the specified separator and returns
a list of substrings.
O/P:--
['Python', 'is', 'a', 'programming', 'language']
['Python is a programming language']
['Python is a programming language']
['Python', 'is a programming language']
['Python is a programming language']
---: List :---
Whenever we want to create a group of objects where we want below mention
properties, then we are using list sequence.
O/P:--
['neeraj', 10, 20, 30, 10, 20]
2. Order is preserved:
List=['neeraj', 10,20,30,10,20]
x=0
for i in List:
print('List[{}] = '.format(x),i)
x=x+1
O/P:--
List[0] = neeraj
List[1] = 10
List[2] = 20
List[3] = 30
List[4] = 10
List[5] = 20
O/P:--
List[0] = neeraj
List[1] = 10
List[2] = 20
List[3] = 30
List[4] = 10
List[5] = 20
['Arvind', 10, 20, 30, 10, 20]
O/P:--
neeraj
10
20
30
10
20
O/P:--
['neeraj', 10, 20, 30, 10]
List=['neeraj', 10,20,30,10,20]
print(List[::-1])
O/P:--
[20, 10, 30, 20, 10, 'neeraj']
6. len(list)
7. max(list) - homogeneous collection required
8. min(list) - homogeneous collection required
9. sum(list) - integer homogeneous collection required
[Link](tuple)
[Link](list)
[Link]()
[Link]()
Methos:--
O/P:--
Updated animals list: ['cat', 'dog', 'rabbit', 'rat']
O/P:--
Count of 2: 3
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
count = [Link]('i')
print('The count of i is:', count)
count = [Link]('p')
print('The count of p is:', count)
O/P:--
The count of i is: 2
The count of p is: 0
# random list
random = ['a', ('a', 'b'), ('a', 'b'), [3, 4]]
count = [Link](('a', 'b'))
print("The count of ('a', 'b') is:", count)
count = [Link]([3, 4])
print("The count of [3, 4] is:", count)
O/P:--
The count of ('a', 'b') is: 2
The count of [3, 4] is: 1
# create a list
list1 = [2, 3, 5]
list2 = [1, 4]
[Link](list2)
print('List after extend():', list1)
O/P:--
List after extend(): [2, 3, 5, 1, 4]
list = ['Hindi']
tuple = ('Spanish', 'English')
set = {'Chinese', 'Japanese'}
[Link](tuple)
print('New Language List:', list)
[Link](set)
print('Newer Languages List:', list)
O/P:--
Example:---
numbers = ['Neeraj',2, 3, 5, 7]
[Link]()
print('Reversed List:', numbers)
O/P:--
Reversed List: [7, 5, 3, 2, 'Neeraj']
Example:----
numbers = ['Neeraj',2, 3, 5, 7]
print(numbers[::-1])
O/P:--
[7, 5, 3, 2, 'Neeraj']
Example:----
numbers = ['Neeraj',2, 3, 5, 7]
# print(numbers[::-1])
list=[]
for i in reversed(numbers):
[Link](i)
print(list)
O/P:--
[7, 5, 3, 2, 'Neeraj']
8. [Link](reverse=True/False) default-False
Example:---
numbers = [2, 3, 7, 5, 4]
[Link]()
print('Sort_List:', numbers)
O/P:--
Sort_List: [2, 3, 4, 5, 7]
Example:---
numbers = [2, 3, 7, 5, 4]
[Link](reverse=True)
print('Sort_List:', numbers)
O/P:--
Sort_List: [7, 5, 4, 3, 2]
---:Tuple :---
In Python, tuples are immutables. Meaning, you cannot change items of a tuple once
it is assigned. There are only two tuple methods count() and index() that a tuple
object can call.
Tuple occupies less memory as compare to list, that’s why tuple is more faster as
compare to list.
Example:--
list = [10,20,30,40,50,60,70]
tuple = (10,20,30,40,50,60,70)
print([Link]('Size of list = ',list))
print([Link]('Size of tuple',tuple))
O/P- 64
62
Built-in functions:-
Methods:--
# Creating tuples
Tuple = (0, 1, (2, 3), (2, 3), 1, [3, 2],'Neeraj', (0), (0,))
res = [Link]((2, 3))
print('Count of (2, 3) in Tuple is:', res)
res = [Link](0)
print('Count of 0 in Tuple is:', res)
res = [Link]((0,))
print('Count of (0,) in Tuple is:', res)
O/P:--
Count of (2, 3) in Tuple is: 2
Count of 0 in Tuple is: 2
Count of (0,) in Tuple is: 1
Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)
# getting the index of 3
res = [Link](3)
print(res)
O/P:--
3
Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)
# getting the index of 3
print([Link](3,4))
O/P:--
5
Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)
# getting the index of 3
print([Link](3,0,4))
o/p:--
3
Characteristics of Dictionary
1. Dictionary will contain data in the form of key, value pairs.
2. Key and values are separated by a colon “:” symbol
3. One key-value pair can be represented as an item.
4. Duplicate keys are not allowed.
5. Duplicate values can be allowed.
6. Heterogeneous objects are allowed for both keys and values.
7. Insertion order is not preserved.
8. Dictionary object having mutable nature.
9. Dictionary objects are dynamic.
[Link] and slicing concepts are not applicable
O/P:--
{}
<class 'dict'>
Adding the items in empty dictionary:--
d = {}
d[1] = "Neeraj"
d[2] = "Rahul"
d[3] = "Ravi"
print(d)
O/P:--
{1: 'Neeraj', 2: 'Rahul', 3: 'Ravi'}
print(d[1])
print(d[2])
print(d[3])
O/P:--
Neeraj
Rahul
Ravi
Note:--- While accessing, if the specified key is not available then we will
get KeyError
print(d[1])
print(d[2])
print(d[3])
print(d[10])
O/P:--
Neeraj
Rahul
Ravi
Traceback (most recent call last):
File "E:\DataSciencePythonBatch\[Link]", line 16, in <module>
print(d[10])
KeyError: 10
if 10 in d:
print(d[10])
else:
print('Key Not found')
O/P:--
Key Not found
d={}
n=int(input("Enter how many student detail you want: "))
i=1
while i <=n:
name=input("Enter Employee Name: ")
email=input("Enter Employee salary: ")
d[name]=email
i=i+1
print(d)
O/P:--
Enter how many student detail you want: 3
Enter Employee Name: Neeraj
Enter Employee salary: neeraj@[Link]
Enter Employee Name: Rahul
Enter Employee salary: rahul@[Link]
Enter Employee Name: Ravi
Enter Employee salary: ravi@[Link]
{'Neeraj': 'neeraj@[Link]', 'Rahul': 'rahul@[Link]', 'Ravi': 'ravi@[Link]'}
Case1: While updating the key in the dictionary, if the key is not available then a
new key will be added at the end of the dictionary with the specified value.
O/P:--
Old dict data {1: 'Neeraj', 2: 'Rahul', 3: 'Ravi'}
Nwe dict data {1: 'Neeraj', 2: 'Rahul', 3: 'Ravi', 10: 'Arvind'}
Case2: If the key already exists in the dictionary, then the old value will be replaced
with a new value.
d={1: 'Neeraj', 2: 'Rahul', 3: 'Ravi'}
print("Old dict data",d)
d[2]="Arvind"
print("New dict data",d)
O/P:--
Old dict data {1: 'Neeraj', 2: 'Rahul', 3: 'Ravi'}
New dict data {1: 'Neeraj', 2: 'Arvind', 3: 'Ravi'}
O/P:--
New dict is {1: 'Neeraj', 2: 'Rahul'}
By using clear() keyword
2. fromkeys() # [Link](keys, value) Initializing multiple keys with the same value.
5. copy() # [Link]()
6. get() # [Link](‘key’)
7. clear() # [Link]()
8. pop() # [Link](‘key’)
9. popitem() # [Link]()
10. key() # [Link]()
11. values() # [Link]()
12. items() # [Link]()
dict() function:
This can be used to create an empty dictionary.
d=dict()
print(d)
print(type(d))
O/P:--
{}
<class 'dict'>
len() function: This function returns the number of items in the dictionary.
d={1: 'Neeraj', 2: 'Rahul', 3: 'Ravi'}
print(len(d))
O/P:--
3
clear() method: This method can remove all elements from the dictionary.
d={1: 'Neeraj', 2: 'Rahul', 3: 'Ravi'}
print([Link]())O/P:--
O/P:--
None
get() method:
This method used to get the value associated with the key. This is another way to get
the values of the dictionary based on the key. The biggest advantage it gives over the
normal way of accessing a dictionary is, this doesn’t give any error if the key is not
present. Let’s see through some examples:
Case1: If the key is available, then it returns the corresponding value otherwise
returns None. It won’t raise any errors.
Syntax: [Link](key)
O/P:--
Neeraj
Rahul
Ravi
Case 2: If the key is available, then returns the corresponding value otherwise returns
the default value that we give.
Syntax: [Link](key, defaultvalue)
pop() method: This method removes the entry associated with the specified key and
returns the corresponding value. If the specified key is not available, then we will get
KeyError.
Syntax: [Link](key)
O/P:
{1: 'Neeraj', 2: 'Rahul'}
O/P:--
(5, 'Santosh')
{1: 'Neeraj', 2: 'Rahul', 3: 'Ravi', 4: 'Jai'}
keys() method:This method returns all keys associated with the dictionary
d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
print(d)
for k in [Link]():
print(k)
O/P:--
1
2
3
values() method: This method returns all values associated with the dictionary
d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
print(d)
for k in [Link]():
print(k)
O/P:--
Ramesh
Suresh
Mahesh
O/P:--
1 --- Ramesh
2 --- Suresh
3 --- Mahesh
---: Set :---
If we want to represent a group of unique elements then we can go for sets. Set
cannot store duplicate elements.
# Creating a set
s = {10,20,30,40}
print(s)
print(type(s))
O/P:--
{40, 10, 20, 30}
<class 'set'>
O/P:--
{'20', True, 234.56, 10, 'Rahul'}
<class 'set'>
O/P:--
{0, 1, 2, 3, 4}
O/P:--
set()
<class 'set'>
# Methods in set:----
s={10,20,30,50}
[Link](40)
print(s)
O/P:--
{40, 10, 50, 20, 30}
2. update(iterable_obj1,iterable_obj2)
s = {10,20,30}
l = [40,50,60,10]
[Link](l)
print(s)
O/P:--
{40, 10, 50, 20, 60, 30}
s = {10,20,30}
l = [40,50,60,10]
[Link](l, range(5))
print(s)
O/P:--
{0, 1, 2, 3, 4, 40, 10, 50, 20, 60, 30}
Difference between add() and update() methods in set:
3. We can use add() to add individual items to the set, whereas we can use
update() method to add multiple items to the set.
4. The add() method can take one argument whereas the update() method can take
any number of arguments but the only point is all of them should be iterable
objects.
s={10,20,30}
s1=[Link]()
print(s1)
O/P:--
{10, 20, 30}
4. pop()--- This method removes and returns some random element from the set.
s = {40,10,30,20}
print(s)
print([Link]())
print(s)
O/P:--
{40, 10, 20, 30}
40
{10, 20, 30}
5. remove(element) --- This method removes specific elements from the set. If
the specified element is not present in the set then we will get KeyError.
s={40,10,30,20}
[Link](30)
print(s)
O/P:--
{40, 10, 20}
s={40,10,30,20}
[Link](50)
print(s)
O/P:--
Traceback (most recent call last):
File "E:\DataSciencePythonBatch\[Link]", line 65, in <module>
[Link](50)
KeyError: 50
6. discard(element) --- This method removes the specified element from the set.
If the specified element is not present in the set, then we won’t get any error.
s={10,20,30}
[Link](10)
print(s)
O/P:--
{20, 30}
s={10,20,30}
[Link](40)
print(s)
O/P:--
{10, 20, 30}
O/P:--
{10, 20, 30}
set()
MATHEMATICAL OPERATIONS ON SETS
1. union() --- This method return all elements present in both sets.
x={10,20,30,40}
y={30,40,50,60}
print([Link](y))
O/P:--
{40, 10, 50, 20, 60, 30}
2. intersection() --- This method returns common elements present in both x and
y.
x = {10,20,30,40}
y = {30,40,50,60}
print([Link](y))
print(x&y)
print([Link](x))
print(y&x)
O/P:--
{40, 30}
{40, 30}
{40, 30}
{40, 30}
3. difference() --- This method returns the elements present in x but not in y
d = {'name':'Neeraj','age':37,'quali':'[Link]'}
fs = frozenset(d)
print(fs)
print(type(fs))
print(id(fs))
O/P:---
frozenset({'quali', 'age', 'name'})
<class 'frozenset'>
3031112853184
d = {'name':'Neeraj','age':37,'quali':'[Link]'}
fs = frozenset(d)
print(max(fs))
print(min(fs))
print(len(fs))
print(type(fs))
print(id(fs))
print(fs)
O/P:--
quali
age
3
<class 'frozenset'>
2888669832896
frozenset({'age', 'name', 'quali'})
methods in frozenet :-
union()
intersection()
difference()
symmetric difference()
issuperset()
isdisjoint()
idsubset()
Python Basic practice Questions
1. Write some benefits/Advantages of Python.
2. Write some Limitation/Disadvantages of Python.
3. When to use a tuple vs list vs dictionary in Python?
4. What is a Negative Index in Python?
5. How do I modify a string in python?
6. What is indexing in Python?
7. What is slicing in Python?
8. Write some key features of Python
9. Name some Libraries of Python Programing language and their application?
10. What is the difference between Compiled Languages and Interpreted Languages?
11. What is a module in Python with example?
12. What is the use of Floor Division in python? Explain with examples.
13. What is the use of Modulas in python? Explain with examples.
14. What is the use Range function in python ?
15. What are .py and .pyc files ?
16. What are the types of literals in Python?
17. What are some built in data types in python ?
18. List some common Python interpreters.
19. Write a program to print all keywords in python?
20. Write a program to print punctuation in python.
21. What is a token in python?
22. Write python inbuilt functions with examples.
23. Write inbuilt methods with examples in python.
24. What is the list in python? Explain list methods with examples.
25. What is the tuple in python? Explain methods with examples.
26. What is the dictionary in python? Explain methods with examples.
27. What is the set in python? Explain methods with examples.
28. What is the frozenset in python? Explain methods with examples.
29. Explain python objects and their types.
30. Write a difference between list and tuple.
31. Write a difference between set and frozen set.
32. Explain join and split methods in string with examples.
33. Write how we declared empty literal-types in python.
34. What is identifiers in python?
35. Write the difference between identifier and variable.
36. Write a program to swap two numbers without using third variable.
37. Write a program to swap two numbers using third variable.
38. Write a program to swap two numbers using addition/subtraction,
multiplication/Division.
39. Write a program to take input from runtime and print type and id of that input.
40. Write a program to find area of triangle.
41. Write a program to find area of square.
42. Write a program to find area of rectangle.
43. Write a program to find square of any number(x2).
44. Write a program to find square root of any number (√x).
45. Write a program to find cube root of any number (3√x).
46. Write a program to find cube of a number (x3).
47. Write a program to find area of circle(πr2).
48. Find max(),min(),len() against given dictionary.
d= {1:"Python",2:"Java",3:"Python"}
49. Find max(),min(),len() against given dictionary.
d= {1:"Python",2:"Java",'3':"Python"}
50. Find max(),sum(),len() against given dictionary.
d= {1:"Python",2:"Java",1:"Python"}
51. Find max(),min(),sum() against given dictionary.
d= {1:"Python",2:"Java",'3':"Python"}
52. Write a difference between is and ==.
Some mathematical logics
Netural number: A natural number is a positive [Link] on context
natural number:
Without 0: natural numbers = {1, 2, 3, ...}
With 0: natural numbers = {0, 1, 2, 3, ...}
Even number: An even number is any integer that is exactly divisible by 2. In other
words, when you divide an even number by 2, there is no remainder. An even number
can be expressed as 2 × n, where n is any integer.
n mod 2 = 0
Prime number: A prime number is a natural number greater than 1 that has exactly
two distinct positive divisors. 1 and itself.
Key Properties:
It cannot be formed by multiplying two smaller natural numbers (except 1
and itself).
The number 1 is not prime.
The smallest prime number is 2, which is also the only even prime.
Factor of given number: A factor (or divisor) of a number is an integer that divides
the number exactly (with no remainder).
For example:
Factors of 12 are:
1, 2, 3, 4, 6, 12
(because all of these divide 12 without leaving a remainder)
How to find factors of a number:
1. Start from 1 and go up to the number itself.
2. Check which numbers divide the given number exactly (i.e., number % i
== 0).
Factorial : A factorial (denoted by n!) is the product of all positive integers from 1
to n.
Definition:
n!=n×(n−1)×(n−2)×…×1
Special case:
0!=1(by definition)
Examples:
1!= 1
2!=2×1=2
3!=3×2×1=6
5!=5×4×3×2×1=120
Leap year: A leap year is a year that has 366 days instead of the usual 365. The
extra day is added to February, making it 29 days long instead of 28.
Rules to determine a leap year:
A year is a leap year if:
It is divisible by 4,
but not divisible by 100,
unless it is also divisible by 400.
In short:
Leap year: 2000, 2016, 2020, 2024
Not a leap year: 1900, 2100 (divisible by 100 but not by 400)
Examples:
2024 is a leap year → divisible by 4, not by 100
1900 is not a leap year → divisible by 100, but not by 400
2000 is a leap year → divisible by 400
Leep year-Concept
Year Day hour minutes seconds
1-Year 365 5 48 47.5
2-Year 365 5 48 47.5
3-Year 365 5 48 47.5
4-Year 365 5 48 47.5
Remain times 20 192 190
190/6=
195/60=3h,15m 3min,10sec
23 15 10
Approx 1-day which is added in Add some
every 4years time
leep
year 366
extra added
negative time in leep year(-) time 44 50
100
year 44*25=1100 50*25=1250
1250/60
20 minutes, 50
1120/60 sec
18hours,40
minutes
18 40 50
100-
years 1-day remove in feb month Not a Leep year
5 19 10
General Rule:
For an n-digit number:
Armstrong number⇒abcd…=anumber_of_digit+bnumber_of_digit+cnumber_of_digit+dnum
ber_of_digit
+… Examples:
153
It's a 3-digit number:
13+53+33=1+125+27=1531^3 + 5^3 + 3^3 = 1 + 125 + 27 =
15313+53+33=1+125+27=153
9474
It's a 4-digit number:
94+44+74+44=6561+256+2401+256=94749^4 + 4^4 + 7^4 + 4^4 =
6561 + 256 + 2401 + 256 =
947494+44+74+44=6561+256+2401+256=9474
370, 371, 407 are also 3-digit Armstrong numbers.
For numbers:
A palindromic number stays the same when its digits are reversed.
121 → reversed is 121
1331 → reversed is 1331
123 → reversed is 321 (not a palindrome)
For words:
LCM: LCM stands for Least Common Multiple — the smallest multiple that two
or more numbers share in common.
Example:
Find the LCM of 4 and 6:
Multiples of 4: 4, 8, 12, 16, ...
Multiples of 6: 6, 12, 18, 24, ...
LCM = 12
How to find LCM:
1. Listing multiples (as above) — good for small numbers.
2. Prime factorization — multiply highest powers of all primes involved.
3. Using formula:
LCM(a,b)=∣a×b∣ / GCD(a,b)
HCF: HCF stands for Highest Common Factor, also known as the Greatest
Common Divisor (GCD). It is the largest number that divides two or more numbers
exactly (without leaving a remainder).
Example:
Find the HCF of 12 and 15:
Factors of 12: 1, 2, 3, 4, 6, 12
Factors of 15: 1, 3, 5, 15
HCF = 3
How to find HCF:
1. Listing common factors: Find the common factors of the numbers and
pick the largest.
2. Prime factorization: Find the prime factorization of both numbers, then
multiply the smallest powers of the common prime factors.
3. Using the formula:
HCF(a,b)=∣a×b∣ / LCM(a,b)
Fibonacci:--
The Fibonacci series is a sequence of numbers in which each number is the sum of
the two preceding ones. It starts like this:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Harshad Numbers:
A Harshad number (also known as a Niven number) is a number that is divisible
by the sum of its digits. The term Harshad is derived from the Sanskrit words "Har"
(joy) and "Shad" (give), meaning "giver of joy.
18 → Sum of digits = 1 + 8 = 9 → 18 is divisible by 9
21 → Sum of digits = 2 + 1 = 3 → 21 is divisible by 3
19 → Sum of digits = 1 + 9 = 10 → 19 is NOT divisible by 10
Anagrams Number:
An anagram is a word or phrase formed by rearranging the letters of another word or
phrase, using all the original letters exactly once
"listen" → "silent"
"race" → "care"
"evil" → "vile"
"dormitory" → "dirty room" (ignoring spaces)
Neon Number:
A Neon Number is a number where the sum of the digits of its square is equal to the
original number.
9 → Square = 9 × 9 = 81
o Sum of digits of 81 → 8 + 1 = 9
12 → Square = 12 × 12 = 144
o Sum of digits of 144 → 1 + 4 + 4 = 9
Peterson Numbers:
A Peterson number is a number where the sum of the factorials of its digits equals
the number itself.
1. 145
o Digits: 1, 4, 5
o Factorial Sum: 1! + 4! + 5! = 1 + 24 + 120 = 145
2. Other Peterson Numbers: 1, 2, 145 (There are very few!)
Spy Numbers
A Spy Number is a number where the sum of its digits is equal to the product of its
digits
1. 112
o Digits: 1, 1, 2
o Sum = 1 + 1 + 2 = 4
o Product = 1 × 1 × 2 = 4
2. 123
o Digits: 1, 2, 3
o Sum = 1 + 2 + 3 = 6
o Product = 1 × 2 × 3 = 6
Sunny number
A sunny number is a number that is one less than a perfect square. In other words, a
number N is sunny if there exists an integer n such that:
N+1=n2
For example:
3 is a sunny number because 3+1=4, and 4 is a perfect square (since 2^2=4).
8 is another sunny number because 8+1=9, and 9 is a perfect square (since 3^2
= 9)
Control Flow Statements
In programming languages, flow control means the order in which the statements or
instructions, that we write, get executed. In order to understand a program, we should
be aware of what statements are being executed and in which order. So,
understanding the flow of the program is very important. There are, generally, three
ways in which the statements will be executed. They are,
1. Sequential
2. Conditional
3. Looping
Sequential: In this type of execution flow, the statements are executed one after the
other sequentially. By using sequential statements, we can develop simple programs
O/P:-
Welcome
to
python class
Conditional: Statements are executed based on the condition. As shown above in the
flow graph, if the condition is true then one set of statements are executed, and if
false then the other set. Conditional statements are used much in complex programs.
Conditional statements are also called decision-making statements. Let’s discuss
some conditions making statements in detail. There are three types of conditional
statements in python. They are as follows:
1. if statement
2. if-else statement
3. nested-if (if-elif-elif-else)
if-statement:-
syntax:-
if condition:
print("Block statement")
print("Out of block statement")
Example:-
O/P:
Enter any no: 10
out of if block statements
PS E:\DataSciencePythonBatch> python [Link]
Enter any no: 18
if block statment executed
out of if block statements
Example:---
if-else condition:-
syntax:-
if condition:
print("if block statement executed")
else:
print("else block statement executed ")
Example:---
O/P:-
PS E:\DataSciencePythonBatch> python [Link]
Enter any no: 18
if block statment executed
PS E:\DataSciencePythonBatch> python [Link]
Enter any no: 15
else block statement executed
Example:---
O/P:-
Example:---
O/P:-
Enter your age: 35
You are eligible to vote.
Example:---
O/P:-
Enter a year: 2000
It's a leap year.
Nested-If else:--
O/P:-
Enter your score: 90
You got an A.
Example:--
if (condition1):
statement of if Block
elif(condition2):
statment of elif Block
elif(condition3):
statement if elif block
else:
ststement of else block
Example:---
O/P:-
Enter a number: 5
Beyond the range than specified
PS E:\DataSciencePythonBatch> python [Link]
Please enter the values from 0 to 4
Enter a number: 4
You entered: 4
O/P:-
Enter a number: 4
The square root of 4.000 is 2.000
PS E:\DataSciencePythonBatch> python [Link]
Enter a number: 8
The square root of 8.000 is 2.828
O/P:---
Enter first side: 5
Enter second side: 6
Enter third side: 7
The area of the triangle is : 14.696938456699069
O/P:---
Enter value of x: 5
Enter value of y: 8
The value of x after swapping: 8
The value of y after swapping: 5
O/P:---
Enter value of x: 4
Enter value of y: 6
The value of x after swapping: 6
The value of y after swapping: 4
# By-using Addition and Subtraction.
x = int(input('Enter value of x: '))
y = int(input('Enter value of y: '))
x=x+y
y=x-y
x=x-y
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
O/P:---
Enter value of x: 4
Enter value of y: 6
The value of x after swapping: 6
The value of y after swapping: 4
# By-using Multiplication and division.
x = int(input('Enter value of x: '))
y = int(input('Enter value of y: '))
x=x*y
y=x/y
x=x/y
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
O/P:---
Enter value of x: 2
Enter value of y: 5
The value of x after swapping: 5.0
The value of y after swapping: 2.0
1. while loop
2. for loop
1. while loop:- The while loop contains an expression/condition. As per the syntax
colon (:) is mandatory otherwise it throws a syntax error. The condition gives the
result as bool type, either True or False. The loop keeps on executing the statements
until the condition becomes False. i.e. With the while loop we can execute a set of
statements as long as a condition is true.
This is the first part of the while loop. Before entering the condition section, some
initialization is required.
Condition:
Once the initializations are done, then it will go for condition checking which is the
heart of the while loop. The condition is checked and if it returns True, then
execution enters the loop for executing the statements inside.
print("End")
print(sum)
for-loop
Basically, a for loop is used to iterate elements one by one from sequences like string,
list, tuple, etc. This loop can be easily understood when compared to the while loop.
While iterating elements from the sequence we can perform operations on every
element.
The Python For Loop is used to repeat a block of statements until there are no items
in the Object may be String, List, Tuple, or any other object.
1. Initialization: We initialize the variable(s) here. Example i=1.
2. Items in Sequence / Object: It will check the items in Objects. For example,
individual letters in String word. If there are items in sequence (True), then it
will execute the statements within it or inside. If no item is in sequence (False),
it will exit.
3. After completing the current iteration, the controller will traverse to the next
item.
4. Again it will check the new items in sequence. The statements inside it will be
executed as long as the items are in sequence.
# Upto n natural no.
n = int(input("Enter a number: ""))
for i in range(1, n + 1):
if i < n:
print(i, end=",") # Print numbers with commas
else:
print(i)
Transfer Statements:
1. Break
2. continue
3. pass
Break statement:--- We can use break statement inside loops to break loop
execution based on some condition.
for i in range(10):
if i==7:
print("processing is enough.. plz break !!!!!!! ")
break
print(i)
O/P:---
0
1
2
3
4
5
6
processing is enough.. plz break !!!!!!!
list=[10,20,600,60,70]
for i in list:
if i>500:
print("no need to check next object of list")
break
print(i)
O/P:--
10
20
no need to check next object of list
continue statement:-- We can use continue statement to skip current iteration and
continue next iteration.
for i in range(10):
if i%2==0:
continue
print(i)
O/P:--
1
3
5
7
9
list=[10,20,600,60,70]
for i in list:
if i>500:
print("no need to print this object")
continue
print(i)
O/P:--
10
20
no need to print this object
60
70
list=[10,20,600,60,70]
for i in list:
if i>500:
continue
print(i)
O/P:--
10
20
60
70
pass statement:--
pass is a keyword in Python. In our programming syntactically if block is required
which won't do anything then we can define that empty block with pass keyword.
1. It is an empty statement
2. It is null statement
3. It won't do anything
for i in range(100):
if i%9==0:
print(i)
else:
pass
O/P:--
0
9
18
27
36
45
54
63
72
81
90
99
# O/P:-- {1: 2, 2: 3}
# code for above output
t=(1,1,2,2,4,2)
dict={}
for i in t:
count=0
for j in t:
if j==i:
count=count+1
if count>=2:
dict[i]=count
print(dict)
#*
#**
#***
#****
#*****
n=int(input("Enter the number of rows: "))
for i in range(1,n+1):
print("* "*i)
# *
# **
# ***
# ****
# *****
# *
# ***
# *****
# *******
# *********
# *
# **
# ***
# ****
# *****
n=int(input("Enter the number of rows: "))
for i in range(1,n+1):
print(" "*(n-i)," *"*i)
#1
#12
#123
#1234
#12345
# *****
# ****
# ***
# **
# *
n=int(input("Enter the number of rows: "))
for i in range(n,0,-1):
print(" "*(n-i),"*"*i)
# *****
# ****
# ***
# **
#*
n=int(input("Enter the number of rows: "))
for i in range(n,0,-1):
print("*"*i)
# *****
# ****
# ***
# **
# *
n=int(input("Enter the number of rows: "))
for i in range(n,0,-1):
print(" "*(n-i)," *"*i)
# *
# **
# ***
# ****
# *****
# *****
# ****
# ***
# **
# *
n=int(input("Enter the number of rows: "))
for i in range(1,n+1):
print(" "*(n-i),"* "*i)
m=n-1
for i in range(m,0,-1):
print(" "*(m-i)," *"*i)
# *
# **
# ***
# ****
# *****
# *****
# ****
# ***
# **
#*
#*
#**
#***
#****
#*****
#****
#***
#**
#*
n=int(input("Enter the number of rows: "))
for i in range(0,n+1):
print("* "*i)
m=n-1
for i in range(m,0,-1):
print("* "*i)
# *
# **
# ***
# ****
# *****
# *****
# ****
# ***
# **
# *
n=int(input("Enter the number of rows: "))
for i in range(0,n+1):
print(" "*(n-i),"*"*i)
for i in range(n,0,-1):
print(" "*(n-i),"*"*i)
Example 4: Write a program to swap two variables without using third variable.
Example 5: Write a program to swap two variables using third variable.
Example 6: Write a program to swap two variables using using Addition and Subtraction.
Example 10: Write a program to find largest no among the three inputs numbers.
Example 13: Write a program to find given year is leep year or not.
While-Loop EXAMPLES
Example 1: Write a program to display n natural numbers. (In Horizontal-
1,2,3,4,5…….. )
Example 7: Write a program to find how many vowels and consonants are present in
strings.
Example 2: Python program to print all the even numbers within the given range.
Example 3: Python program to calculate the sum of all numbers from 1 to a given number.
Example 4: Python program to calculate the sum of all the odd numbers within the given range.
Example 8: .(madam=madam)
Example 9: Python program that accepts a word from the user and reverses it.
Example 11: Python program to count the number of even and odd numbers from a series of
numbers.
Example 12: Python program to display all numbers within a range except the prime numbers.
Example 15: Python program that accepts a string and calculates the number of digits and letters.
Example 16: Write a Python program that iterates the integers from 1 to 25.
Example 17: Python program to check the validity of password input by users.
Example 18: Python program to convert the month name to a number of days.
----:Functions:----
x=200
y=100
print("Addition of x & y =",x+y)
print("Addition of x & y =",x-y)
print("Addition of x & y =",x*y)
x=10
y=5
print("Addition of x & y =",x+y)
print("Addition of x & y =",x-y)
print("Addition of x & y =",x*y)
O/P:--
Addition of x & y = 30
Addition of x & y = -10
Addition of x & y = 200
Addition of x & y = 300
Addition of x & y = 100
Addition of x & y = 20000
Addition of x & y = 15
Addition of x & y = 5
Addition of x & y = 50
Now, repeated code can be bound into single unit that is called function.
O/P:--
Addition of x & y = 30
Addition of x & y = -10
Addition of x & y = 200
Addition of x & y = 300
Addition of x & y = 100
Addition of x & y = 20000
Addition of x & y = 15
Addition of x & y = 5
Addition of x & y = 50
Types of function:---
1. In-built function :-- The functions which are coming along with Python
software automatically,are called built-in functions or pre defined functions.
Examples:--
1. print()
2. id()
3. type()
4. len()
5. eval()
6. sorted()
7. count() etc…….
2. User define function:--- The functions which are defined by the developer as per
the requirement are called user-defined functions.
Syntax:---
def fun_name(parameters….):
‘‘‘ doc string….’’’
Statment1…….
Statment2…….
Statment3…….
return (anything)
# call function
fun_name(arguments....)
Important terminology
def-keyword mandatory
return-keyword optional
arguments optional
parameters optional
fun_name mandatory
1. def keyword – Every function in python should start with the keyword ‘def’.
In other words, python can understand the code as part of a function if it
contains the ‘def’ keyword only.
2. Name of the function – Every function should be given a name, which can
later be used to call it.
3. Parenthesis – After the name ‘()’ parentheses are required
4. Parameters – The parameters, if any, should be included within the
parenthesis.
5. Colon symbol ‘:’ should be mandatorily placed immediately after closing the
parentheses.
6. Body – All the code that does some operation should go into the body of the
function. The body of the function should have an indentation of one level with
respect to the line containing the ‘def’ keyword.
7. Return statement – Return statement should be in the body of the function.
It’s not mandatory to have a return statement. If we are not writing return
statement then default return value is None
8. Arguments:-- At the time of calling any function, in between the parentheses
we passes arguments.
Relation between parameters and arguments:--
Parameters are inputs to the function. If a function contains parameters, then at the
time of calling, compulsory we should provide values as a arguments, otherwise we
will get error.
def calculate(x, y):
print("Addition of x & y =",x+y)
print("Addition of x & y =",x-y)
print("Addition of x & y =",x*y)
calculate(10,20)
calculate(200,100)
calculate(10,5)
O/P:--
Addition of x & y = 30
Addition of x & y = -10
Addition of x & y = 200
Addition of x & y = 300
Addition of x & y = 100
Addition of x & y = 20000
Addition of x & y = 15
Addition of x & y = 5
Addition of x & y = 50
# Write a function to take number as input and print its square value
def square(x):
print("The Square of",x,"is", x*x)
square(4)
square(5)
O/P:--
The Square of 4 is 16
The Square of 5 is 25
# Write a function to check whether the given number is even or odd?
def even_odd(num):
if num%2==0:
print(num,"is Even Number")
else:
print(num,"is Odd Number")
even_odd(10)
even_odd(15)
O/P:--
10 is Even Number
15 is Odd Number
O/P:--
Enter any no 5
The Factorial of 5 is : 120
Returning multiple values from a function: In other languages like C, C++ and
Java, function can return almost one value. But in Python, a function can return any
number of values.
def add_sub(a,b):
add=a+b
sub=a-b
return add,sub
x,y=add_sub(100,50)
print("The Addition is :",x)
print("The Subtraction is :",y)
O/P:--
The Addition is : 150
The Subtraction is : 50
Or
def add_sub(a,b):
add=a+b
sub=a-b
return add,sub
x,y=int(input("Enter first value:")),int(input("Enter second value: "))
print("The Addition is :",x)
print("The Subtraction is :",y)
O/P:--
The Addition is : 100
The Subtraction is : 50
def calc(a,b):
add=a+b
sub=a-b
mul=a*b
div=a/b
return add,sub,mul,div
def square(x):
print("The Square of",x,"is", x*x)
square(4)
square(5)
O/P:-
The Square of 4 is 16
The Square of 5 is 25
2. keyword arguments:
def f1(a,b):
------
------
f1(a=10,b=20)
def square(x):
print("The Square of",x,"is", x*x)
square(x=4)
square(x=5)
O/P:--
The Square of 4 is 16
The Square of 5 is 25
3. default arguments:
def f1(a=0,b=0):
------
------
f1(10,20)
f1()
def square(x=0):
print("The Square of",x,"is", x*x)
square(x=4)
square()
O/P:--
The Square of 4 is 16
The Square of 0 is 0
def sum(*n):
total=0
for i in n:
total=total+i
print("The Sum=",total)
sum()
sum(10)
sum(10,20)
sum(10,20,30,40)
O/P:--
The Sum= 0
The Sum= 10
The Sum= 30
The Sum= 100
5. key word variable length arguments:
def f1(**n):
------
------
f1(n1=10, n2=20)
def display(**kwargs):
for k,v in [Link]():
print(k,"=",v)
display(n1=10,n2=20,n3=30)
print("-----------")
display(rno=100, name="Neeraj", marks=70, subject="Java")
O/P:--
n1 = 10
n2 = 20
n3 = 30
-----------
rno = 100
name = Neeraj
marks = 70
subject = Java
# ===============================================
def display_info(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")
display_info(Name="Neeraj",age=37)
O/P:---
Name: Neeraj
age: 37
def a():
x=10
return "value of Local variable is:",x
def b():
return "value of Local variable is:",x
p=a()
print(p)
y=b()
print(y)
O/P:-
('value of Local variable is:', 10)
Traceback (most recent call last):
File "E:\Python Core_Advance\[Link]", line 10, in <module>
y=b()
File "E:\Python Core_Advance\[Link]", line 6, in b
return "value of Local variable is:",x
NameError: name 'x' is not defined
We Can’t access local variable outside the function:
def a():
x=10
return "value of Local variable is:",x
def b():
return "value of Local variable is:",x
p=a()
print(p)
print(x)
O/P:--
('value of Local variable is:', 10)
Traceback (most recent call last):
File "E:\Python Core_Advance\[Link]", line 12, in <module>
print(x)
NameError: name 'x' is not defined
O/P:--
a from function m(): 11
b from function m(): 12
a from function n(): 11
b from function n(): 12
GLOBAL KEYWORD IN PYTHON
The keyword global can be used for the following 2 purposes:
1. To declare a global variable inside a function
2. To make global variables available to the function.
def m1():
global a
a=2
print("a value from m1() function: ", a)
def m2():
print("a value from m2() function:", a)
m1()
m2()
O/P:--
a value from m1() function: 2
a value from m2() function: 2
global and local variables having the same name in Python
a=1
def m1():
global a
a=2
print("a value from m1() function:", a)
def m2():
print("a value from m2() function:", a)
m1()
m2()
O/P:--
a value from m1() function: 2
a value from m2() function: 2
If we use the global keyword inside the function, then the function is able to read-
only global variables.
PROBLEM: This would make the local variable no more available.
globals() built-in function in python:
The problem of local variables not available, due to the use of global keywords can
be overcome by using the Python built-in function called globals(). The globals() is a
built-in function that returns a table of current global variables in the form of a
dictionary. Using this function, we can refer to the global variable “a” as:
global()[“a”].
a=1
def m1():
a=2
print("a value from m1() function:", a)
print("a value from m1() function:", globals()['a'])
m1()
O/P:--
a value from m1() function: 2
a value from m1() function: 1
1. Map()
2. Filter()
3. Lambda()
4. Reduce()
5. Decorators()
6. Generators()
map() Syntax
map(function, iterable, ...)
map() Arguments
The map() function returns an object of map class. The returned value can be passed
to functions like list() - to convert to list, set() - to convert to a set, and so on.
Example:-1
my_list=[10,20,30,40]
def sqr(n):
return n*n
x=map(sqr,my_list)
print(x)
print(list(x))
O/P:--
<map object at 0x000001EA310E3490>
[100, 400, 900, 1600]
Example:-2
my_tuple=(10,20,30,40)
def sqr(n):
return n*n
x=map(sqr,my_tuple)
print(x)
print(tuple(x))
O/P:-
<map object at 0x0000019833A83490>
(100, 400, 900, 1600)
Example:-3
my_str="Neeraj"
def add(n):
x=ord(n)
return x
x=map(add,my_str)
print(x)
print(list(x))
O/P:-
<map object at 0x000001D03A4E3490>
[78, 101, 101, 114, 97, 106]
Example:-4
my_str="Neeraj"
def add(n):
x=ord(n)
return chr(x+5)
x=map(add,my_str)
print(x)
print(list(x))
O/P:-
<map object at 0x0000026D8F1634C0>
['S', 'j', 'j', 'w', 'f', 'o']
filter() Syntax
1. function - a function
2. iterable - an iterable like sets, lists, tuples etc.
Example 1:-
def fun(n):
if n>=60:
return True
x=filter(fun , my_list)
print(list(x))
O/P:--
[60, 70, 90, 75]
Example 2:-
def check_even(number):
if number % 2 == 0:
return True
return False
def check_odd(number):
if number % 2 != 0:
return True
return False
O/P:--
[1, 3, 5, 7, 9]
A lambda function can take any number of arguments, but can only have one
expression.
lambda Function Declaration: We use the lambda keyword instead of def to create
a lambda function. Here's the syntax to declare the lambda function:
Syntex:----
O/P:--
Hello World
greet = lambda : print('Hello World'). Here, we have defined a lambda function and
assigned it to the variable named greet. In the above example, we have defined a
lambda function and assigned it to the greet variable. When we call the lambda
function, the print() statement inside the lambda function is executed.
# with argument
x=lambda p,q,r:3*p+4*q+5*r+5
print(x(10,20,30))
O/P:-
265
# with argument
user = lambda name : print('Hello', name)
user('Neeraj')
O/P:--
Hello Neeraj
---: Reduce :---
The reduce() function in Python is part of the functools module, which needs to be
imported before it can be used.
1. The function passed as an argument is applied to the first two elements of the
iterable.
2. After this, the function is applied to the previously generated result and the
next element in the iterable.
3. This process continues until the whole iterable is processed.
4. The single value is returned as a result of applying the reduce function on the
iterable.
from functools import reduce
def product(x,y):
return x*y
O/P:--
210
import functools
my_list=(10,20,60,30,40)
def greater(a,b):
if a>b:
return a
else:
return b
x=[Link](greater,my_list)
print(x)
O/P:-
60
my_list=(10,20,60,30,40)
def lowest_digit(a,b):
if a<b:
return a
else:
return b
x=[Link](lowest_digit,my_list)
print(x)
O/P:-
10
my_str="Neeraj"
def greater(a,b):
if a>b:
return a
else:
return b
x=[Link](greater,my_str)
print("This char have greater asci value:",x)
O/P:-
This char have greater asci value: r
Decorators are the most common use of higher-order functions in Python. They
enable programmers to modify the behavior of a function or class. By wrapping one
function with another, decorators allow us to extend the behavior of the wrapped
function without permanently changing it. In this process, functions are passed as
arguments to another function and then called within the wrapper function.
# defining a decorator
def decorator(func):
def inner1():
print("Hello, this is before function execution")
func()
print("This is after function execution")
return inner1
def function():
print("This is inside the function !!")
function_used = decorator(function)
function_used()
O/P:--
Hello, this is before function execution
This is inside the function !!
This is after function execution
def decorator(func):
def inner1():
print("Hello, this is before function execution")
func()
print("This is after function execution")
return inner1
O/P:--
Hello, this is before function execution
This is inside the function !!
This is after function execution
Examples:---
def greet(fun):
def inner():
print("Good morning")
fun()
print("Thanks for using")
return inner
def hello():
print("Hello world")
var=greet(hello)
var()
O/P:--
Good morning
Hello world
Thanks for using
def greet(fun):
def inner():
print("Good morning")
fun()
print("Thanks for using")
return inner
@greet
def hello():
print("Hello world")
hello()
O/P:--
Good morning
Hello world
Thanks for using
def decorator1(fun):
def inner():
a=fun()
add = a+5
return add
return inner
def decorator2(fun):
def inner():
b=fun()
add = b+5
return add
return inner
def fun():
return 100
fun = decorator2(decorator1(fun))
print(fun())
O/P:--
110
def decorator1(fun):
def inner():
a=fun()
add = a+5
return add
return inner
def decorator2(fun):
def inner():
b=fun()
add = b+5
return add
return inner
@decorator2
@decorator1
def fun():
return 100
print(fun())
O/P:--
110
Generators are similar to functions but produce a sequence of values that can be
iterated over using loops. Instead of using return statements, generators use yield
statements to return values one at a time.
O/P:--
5
6
7
8
9
10
O/P:--
first object from generator : 5
Second object from generator : 6
7
8
9
10
O/P:--
object from generator : 5
object from generator : 6
object from generator : 7
object from generator : 8
object from generator : 9
object from generator : 10
x = 10
def sum(a, b):
print("Sum of two values: " , (a+b))
def multiplication(a, b):
print("Multiplication of two values: " , (a*b))
Now [Link] file is a module. [Link] module contains one variable and two
functions.
Import module_name
Note: Whenever we are using a module in our program, that module’s compiled file
will be generated and stored in the hard disk permanently.
Example:---
x = 10
def sum(a, b):
print("Sum of two values: " , (a+b))
def multiplication(a, b):
print("Multiplication of two values: " , (a*b))
O/P:--
Sum of two values: 30
----------------------------------------------------
import module as cal
print(10+cal.x)
O/P:--
20
Syntax:-
or
x = 10
def sum(a, b):
print("Sum of two values: " , (a+b))
def multiplication(a, b):
print("Multiplication of two values: " , (a*b))
# file name is [Link]
# In this file we are importing [Link] file as a module
# from keyword-------------------
from module import sum
sum(10,20)
O/P:--
Sum of two values: 30
# import * keyword-------------------
from module import *
sum(10,20)
O/P:--
Sum of two values: 30
x = 10
def sum(a, b):
print("Sum of two values: " , (a+b))
def multiplication(a, b):
print("Multiplication of two values: " , (a*b))
multi(5,10)
add(10,20)
print("Value of x=",y)
O/P:--
Multiplication of two values: 50
Sum of two values: 30
Value of x= 10
Note:- Once an alias name is given, we should use the alias name only and not
the original name.
By default, a module will be loaded only once even though we are importing multiple
times. Let’s consider a module with name module1.
# -------------------------------------------------
# file name is [Link]
# In this file we are importing [Link] file as a module
import module1
import module1
import module1
import module1
import module1
import module1
O/P:--
This comes from [Link]
This comes from [Link] file
The problem in this approach is if a module is updated outside after loading it in our
program, then the updated version of the module will not be available to our program.
We can solve this problem by reloading modules explicitly based on our requirement
wherever needed. We can reload by using the reload() function of the imp module.
Syntax:
import importlib
[Link](module1)
Or
from importlib import reload
reload(module1)
# file name is [Link]
print("This comes from [Link]")
# -------------------------------------------------
# file name is [Link]
# In this file we are importing [Link] file as a module
reload(module1)
reload(module1)
reload(module1)
reload(module1)
O/P:--
This comes from [Link]
This comes from [Link] file
This comes from [Link]
This comes from [Link]
This comes from [Link]
This comes from [Link]
Note:-- The main advantage of explicit module reloading is we can ensure that
updated versions are always available to our program.
----:Recursion:----
Recursion means that a function calls itself.
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = int(input("Enter any no: "))
print("The factorial of", num, "is", factorial(num))
else:
return n+summation(n-1)
num = int(input("Enter any no: "))
print(summation(num))
def findmin(list,n):
if n == 1:
return list[0]
else:
return min(list[n-1],findmin(list,n-1))
print(findmin(my_list,n))
# Write a function to find the greatest common divisor (GCD) of two positive
integers
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
x=int(input("Enter first no: "))
y=int(input("Enter second no: "))
print(gcd(x, y))
# Write a function to find the sum of all digits against user given no.
def sum_digits(n):
if n < 10:
return n
else:
return n % 10 + sum_digits(n // 10)
print(sum_digits(12345))
# Write a function to find the length of a string
def str_len(s):
if s == '':
return 0
else:
return 1 + str_len(s[1:])
my_str = input("Enter any string: ")
print(str_len(my_str))
1. class
2. object
Syntax:
def __init__(self):
body of the constructor
class Test:
def __init__(self):
print("Constructor executed....!!!!!!!")
t = Test()
O/P:--
Constructor executed....!!!!!!!
Yes, we can call constructor explicitly with object name. But since the constructor
gets executed automatically at the time of object creation, it is not recommended to
call it explicitly.
class Student:
def __init__(self):
print("Constructor called............")
O/P:--
Constructor called............
Constructor called............
Constructor called............
Constructor called............
# Constructor is not mandatory for any class, it is optional on the bases of our
requirement.
Class Test:
def m1(self):
print(“Instence method executed….!!!!!!”)
t = Test()
t.m1()
print(dir(Test))
O/P:--
Instence method executed….!!!!!!
[‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’,
‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’,
‘__init_subclass__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__ne__’, ‘__new__’,
‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’,
‘__subclasshook__’, ‘__weakref__’,
‘m1’]
How many parameters we passed in constructor:---
Constructor can accept n number of parameters. It totally depends on our
requirements. All values that need to be initialized during object creation should be
passed to the constructor. The first parameter of the constructor should always refer
to the current instance, which is typically denoted as self.
O/P:--
Constructor called............
<__main__.Student object at 0x00000245668B3400>
# help(Student)
obj1= Student("Neeraj",101,84)
print([Link])
print([Link])
print([Link])
print(Student.__doc__)
[Link]()
O/P:--
Neeraj
101
84
This class is develop by Neeraj for demo
my name is Neeraj
my roll no is 101
my marks is 84
We can define multiple constructors (__init__()) methods in a class but always last
one is executed.
class Student:
''' This class is develop by Neeraj for demo'''
def __init__(self,name,roll,marks):
[Link]=name
[Link]=roll
[Link] = marks
def __init__(self,name,roll,marks,city):
[Link]=name
[Link]=roll
[Link] = marks
[Link] = city
def display(self):
print("my name is", [Link])
print("my roll no is", [Link])
print("my marks is", [Link])
print("my city is", [Link])
# help(Student)
obj1= Student("Neeraj",101,84)
obj1= Student("Neeraj",101,84,"Bhopal")
print([Link])
print([Link])
print([Link])
print(Student.__doc__)
[Link]()
O/P:---
obj1= Student("Neeraj",101,84)
TypeError: Student.__init__() missing 1 required positional argument: 'city'
class Student:
''' This class is develop by Neeraj for demo'''
def __init__(self,name,roll,marks):
[Link]=name
[Link]=roll
[Link] = marks
def __init__(self,name,roll,marks,city):
[Link]=name
[Link]=roll
[Link] = marks
[Link] = city
def display(self):
print("my name is", [Link])
print("my roll no is", [Link])
print("my marks is", [Link])
print("my city is", [Link])
# obj1= Student("Neeraj",101,84)
obj1= Student("Neeraj",101,84,"Bhopal")
print([Link])
print([Link])
print([Link])
print([Link])
[Link]()
O/P:--
Neeraj
101
84
Bhopal
my name is Neeraj
my roll no is 101
my marks is 84
my city is Bhopal
Types of Variables in a Class in Python:---
Inside a class, we can have three types of variables. They are:
1. Instance variables (object level variables)
2. Static variables (class level variables)
3. Local variables
stu1 = Student("Neeraj",101,"90","Bhopal")
stu2 = Student("Rahul",102,"92","Indore")
print([Link])
print([Link])
[Link]()
[Link]()
print(stu1.__dict__)
print(stu2.__dict__)
O/P:--
Neeraj
Rahul
my name is Neeraj
my roll no is 101
my marks is 90
my city is Bhopal
my name is Rahul
my roll no is 102
my marks is 92
my city is Indore
{'name': 'Neeraj', 'roll': 101, 'marks': '90', 'city': 'Bhopal'}
{'name': 'Rahul', 'roll': 102, 'marks': '92', 'city': 'Indore'}
O/P:--
my name is Neeraj
my roll no is 101
my marks is 90
my city is Bhopal
Neeraj
my name is Rahul
my roll no is 102
my marks is 92
my city is Indore
Rahul
{'name': 'Rahul', 'roll': 102, 'marks': '92', 'city': 'Indore'}
# Instence Variable..........(By using object)
class Student:
def __init__(self):
print("This is constructor")
def m1(self):
print("This is instance method")
t=Student()
t.m1()
t.a=10
t.b=20
t.c=55
print(t.a)
print(t.b)
print(t.c)
print(t.__dict__)
O/P:--
This is constructor
This is instance method
10
20
55
{'a': 10, 'b': 20, 'c': 55}
By using object name :--- We can access instance variables outside of the class by
using object name.
s= Student()
print(s.a)
print(s.b)
O/p:--
10
20
# Static variable...........
class Student:
''' This class is develop by Neeraj for demo'''
School_name="SHSC"
def __init__(self,name,roll,marks,city):
[Link]=name
[Link]=roll
[Link] = marks
[Link] = city
def display(self):
print("my name is", [Link])