Professional Documents
Culture Documents
The data stored in memory can be of many types. For example, a person's age is stored
as a numeric value and his or her address is stored as alphanumeric characters. Python has
various standard data types that are used to define the operations possible on them and the
storage method for each of them.
1. Numbers
2. Sequence Type
3. Dictionary
4. Boolean
5. Set
2.1.1 Numbers:
Number stores numeric values. The integer, float, and complex values belong to a Python
Numbers data-type. Python provides the type() function to know the data-type of the variable.
Similarly, the isinstance() function is used to check an object belongs to a particular class.
For example;
Output:
1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has
no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote
the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.
2.1.2Sequence Type:
String:
The string can be defined as the sequence of characters represented in the quotation marks. In
Python, we can use single, double, or triple quotes to define a string.
String handling in Python is a straightforward task since Python provides built-in functions and
operators to perform operations in the string.
In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
Output:
List:
Python Lists are similar to arrays in C. However, the list can contain data of different types. The
items stored in the list are separated with a comma (,) and enclosed within square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator (+) and
repetition operator (*) works with the list in the same way as they were working with the strings.
Tuple:
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The items of the tuple are separated with a comma (,) and enclosed
in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.
Output:
Dictionary:
The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.
it
Boolean:
Boolean type provides two built-in values, True and False. These values are used to determine
the given statement true or false. It denotes by the class bool. True can be represented by any
non-zero value or 'T' whereas false can be represented by the 0 or 'F'.
Output:
it
Set:
Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after
creation), and has unique elements. In set, the order of the elements is undefined; it may return
the changed sequence of the element. The set is created by using a built-in function set(), or a
sequence of elements is passed in the curly braces and separated by the comma. It can contain
various types of values.
Output:
Whenever an object is instantiated, it is assigned a unique object id. The type of the
object is defined at the runtime and it can’t be changed afterwards. However, it’s state can be
changed if it is a mutable object.
To summarize the difference, mutable objects can change their state or contents and
immutable objects can’t change their state or content.
Immutable Objects: These are of in-built types like int, float, bool, string, unicode, tuple.
In simple words, an immutable object can’t be changed after it is created.
Mutable Objects : These are of type list, dict, set . Custom classes are generally mutable.
Mutable and immutable objects are handled differently in python. Immutable objects are
quicker to access and are expensive to change because it involves the creation of a copy.
Whereas mutable objects are easy to change. Use of mutable objects is recommended when
there is a need to change the size or content of the object
It is important to understand that every object in Python has an ID (identity), and type and
a value. Once created, the ID of an object never changes. It is a unique identifier for it, and it is
used behind the scenes by Python to retrieve the object when we want to use it.
The type also never changes. The type tells what operations are supported by the object and
the possible values that can be assigned to it.
The value can either change or not. If it can, the object is said to be mutable, while when it
cannot, the object is said to be immutable.
Output is:
Byte Arrays:
Byte arrays represent the mutable version of bytes objects. They expose most of the
usual methods of mutable sequences as well as most of the methods of the bytes type. Items
are integers in the range [0, 256).
Sets
Python provides two set types, set and frozenset. They are unordered collections of immutable
objects.
Frozen Sets:
As discussed in the previous section, frozensets are similar to sets. However, frozenset objects are
quite limited in respect of their mutable counterpart since they cannot be changed. Nevertheless,
they still prove very effective for membership test, union, intersection, and difference operations,
and for performance reasons.
Tuples:
The last immutable sequence type we’re going to see is the tuple. A tuple is a sequence of
arbitrary Python objects. In a tuple, items are separated by commas. These, too, are immutable, as
shown in the following example:
2.3 FUNDAMENTAL DATA TYPES:
Data type is a collection of data or items. The basic fundamental data types are numeric data
type which consists of the following:
INT
FLOAT
COMPLEX
BOOLEAN
STRING.
These represent numbers in the range -2147483648 through 2147483647. (The range
may be larger on machines with a larger natural word size, but not smaller.) When the result of
an operation would fall outside this range, the result is normally returned as a long integer (in
some cases, the exception OverflowError is raised instead). For the purpose of shift and mask
operations, integers are assumed to have a binary, 2’s complement notation using 32 or more
bits, and hiding no bits from the user (i.e., all 4294967296 different bit patterns correspond to
different values).
Plain integers (also just called integers) are implemented using long in C, which gives
them at least 32 bits of precision (sys.maxint is always set to the maximum plain integer value
for the current platform; the minimum value is -sys.maxint - 1). Long integers have unlimited
precision.
Numbers are created by numeric literals or as the result of built-in functions and
operators. Unadorned integer literals (including binary, hex, and octal numbers) yield plain
integers unless the value they denote is too large to be represented as a plain integer, in which
case they yield a long integer. Integer literals with an ‘L’ or ‘l’ suffix yield long integers (‘L’ is
preferred because 1l looks too much like eleven!).
These represent machine-level double precision floating point numbers. You are at the
mercy of the underlying machine architecture (and C or Java implementation) for the accepted
range and handling of overflow. Python does not support single-precision floating point
numbers; the savings in processor and memory usage that are usually the reason for using these
is dwarfed by the overhead of using objects in Python, so there is no reason to complicate the
language with two kinds of floating point numbers.
Floating point numbers are usually implemented using double in C; information about the
precision and internal representation of floating point numbers for the machine on which your
program is running is available in sys.float_info.
In Python we can print decimal equivalent of binary, octal and hexadecimal numbers using the
following built-in functions.
Eg: x = 10
y = bin(x)
print (y)
Eg: result = hex(1)
result2 = hex(342)
print(result)
print(result2)
Eg: val = oct(10)
print("Octal value of 10:",val)
The Python built-in functions are defined as the functions whose functionality is pre-
defined in Python. The python interpreter has several functions that are always present for use.
These functions are known as Built-in Functions. There are several built-in functions in Python
which are listed below:
4. bool(): converts a value
1. test1 = [0]
to boolean(True or False)
2. print(test1,'is',bool(test1))
using the standard truth
testing procedure. OUTPUT: [0] is True
6. callable() : is something
1. x = 8
that can be called. This
2. print(callable(x))
built-in function checks
and returns true if the OUTPUT: False
object passed appears to
be callable, otherwise
false.
7. compile() : takes source
1. code_str = 'x=5\ny=10\nprint("sum =",x+y)'
code as input and returns
2. code = compile(code_str, 'sum.py', 'exec')
a code object which can
3. print(type(code))
later be executed by
4. exec(code)
exec() function. 5. exec(x)
OUTPUT: <class 'code'>
sum = 15
OUTPUT: [‘c’,’e’,’m’,’r’,’w’]
44. next() :is used to fetch next number = iter([256, 32, 82])
item from the collection. item = next(number)
print(item)
1. item = next(number)
2. print(item)
OUTPUT: 256
32
OUTPUT: 10
11
7
OUTPUT: True
False
True
True
Sometimes, you may need to perform conversions between the built-in types. To convert
between types, you simply use the type name as a function.
There are several built-in functions to perform conversion from one data type to another. These
functions return a new object representing the converted value.
1 int(x [,base])
2 long(x [,base] )
3 float(x)
Converts x to a floating-point number.
4 complex(real [,imag])
5 str(x)
6 repr(x)
7 eval(str)
8 tuple(s)
Converts s to a tuple.
9 list(s)
Converts s to a list.
10 set(s)
Converts s to a set.
11 dict(d)
13 chr(x)
14 unichr(x)
15 ord(x)
16 hex(x)
17 oct(x)
The operator can be defined as a symbol which is responsible for a particular operation
between two operands. Operators are the pillars of a program on which the logic is built in a
specific programming language. Python provides a variety of operators, which are described as
follows.
Arithmetic operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic operators are used to perform arithmetic operations between two operands. It includes
+ (addition), - (subtraction), *(multiplication), /(divide), %(reminder), //(floor division), and
exponent (**) operators.
Comparison operators are used to comparing the value of the two operands and
returns Boolean true or false accordingly. The comparison operators are described in the
following table.
The assignment operators are used to assign the value of the right expression to the left operand.
The assignment operators are described in the following table.
2.8.4 Bitwise Operators:
The bitwise operators perform bit by bit operation on the values of the two operands. Consider
the following example.
For example,
2.8.5 Logical Operators:
The logical operators are used primarily in the expression evaluation to make a decision. Python
supports the following logical operators.
Python membership operators are used to check the membership of value inside a Python data
structure. If the value is present in the data structure, then the resulting value is true otherwise it
returns false.
2.8.7 Identity Operators:
The identity operators are used to decide whether an element certain class or type
On our way up the learning curve for Python, we only need to deal with Python
iterables not so huge. But when building an application with it, not always do we need to
retrieve the entire iterable. In such cases, slicing is useful as it lets us choose what to see and
focus on. This aids readability and implements abstraction.
To slice a iterable, we use the slicing operator, that is [ ]. To separate the start, stop, and step
values, we use the colon ( : ).
Say you want to declare a list with the values 1,2,3,4,5, and only want to see values 2,3, and 4.
You can slice the list for that.
1. >>> list=[1,2,3,4,5]
2. >>> list[1:4]
[2, 3, 4]
slice() is a constructor that creates a Python Slice object to represent the set of indices that
range(start, stop, step) specifies. With this, we can slice a sequence like a string, a tuple, a list, a
range object, or a bytes object. These are all objects that support sequence protocols and
implement __getitem__() and __len__().
The slice() function returns a Python Slice Object.
1. slice(stop)
1. >>>slice(3)
slice(None, 3, None)
1. >>> l=[1,2,3,4,5]
2. >>> l[slice(3)]
[1, 2, 3]
Note that it displays values at the indices 0, 1, and 2. It stops at index 3.
We can also specify the interval. Slicing a string may give us a substring when the step size is 1.
You must learn about Python String
1. >>> s='helloworld'
2. >>> s[slice(1,6,2)]
‘elw’
2. >>> s[slice(1,6)]
‘ellow’
But like we’ve seen with lists earlier, we can pass negative indices too. These are what it
traverses from the right.
To read the same value right to left, we do:
1. >>> s='helloworld'
2. >>> s[slice(-5,-10,-1)]
‘wolle’
Here’s how we traverse right to left:
Python String Slice
Now let’s take a look at performing Python Slicing on tuples. Check the following code:
Positive Indices-
1. >>> t=(1,2,3,4,5)
2. >>> t[slice(2,4)]
(3, 4)
Negative Indices-
1. >>> t[slice(-1,-5,-2)]
(5, 3)
We have often sliced lists using [ : ]. Let’s try that one more time.
Remember the previous Python Slicing example? Now take a look at this-
1. >>> t[-1:-5:-2]
(5, 3)
So we concur that slicing is a way to choose indices for elements to show. What slice() really
does is give us indices for those. We can use the slice() function as a subscript.
When indexing, what happens when we do not pass one or more of the values?
1. >>> t[:3]#From 0 to 2
(1, 2, 3)
(4, 5)
(1, 2, 3, 4, 5)
a. Extended Python Slices with a step value
1. >>> t[::-1]#Reverse
(5, 4, 3, 2, 1)
(5, 3, 1)
(1, 3, 5)
1. >>> t[:5:-1]#Index 5 to end (already ahead of that), right to left; results in empty tuple
()
1. >>> t
(1, 2, 3, 4, 5)
(5, 2)
1. >>> l=[1,2,3,4,5]
2. >>> l[1:4]
[2, 3, 4]
1. >>> l[1:4]=[2,3,3.5,4]
2. >>> l
[1, 2, 3, 3.5, 4, 5]
The length of the slice on the right should be equal to that on the left.
c. Deleting Python Slices
2. >>> l
[2, 3, 3.5, 5]
Decision making is the most important aspect of almost all the programming languages. As the
name implies, decision making allows us to run a particular block of code for a particular
decision. Here, the decisions are made on the validity of the particular conditions. Condition
checking is the backbone of decision making.
Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow the use of
parentheses for the block level code. In Python, indentation is used to declare a block. If two
statements are at the same indentation level, then they are the part of the same block.
Generally, four spaces are given to indent the statements which are a typical amount of
indentation in python.
Indentation is the most used part of the python language since it declares the block of code. All
the statements of one block are intended at the same level indentation. We will see how the
actual indentation takes place in decision making and other stuff in python.
The if statement is used to test a particular condition and if the condition is true, it executes a
block of code known as if-block. The condition of if statement can be any valid logical
expression which can be either evaluated to true or false.
1. if expression:
2. statement
Example 1
1. num = int(input("enter the number?"))
2. if num%2 == 0:
3. print("Number is even")
Output:
Number is even
1. a = int(input("Enter a? "));
2. b = int(input("Enter b? "));
3. c = int(input("Enter c? "));
4. if a>b and a>c:
5. print("a is largest");
6. if b>a and b>c:
7. print("b is largest");
8. if c>a and c>b:
9. print("c is largest");
Output:
Enter a? 100
Enter b? 120
Enter c? 130
c is largest
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)
1. age = int (input("Enter your age? "))
2. if age>=18:
3. print("You are eligible to vote !!");
4. else:
5. print("Sorry! you have to wait !!");
Output:
1. num = int(input("enter the number?"))
2. if num%2 == 0:
3. print("Number is even...")
4. else:
5. print("Number is odd...")
Output:
Number is even
The elif statement enables us to check multiple conditions and execute the specific block of
statements depending upon the true condition among them. We can have any number of elif
statements in our program depending upon our need. However, using elif is optional.
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement.
1. if expression 1:
2. # block of statements
3.
4. elif expression 2:
5. # block of statements
6.
7. elif expression 3:
8. # block of statements
9.
10. else:
11. # block of statements
Example 1
1. number = int(input("Enter the number?"))
2. if number==10:
3. print("number is equals to 10")
4. elif number==50:
5. print("number is equal to 50");
6. elif number==100:
7. print("number is equal to 100");
8. else:
9. print("number is not equal to 10, 50 or 100");
Output:
Example 2
1. marks = int(input("Enter the marks? "))
2. f marks > 85 and marks <= 100:
3. print("Congrats ! you scored grade A ...")
4. lif marks > 60 and marks <= 85:
5. print("You scored grade B + ...")
6. lif marks > 40 and marks <= 60:
7. print("You scored grade B ...")
8. lif (marks > 30 and marks <= 40):
9. print("You scored grade C ...")
10. lse:
11. print("Sorry you are fail ?")
The flow of the programs written in any programming language is sequential by default.
Sometimes we may need to alter the flow of the program. The execution of a specific code may
need to be repeated several numbers of times.
For this purpose, The programming languages provide various types of loops which are capable
of repeating some specific code several numbers of times. Consider the following diagram to
understand the working of a loop statement.
2.11.1 Why we use loops in python?
The looping simplifies the complex problems into the easy ones. It enables us to alter the flow
of the program so that instead of writing the same code again and again, we can repeat the
same code for a finite number of times. For example, if we need to print the first 10 natural
numbers then, instead of using the print statement 10 times, we can print inside a loop which
runs up to 10 iterations.
The for loop in Python is used to iterate the statements or a part of the program several times.
It is frequently used to traverse the data structures like list, tuple, or dictionary.
1. for iterating_var in sequence:
2. statement(s)
1. str = "Python"
2. for i in str:
3. print(i)
Output:
n
Example- 2: Program to print the table of the given number .
1. list = [1,2,3,4,5,6,7,8,9,10]
2. n = 5
3. for i in list:
4. c = n*i
5. print(c)
Output:
10
15
20
25
30
35
40
45
50s
1. list = [10,30,23,43,65,12]
2. sum = 0
3. for i in list:
4. sum = sum+i
5. print("The sum is:",sum)
Output:
The sum is: 183
The range() function is used to generate the sequence of the numbers. If we pass the range(10),
it will generate the numbers from 0 to 9. The syntax of the range() function is given below.
Syntax:
1. range(start,stop,step size)
1. for i in range(10):
2. print(i,end = ' ')
Output:
0123456789
1. n = int(input("Enter the number "))
2. for i in range(1,11):
3. c = n*i
4. print(n,"*",i,"=",c)
Output:
Enter the number 10
10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
10 * 10 = 100
1. n = int(input("Enter the number "))
2. for i in range(2,n,2):
3. print(i)
Output:
10
12
14
16
18
1. list = ['Peter','Joseph','Ricky','Devansh']
2. for i in range(len(list)):
3. print("Hello",list[i])
Output:
Hello Peter
Hello Joseph
Hello Ricky
Hello Devansh
Python allows us to nest any number of for loops inside a for loop. The inner loop is executed n
number of times for every iteration of the outer loop. The syntax is given below.
Syntax
1. for iterating_var1 in sequence: #outer loop
2. for iterating_var2 in sequence: #inner loop
3. #block of statements
4. #Other statements
1. # User input for number of rows
2. rows = int(input("Enter the rows:"))
3. # Outer loop will print number of rows
4. for i in range(0,rows+1):
5. # Inner loop will print number of Astrisk
6. for j in range(i):
7. print("*",end = '')
8. print()
Output:
**
***
****
*****
1. rows = int(input("Enter the rows"))
2. for i in range(0,rows+1):
3. for j in range(i):
4. print(i,end = '')
5. print()
Output:
22
333
4444
55555
Unlike other languages like C, C++, or Java, Python allows us to use the else statement with the
for loop which can be executed only when all the iterations are exhausted. Here, we must
notice that if the loop contains any of the break statement then the else statement will not be
executed.
Example 1
1. for i in range(0,5):
2. print(i)
3. else:
4. print("for loop completely exhausted, since there is no break.")
Output:
Example 2
1. for i in range(0,5):
2. print(i)
3. break;
4. else:print("for loop is exhausted");
5. print("The loop is broken due to break statement...came out of the loop")
In the above example, the loop is broken due to the break statement; therefore, the else
statement will not be executed. The statement present immediate next to else block will be
executed.
Output:
The Python while loop allows a part of the code to be executed until the given condition returns
false. It is also known as a pre-tested loop.
It can be viewed as a repeating if statement. When we don't know the number of iterations
then the while loop is most effective to use.
1. while expression:
2. statements
Here, the statements can be a single statement or a group of statements. The expression
should be any valid Python expression resulting in true or false. The true is any non-zero value
and false is 0.
1. i=1
2. #The while loop will iterate until condition becomes false.
3. While(i<=10):
4. print(i)
5. i=i+1
Output:
7
8
10
1. i=1
2. number=0
3. b=9
4. number = int(input("Enter the number:"))
5. while i<=10:
6. print("%d X %d = %d \n"%(number,i,number*i))
7. i = i+1
Output:
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
If the condition is given in the while loop never becomes false, then the while loop will never
terminate, and it turns into the infinite while loop.
Example 1
1. while (1):
2. print("Hi! we are inside the infinite while loop")
Output:
Example 2
1. var = 1
2. while(var != 2):
3. i = int(input("Enter the number:"))
4. print("Entered value is %d"%(i))
Output:
Entered value is 10
Entered value is 10
Entered value is 10
Infinite time
Python allows us to use the else statement with the while loop also. The else block is executed
when the condition given in the while statement becomes false. Like for loop, if the while loop
is broken using break statement, then the else block will not be executed, and the statement
present after else block will be executed. The else statement is optional to use with the while
loop. Consider the following example.
Example 1
1. i=1
2. while(i<=5):
3. print(i)
4. i=i+1
5. else:
6. print("The while loop exhausted")
Example 2
1. i=1
2. while(i<=5):
3. print(i)
4. i=i+1
5. if(i==3):
6. break
7. else:
8. print("The while loop exhausted")
Output:
In the above code, when the break statement encountered, then while loop stopped its
execution and skipped the else statement.
1. terms = int(input("Enter the terms "))
2. # first two intial terms
3. a = 0
4. b = 1
5. count = 0
6.
7. # check if the number of terms is Zero or negative
8. if (terms <= 0):
9. print("Please enter a valid integer")
10. elif (terms == 1):
11. print("Fibonacci sequence upto",limit,":")
12. print(a)
13. else:
14. print("Fibonacci sequence:")
15. while (count < terms) :
16. print(a, end = ' ')
17. c = a + b
18. # updateing values
19. a = b
20. b = c
21.
22. count += 1
Output:
Fibonacci sequence:
0 1 1 2 3 5 8 13 21 34
The break is a keyword in python which is used to bring the program control out of the loop.
The break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the
inner loop first and then proceeds to outer loops. In other words, we can say that break is used
to abort the current execution of the program and the control goes to the next line after the
loop.
The break is commonly used in the cases where we need to break the loop for a given
condition.
The syntax of the break is given below.
1. #loop statements
2. break;
Example 1
1. list =[1,2,3,4]
2. count = 1;
3. for i in list:
4. if i == 4:
5. print("item matched")
6. count = count + 1;
7. break
8. print("found at",count,"location");
Output:
item matched
found at 2 location
Example 2
1. str = "python"
2. for i in str:
3. if i == 'o':
4. break
5. print(i);
Output:
p
1. i = 0;
2. while 1:
3. print(i," ",end=""),
4. i=i+1;
5. if i == 10:
6. break;
7. print("came out of while loop");
Output:
Example 3
1. n=2
2. while 1:
3. i=1;
4. while i<=10:
5. print("%d X %d = %d\n"%(n,i,n*i));
6. i = i+1;
7. choice = int(input("Do you want to continue printing the table, press 0 for no?"))
8. if choice == 0:
9. break;
10. n=n+1
Output:
2X1=2
2X2=4
2X3=6
2X4=8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
3X2=6
3X3=9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
The continue statement in Python is used to bring the program control to the beginning of the
loop. The continue statement skips the remaining lines of code inside the loop and start with
the next iteration. It is mainly used for a particular condition inside the loop so that we can skip
some specific code for a particular condition.The continue statement in Python is used to bring
the program control to the beginning of the loop. The continue statement skips the remaining
lines of code inside the loop and start with the next iteration. It is mainly used for a particular
condition inside the loop so that we can skip some specific code for a particular condition.
Syntax
1. #loop statements
2. continue
3. #the code to be skipped
Flow Diagram
Consider the following examples.
Example 1
1. i = 0
2. while(i < 10):
3. i = i+1
4. if(i == 5):
5. continue
6. print(i)
Output:
10
Observe the output of above code, the value 5 is skipped because we have provided the if
condition using with continue statement in while loop. When it matched with the given
condition then control transferred to the beginning of the while loop and it skipped the value 5
from the code.
Example 2
1. str = "JavaTpoint"
2. for i in str:
3. if(i == 'T'):
4. continue
5. print(i)
Output:
The pass statement is a null operation since nothing happens when it is executed. It is used in
the cases where a statement is syntactically needed but we don't want to use any executable
statement at its place.
For example, it can be used while overriding a parent class method in the subclass but don't
want to give its specific implementation in the subclass.
Pass is also used where the code will be written somewhere but not yet written in the program
file. Consider the following example.
Example
1. list = [1,2,3,4,5]
2. flag = 0
3. for i in list:
4. print("Current element:",i,end=" ");
5. if i==3:
6. pass
7. print("\nWe are inside pass block\n");
8. flag = 1
9. if flag==1:
10. print("\nCame out of pass\n");
11. flag=0
Output:
Python Pass
In Python, the pass keyword is used to execute nothing; it means, when we don't want to
execute code, the pass can be used to execute empty. It is the same as the name refers to. It
just makes the control to pass by without executing any code. If we want to bypass any code
pass statement can be used.
It is beneficial when a statement is required syntactically, but we want we don't want to
execute or execute it later. The difference between the comments and pass is that, comments
are entirely ignored by the Python interpreter, where the pass statement is not ignored.
Suppose we have a loop, and we do not want to execute right this moment, but we will execute
in the future. Here we can use the pass.
1. # pass is just a placeholder for
2. # we will adde functionality later.
3. values = {'P', 'y', 't', 'h','o','n'}
4. for val in values:
5. pass
Example - 2:
1. for i in [1,2,3,4,5]:
2. if(i==4):
3. pass
4. print("This is pass block",i)
5. print(i)
Output:
1. 1
2. 2
3. 3
4. This is pass block 4
5. 4
6. 5
1. # Empty Function
2. def function_name(args):
3. pass
4. #Empty Class
5. class Python:
6. pass