0% found this document useful (0 votes)
4 views39 pages

Unit-1 Python Programming

Uploaded by

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

Unit-1 Python Programming

Uploaded by

geniusdwkr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Course Name Branch Subject Name with Code Semester Unit No.

B.Tech CSE/ECE/ME/MAE Python Programming(CS-205) 3rd 1

What is Python
Python is a general purpose, dynamic, high-level, and interpreted programming language.
It supports Object Oriented programming approach to develop applications. It is simple and
easy to learn and provides lots of high-level data structures.

Python is easy to learn yet powerful and versatile scripting language, which makes it
attractive for Application Development.

Python's syntax and dynamic typing with its interpreted nature make it an ideal language
for scripting and rapid application development.

Python supports multiple programming pattern, including object-oriented, imperative, and


functional or procedural programming styles.

Python is not intended to work in a particular area, such as web programming. That is why
it is known as multipurpose programming language because it can be used with web,
enterprise, 3D CAD, etc.

We don't need to use data types to declare variable because it is dynamically typed so we
can write a=10 to assign an integer value in an integer variable.

Python makes the development and debugging fast because there is no compilation step
included in Python development, and edit-test-debug cycle is very fast.

Python Features
Python provides many useful features which make it popular and valuable from the other
programming languages. It supports object-oriented programming, procedural
programming approaches and provides dynamic memory allocation. We have listed below a
few essential features.

1) Easy to Learn and Use


Python is easy to learn as compared to other programming languages. Its syntax is
straightforward and much the same as the English language. There is no use of the
semicolon or curly-bracket, the indentation defines the code block. It is the recommended
programming language for beginners.
2) Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello
world program you simply type print("Hello World"). It will take only one line to execute,
while Java or C takes multiple lines.

3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a
time. The advantage of being interpreted language, it makes debugging easy and portable.

4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and
Macintosh, etc. So, we can say that Python is a portable language. It enables programmers
to develop the software for several competing platforms by writing a program only once.

5) Free and Open Source


Python is freely available for everyone. It is freely available on its official
website www.python.org. It has a large community across the world that is dedicatedly
working towards make new python modules and functions. Anyone can contribute to the
Python community. The open-source means, "Anyone can download its source code without
paying any penny."

6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come into
existence. It supports inheritance, polymorphism, and encapsulation, etc. The object-
oriented procedure helps to programmer to write reusable code and develop applications in
less code.

7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it
can be used further in our Python code. It converts the program into byte code, and any
platform can use that byte code.

8) Large Standard Library


It provides a vast range of libraries for the various fields such as machine learning, web
developer, and also for the scripting. There are various machine learning libraries, such as
Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the
popular framework for Python web development.

9) GUI Programming Support


Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter,
Kivy are the libraries which are used for developing the web application.
10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line
by line like C,C++ Java. It makes easy to debug the code.

11. Embeddable
The code of the other programming language can use in the Python source code. We can
use Python source code in another programming language as well. It can embed other
language into our code.

12. Dynamic Memory Allocation


In Python, we don't need to specify the data-type of the variable. When we assign some
value to the variable, it automatically allocates the memory to the variable at run time.
Suppose we are assigned integer value 15 to x, then we don't need to write int x =
15. Just write x = 15.

Python History
o Python laid its foundation in the late 1980s.
o The implementation of Python was started in December 1989 by Guido Van
Rossum at CWI in Netherland.
o In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
alt.sources.
o In 1994, Python 1.0 was released with new features like lambda, map, filter, and
reduce.
o Python 2.0 added new features such as list comprehensions, garbage collection
systems.
o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed
to rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language, which
was capable of Exception Handling and interfacing with the Amoeba Operating
System.
o The following programming languages influence Python:
o ABC language.
o Modula-3

Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other
object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by
zero or more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers.
Python is a case sensitive programming language.
Thus, Manpower and manpower are two different identifiers in Python.
Here are naming conventions for Python identifiers −
 Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
 Starting an identifier with a single leading underscore indicates that the identifier
is private.
 Starting an identifier with two leading underscores indicates a strongly private
identifier.
 If the identifier also ends with two trailing underscores, the identifier is a language-
defined special name.

Identifier Naming
Variables are the example of identifiers. An Identifier is used to identify the literals used in
the program. The rules to name an identifier are given below.

o The first character of the variable must be an alphabet or underscore ( _ ).


o All the characters except the first character may be an alphabet of lower-case(a-z),
upper-case (A-Z), underscore, or digit (0-9).
o Identifier name must not contain any white-space, or special character (!, @, #, %,
^, &, *).
o Identifier name must not be similar to any keyword defined in the language.
o Identifier names are case sensitive; for example, my name, and MyName is not the
same.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.

Python keywords

The following list shows the Python keywords. These are reserved words and you cannot
use them as constant or variable or any other identifier names. All the Python keywords
contain lowercase letters only.
and exec not

assert finally or

break for pass

class from print

continue global raise

def if return

del import try

elif in while

else is with

except lambda yield

Python Variables
Variable is a name that is used to refer to memory location. Python variable is also known
as an identifier and used to hold value.

In Python, we don't need to specify the type of variable because Python is a infer language
and smart enough to get variable type.

Variable names can be a group of both the letters and digits, but they have to begin with a
letter or an underscore.

It is recommended to use lowercase letters for the variable name. Rahul and rahul both are
two different variables.
Declaring Variable and Assigning Values
Python does not bind us to declare a variable before using it in the application. It allows us
to create a variable at the required time.

We don't need to declare explicitly variable in Python. When we assign any value to the
variable, that variable is declared automatically.

The equal (=) operator is used to assign value to a variable.

Object References
It is necessary to understand how the Python interpreter works when we declare a variable.
The process of treating variables is somewhat different from many other programming
languages.

Python is the highly object-oriented programming language; that's why every data item
belongs to a specific type of class. Consider the following example.

print("John")

Output:

John

The Python object creates an integer object and displays it to the console. In the above
print statement, we have created a string object. Let's check the type of it using the Python
built-in type() function.

type("John")

Output:

<class 'str'>

In Python, variables are a symbolic name that is a reference or pointer to an object. The
variables are used to denote objects by that name.

Let's understand the following example

a = 50

In the above image, the variable a refers to an integer object.


Suppose we assign the integer value 50 to a new variable b.

a = 50

b=a

The variable b refers to the same object that a points to because Python does not create
another object.

Let's assign the new value to b. Now both variables will refer to the different objects.

a = 50

b =100

Python manages memory efficiently if we assign the same variable to two different values.

Object Identity
In Python, every created object identifies uniquely in Python. Python provides the
guaranteed that no two objects will have the same identifier. The built-in id() function, is
used to identify the object identifier. Consider the following example.

a = 50
b=a
print(id(a))
print(id(b))
# Reassigned variable a
a = 500
print(id(a))

Output:
140734982691168
140734982691168
2822056960944

We assigned the b = a, a and b both point to the same object. When we checked by
the id() function it returned the same number. We reassign a to 500; then it referred to the
new object identifier.

Variable Names
We have already discussed how to declare the valid variable. Variable names can be any
length can have uppercase, lowercase (A to Z, a to z), the digit (0-9), and underscore
character(_). Consider the following example of valid variables names.

name = "Devansh"
age = 20
marks = 80.50

print(name)
print(age)
print(marks)

Output:

Devansh
20
80.5

Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement, which is also
known as multiple assignments.

We can apply multiple assignments in two ways, either by assigning a single value to
multiple variables or assigning multiple values to multiple variables. Consider the following
example.

1. Assigning single value to multiple variables

Eg:

x=y=z=50
print(x)
print(y)
print(z)

Output:

50
50
50

2. Assigning multiple values to multiple variables:

Eg:

a,b,c=5,10,15
print a
print b
print c

Output:

5
10
15

The values will be assigned in the order in which variables appear.

Python Data Types


Variables can hold values, and every value has a data-type. Python is a dynamically typed
language; hence we do not need to define the type of the variable while declaring it. The
interpreter implicitly binds the value with its type.

a=5

The variable a holds integer value five and we did not define its type. Python interpreter will
automatically interpret variables a as an integer type.

Python enables us to check the type of the variable used in the program. Python provides us
the type() function, which returns the type of the variable passed.

Consider the following example to define the values of different data types and checking its
type.
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))

Output:

<type 'int'>
<type 'str'>
<type 'float'>

Standard data types


A variable can hold different types of values. For example, a person's name must be stored
as a string whereas its id must be stored as an integer.

Python provides various standard data types that define the storage method on each of
them. The data types defined in Python are given below.

1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
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.

Python creates Number objects when a number is assigned to a variable. For example;

a=5
print("The type of a", type(a))

b = 40.5
print("The type of b", type(b))

c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))

Output:
The type of a <class 'int'>
The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True
Python supports three types of numeric data.

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.

Sequence 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".

The operator * is known as a repetition operator as the operation "Python" *2 returns


'Python Python'.

The following example illustrates the string in Python.

Example - 1

str = "string using double quotes"


print(str)
s = '''''A multiline
string'''
print(s)

Output:

string using double quotes


A multiline
string

Example - 2

str1 = 'hello javatpoint' #string str1


str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2

Output:

he
o
hello javatpointhello javatpoint
hello javatpoint how are you

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.

Consider the following example.

list1 = [1, "hi", "Python", 2]


#Checking type of given list
print(type(list1))

#Printing the list1


print (list1)

# List slicing
print (list1[3:])

# List slicing
print (list1[0:2])

# List Concatenation using + operator


print (list1 + list1)

# List repetation using * operator


print (list1 * 3)

Output:

[1, 'hi', 'Python', 2]


[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

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.

Let's see a simple example of the tuple

tup = ("hi", "Python", 2)


# Checking type of tup
print (type(tup))

#Printing the tuple


print (tup)

# Tuple slicing
print (tup[1:])
print (tup[0:1])

# Tuple concatenation using + operator


print (tup + tup)

# Tuple repatation using * operator


print (tup * 3)

# Adding value to tup. It will throw an error.


t[2] = "hi"

Output:

<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)

Traceback (most recent call last):


File "main.py", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment
Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative array or
a hash table where each key stores a specific value. Key can hold any primitive data type,
whereas value is an arbitrary Python object.

The items in the dictionary are separated with the comma (,) and enclosed in the curly
braces {}.

Consider the following example.

d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}

# Printing dictionary
print (d)

# Accesing value using keys


print("1st name is "+d[1])
print("2nd name is "+ d[4])

print (d.keys())
print (d.values())

Output:

1st name is Jimmy


2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])

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'.
Consider the following example.

# Python program to check the boolean type


print(type(True))
print(type(False))
print(false)

Output:

<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined

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. Consider the following example.

# Creating Empty set


set1 = set()

set2 = {'James', 2, 3,'Python'}

#Printing Set value


print(set2)

# Adding element to the set

set2.add(10)
print(set2)

#Removing element from the set


set2.remove(2)
print(set2)

Output:

{3, 'Python', 'James', 2}


{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}

python data types are divided in two categories, mutable data types and
immutable data types.

Immutable Data types in Python


1. Numeric
2. String
3. Tuple

Mutable Data types in Python


1. List
2. Dictionary
3. Set

Python Operators
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.

o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators

Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations between two operands. It
includes + (addition), - (subtraction), *(multiplication), /(divide), %(reminder), //(floor
division), and exponent (**) operators.

Consider the following table for a detailed explanation of arithmetic operators.

Operator Description

+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 =>


a+b = 30

- (Subtraction) It is used to subtract the second operand from the first operand. If
the first operand is less than the second operand, the value results
negative. For example, if a = 20, b = 10 => a - b = 10
/ (divide) It returns the quotient after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a/b = 2.0

* It is used to multiply one operand with the other. For example, if a =


(Multiplication) 20, b = 10 => a * b = 200

% (reminder) It returns the reminder after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a%b = 0

** (Exponent) It is an exponent operator represented as it calculates the first


operand power to the second operand.

// (Floor It gives the floor value of the quotient produced by dividing the two
division) operands.

Comparison operator
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.

Operator Description

== If the value of two operands is equal, then the condition becomes true.

!= If the value of two operands is not equal, then the condition becomes true.

<= If the first operand is less than or equal to the second operand, then the condition
becomes true.

>= If the first operand is greater than or equal to the second operand, then the
condition becomes true.

> If the first operand is greater than the second operand, then the condition becomes
true.
< If the first operand is less than the second operand, then the condition becomes
true.

Assignment Operators
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.

Operator Description

= It assigns the value of the right expression to the left operand.

+= It increases the value of the left operand by the value of the right operand and
assigns the modified value back to left operand. For example, if a = 10, b = 20
=> a+ = b will be equal to a = a+ b and therefore, a = 30.

-= It decreases the value of the left operand by the value of the right operand and
assigns the modified value back to left operand. For example, if a = 20, b = 10
=> a- = b will be equal to a = a- b and therefore, a = 10.

*= It multiplies the value of the left operand by the value of the right operand and
assigns the modified value back to then the left operand. For example, if a = 10,
b = 20 => a* = b will be equal to a = a* b and therefore, a = 200.

%= It divides the value of the left operand by the value of the right operand and
assigns the reminder back to the left operand. For example, if a = 20, b = 10 =>
a % = b will be equal to a = a % b and therefore, a = 0.

**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign
4**2 = 16 to a.

//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign
4//3 = 1 to a.
Bitwise Operators
The bitwise operators perform bit by bit operation on the values of the two operands.
Consider the following example.

For example,

if a = 7
b=6
then, binary (a) = 0111
binary (b) = 0011

hence, a & b = 0011


a | b = 0111
a ^ b = 0100
~ a = 1000

Operator Description

& (binary If both the bits at the same place in two operands are 1, then 1 is
and) copied to the result. Otherwise, 0 is copied.

| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the
resulting bit will be 1.

^ (binary The resulting bit will be 1 if both the bits are different; otherwise, the
xor) resulting bit will be 0.

~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit is
0, the resulting bit will be 1 and vice versa.

<< (left The left operand value is moved left by the number of bits present in
shift) the right operand.

>> (right The left operand is moved right by the number of bits present in the
shift) right operand.

Logical Operators
The logical operators are used primarily in the expression evaluation to make a decision.
Python supports the following logical operators.
Operator Description

and If both the expression are true, then the condition will be true. If a and b are
the two expressions, a → true, b → true => a and b → true.

or If one of the expressions is true, then the condition will be true. If a and b are
the two expressions, a → true, b → false => a or b → true.

not If an expression a is true, then not (a) will be false and vice versa.

Membership 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.

Operator Description

in It is evaluated to be true if the first operand is found in the second operand


(list, tuple, or dictionary).

not in It is evaluated to be true if the first operand is not found in the second operand
(list, tuple, or dictionary).

Identity Operators
The identity operators are used to decide whether an element certain class or type.

Operator Description

is It is evaluated to be true if the reference present at both sides point to the


same object.
is not It is evaluated to be true if the reference present at both sides do not point to
the same object.

Input and output function


Python provides numerous built-in functions that are readily available to us at
the Python prompt.
Some of the functions like input() and print() are widely used for standard
input and output operations respectively.

Python Output Using print() function


We use the print() function to output data to the standard output device
(screen).

An example of its use is given below.

print('This sentence is output to the screen')

Output

This sentence is output to the screen

Another example is given below:

a = 5
print('The value of a is', a)

Output

The value of a is 5
In the second print() statement, we can notice that space was added
between the string and the value of variable a

Python Input
we might want to take the input from the user. In Python, we have
the input() function to allow this. The syntax for input() is:

input([prompt])

where prompt is the string we wish to display on the screen. It is optional.

>>> num = input('Enter a number: ')


Enter a number: 10
>>> num
'10'

Here, we can see that the entered value 10 is a string, not a number. To
convert this into a number we can use int() or float() functions.

>>> int('10')
10
>>> float('10')
10.0

Python If-else statements


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.

In python, decision making is performed by the following statements.

Statement Description
If Statement The if statement is used to test a specific condition. If the condition is
true, a block of code (if-block) will be executed.

If - else The if-else statement is similar to if statement except the fact that, it also
Statement provides the block of the code for the false case of the condition to be
checked. If the condition provided in the if statement is false, then the
else statement will be executed.

Nested if Nested if statements enable us to use if ? else statement inside an outer if


Statement statement.

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
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.
The syntax of the if-statement is given below.

if expression:
statement
Example 1
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")

Output:

enter the number?10


Number is even
Example 2 : Program to print the largest of the three
numbers.
a = int(input("Enter a? "));
b = int(input("Enter b? "));
c = int(input("Enter c? "));
if a>b and a>c:
print("a is largest");
if b>a and b>c:
print("b is largest");
if c>a and c>b:
print("c is largest");

Output:

Enter a? 100
Enter b? 120
Enter c? 130
c is largest

The if-else statement


The if-else statement provides an else block combined with the if statement which is
executed in the false case of the condition.

If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.

The syntax of the if-else statement is given below.

if condition:
#block of statements
else:
#another block of statements (else-block)

Example 1 : Program to check whether a person is eligible to


vote or not.
age = int (input("Enter your age? "))
if age>=18:
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");

Output:

Enter your age? 90


You are eligible to vote !!

The elif statement


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.

The syntax of the elif statement is given below.

if expression 1:
# block of statements

elif expression 2:
# block of statements

elif expression 3:
# block of statements

else:
# block of statements
Example 1
number = int(input("Enter the number?"))
if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50");
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");

Output:

Enter the number?15


number is not equal to 10, 50 or 100

Python Loops
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.
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.

Advantages of loops
There are the following advantages of loops in Python.

1. It provides code re-usability.


2. Using loops, we do not need to write the same code again and again.
3. Using loops, we can traverse over the elements of data structures (array or linked
lists).

There are the following loop statements in Python.


Loop Description
Statement

for loop The for loop is used in the case where we need to execute some part of the
code until the given condition is satisfied. The for loop is also called as a per-
tested loop. It is better to use for loop if the number of iteration is known in
advance.

while loop The while loop is to be used in the scenario where we don't know the number
of iterations in advance. The block of statements is executed in the while loop
until the condition specified in the while loop is satisfied. It is also called a pre-
tested loop.

do-while The do-while loop continues until a given condition satisfies. It is also called
loop post tested loop. It is used when it is necessary to execute the loop at least
once (mostly menu driven programs).

Python for loop


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.

The syntax of for loop in python is given below.

for iterating_var in sequence:


statement(s)
For loop Using Sequence
Example-1: Iterating string using for loop

str = "Python"
for i in str:
print(i)

Output:

P
y
t
h
o
n

Example- 2: Program to print the table of the given number .

list = [1,2,3,4,5,6,7,8,9,10]
n=5
for i in list:
c = n*i
print(c)

Output:

5
10
15
20
25
30
35
40
45
50s

For loop Using range() function


The range() function

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:

range(start,stop,step size)
o The start represents the beginning of the iteration.
o The stop represents that the loop will iterate till stop-1. The range(1,5) will
generate numbers 1 to 4 iterations. It is optional.
o The step size is used to skip the specific numbers from the iteration. It is optional to
use. By default, the step size is 1. It is optional.

Consider the following examples:

Example-1: Program to print numbers in sequence.


for i in range(10):
print(i,end = ' ')

Output:

0 1 2 3 4 5 6 7 8 9

Using else statement with for loop


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
for i in range(0,5):
print(i)
else:
print("for loop completely exhausted, since there is no break.")

Output:

0
1
2
3
4
for loop completely exhausted, since there is no break.

The for loop completely exhausted, since there is no break.

Example 2
for i in range(0,5):
print(i)
break;
else:print("for loop is exhausted");
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:

0
The loop is broken due to the break statement...came out of the loop. We will learn more
about the break statement in next tutorial.

Python While loop


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.

The syntax is given below.

while expression:
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.

Example-1: Program to print 1 to 10 using while loop


i=1
#The while loop will iterate until condition becomes false.
While(i<=10):
print(i)
i=i+1

Output:

1
2
3
4
5
6
7
8
9
10

Infinite while loop


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.
Any non-zero value in the while loop indicates an always-true condition, whereas zero
indicates the always-false condition. This type of approach is useful if we want our program
to run continuously in the loop without any disturbance.

Example 1
while (1):
print("Hi! we are inside the infinite while loop")

Output:

Hi! we are inside the infinite while loop


Hi! we are inside the infinite while loop

Using else with while loop


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
i=1
while(i<=5):
print(i)
i=i+1
else:
print("The while loop exhausted")
Example 2
i=1
while(i<=5):
print(i)
i=i+1
if(i==3):
break
else:
print("The while loop exhausted")

Output:

1
2

In the above code, when the break statement encountered, then while loop stopped its
execution and skipped the else statement.
Python break statement
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.

#loop statements
break;

Example 1
list =[1,2,3,4]
count = 1;
for i in list:
if i == 4:
print("item matched")
count = count + 1;
break
print("found at",count,"location");

Output:

item matched
found at 2 location

Example 2
str = "python"
for i in str:
if i == 'o':
break
print(i);
Output:

p
y
t
h

Python continue Statement


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
#loop statements
continue
#the code to be skipped
Consider the following examples.

Example 1
i=0
while(i < 10):
i = i+1
if(i == 5):
continue
print(i)

Output:

1
2
3
4
6
7
8
9
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.

Let's have a look at another example:

Pass Statement
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
list = [1,2,3,4,5]
flag = 0
for i in list:
print("Current element:",i,end=" ");
if i==3:
pass
print("\nWe are inside pass block\n");
flag = 1
if flag==1:
print("\nCame out of pass\n");
flag=0

Output:

Current element: 1 Current element: 2 Current element: 3


We are inside pass block

Came out of pass

Current element: 4 Current element: 5

You might also like