Python UNIT1&2 24
Python UNIT1&2 24
Introduction to Python: History, Features, Applications, First Python Program, Variables, Data
Types, Numbers, Operators, Input and Output statements, inbuilt functions
Introduction to Python:
History:
• Python was initially designed by Guido van Rossum in 1991 and developed by Python Software
Foundation.
• It was mainly developed for emphasis on code readability, and its syntax allows programmers to
express concepts in fewer lines of code.
• Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol- 68,
SmallTalk, and Unix shell and other scripting languages.
• Like Perl, Python source code is now available under the GNU General Public License (GPL).
Features:
Python provides many useful features which make it popular and valuable from the other
programming languages.
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.
[Type here]
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.
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.
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.
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 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
[Type here]
our code.
[Type here]
Applications:
Python is known for its general-purpose nature that makes it applicable in almost every domain
of software development. Python makes its presence in every emerging field. It is the fastest-
growing programming language and can develop any application.
1) Web Applications
We can use Python to develop web applications. It provides libraries to handle internet protocols
such as HTML and XML, JSON, Email processing, request, beautifulSoup, Feedparser, etc. One
of Python web-framework named Django is used on Instagram. Python provides many useful
frameworks, and these are given below:
[Type here]
2) Desktop GUI Applications
The GUI stands for the Graphical User Interface, which provides a smooth interaction to any
application. Python provides a Tk GUI library to develop a user interface. Some popular GUI
libraries are given below.
• Tkinter or Tk
• wxWidgetM
• Kivy (used for writing multitouch applications )
• PyQt or Pyside
3) Console-based Application
Console-based applications run from the command-line or shell. These applications are computer
program which are used commands to execute. This kind of application was more popular in the
old generation of computers. Python can develop this kind of application very effectively. It is
famous for having REPL, which means the Read-Eval-Print Loop that makes it the most suitable
language for the command-line applications.
Python provides many free library or module which helps to build the command-line apps. The
necessary IO libraries are used to read and write. It helps to parse argument and create console
help text out-of-the-box. There are also advance libraries that can develop independent console
apps.
4) Software Development
Python is useful for the software development process. It works as a support language and can be
used to build control and management, testing, etc.
This is the era of Artificial intelligence where the machine can perform the task the same as the
human. Python language is the most suitable language for Artificial intelligence or machine
learning. It consists of many scientific and mathematical libraries, which makes easy to solve
complex calculations.
Implementing machine learning algorithms require complex mathematical calculation. Python has
many libraries for scientific and numeric such as Numpy, Pandas, Scipy, Scikit-learn, etc. If you
have some basic knowledge of Python, you need to import libraries on the top of the code. Few
popular frameworks of machine libraries are given below.
• SciPy
[Type here]
• Scikit-learn
[Type here]
• NumPy
• Pandas
• Matplotlib
6) Business Applications
Business Applications differ from standard applications. E-commerce and ERP are an example
of a business application. This kind of application requires extensively, scalability and readability,
and Python provides all these features.
Oddo is an example of the all-in-one Python-based application which offers a range of business
applications. Python provides a Tryton platform which is used to develop the business application.
Python is flexible to perform multiple tasks and can be used to create multimedia applications.
Some multimedia applications which are made by using Python are TimPlayer, cplay, etc. The
few multimedia libraries are given below.
• Gstreamer
• Pyglet
• QT Phonon
8) 3D CAD Applications
The CAD (Computer-aided design) is used to design engineering related architecture. It is used
to develop the 3D representation of a part of a system. Python can create a 3D CAD application
by using the following functionalities.
• Fandango (Popular )
• CAMVOX
• HeeksCNC
• AnyCAD
• RCAM
9) Enterprise Applications
Python can be used to create applications that can be used within an Enterprise or an Organization.
Some real-time applications are OpenERP, Tryton, Picalo, etc.
Python contains many libraries that are used to work with the image. The image can be
manipulated according to our requirements. Some libraries of image processing are given below.
• OpenCV
[Type here]
• Pillow
• SimpleITK
The future of python
Python has huge user base that is constantly growing.it is the most preferred language of
companies ,such as Nokia,Google, and youtube,as well as NASA for its easy syntax.
It has bright future ahead of it supported by a huge community of OS developers.
Python is a high-speed dynamic language therefore it works well in applications like photo
development and has been embedded in programs such as GIMP and paint shop pro.
• Python provides us the feature to execute the Python statement one by one at the interactive
prompt.
• It is preferable in the case where we are concerned about the output of each line of our Python
program.
• To open the interactive mode, open the terminal (or command prompt) and type python.
• After writing the print statement, press the Enter key.
Step - 1: Open the Python interactive shell, and click "File" then choose "New", it will open a
new blank script in which we can write our code.
[Type here]
Step -2: Now, write the code and press "Ctrl+S" to save the file.
Step - 3: After saving the code, we can run it by clicking "Run" or "Run Module". It will display
the output to the shell.
Multi-line Statements
Multi-line statements are written into the notepad like an editor and saved it with .py extension. In
the following example, we have defined the execution of the multiple code lines using the Python
script.
Script: multiline.py
name = "Deepika"
age = "32"
print("My name is: ", name ) print("My branch is : ", branch) print("My age is: ", age)
Output:
My name is: Deepika My branch is : AI & ML My age is: 32
• 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.
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.
[Type here]
• Identifier name must not be similar to any keyword defined in the language.
• Identifier names are case sensitive; for example, my name, and MyName is not the same.
• Examples of valid identifiers: a123, _n, n_9, etc.
• Examples of invalid identifiers: 1a, n%4, n 9, etc.
Example:
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.
print(z)
Output:
50
50
[Type here]
50
Example:
a,b,c=5,10,15
10
15
Keywords:
And,assert,break,class,continue,def,del,elif,else,except,exec,finally,for,from,global,if,import,
in,is,lambda,not,or,pass,print,raise,return,try,while,with,yield.
Comments in python
Comments are non-executable statements in a program.they are just added to describe the
statements in the program code.
Program on comments:
# this is a comment
Print(“hello”)# to display hello
#program ends here
o/p
hello
Indentation:
Whitespace at the beginning of the line is called indentation. These whitespaces or
indentation is very important in python.in python indentation is used to associate and group
statements.
Program to show indentation errors.the level of indentation groups statements to form a
block of statements.this means that statements in a block must have the same indentation
level.
Age=21
Print(“you can vote”)#error-tab at the start of the line
[Type here]
• input( ) - Used for input operations.
When we use the print( ) function to display a message, the string can be enclosed
either in the single quotation or double quotation.
print(num1)
#Output : 10
In the above example, we have created a variable num1 with a value 10. The value of
the variable num1 is displayed using the print( ) function.
[Type here]
print('It is tuesday ')
output:
Good Morning! It is tuesday
Here,
Output formatting
Sometimes we would like to format our output to make it look attractive. This
can be done by using the str.format() method. For example,
• x=5
• y = 10
•
[Type here]
# This program adds two numbers
num1 = 1.5
num2 = 6.3
When input( ) function is used without a message, it simply prompts for the input
value. When the user enters the input value it reads the entered value as a string
and assigns it to the left-hand-side variable.
Example
number_1 = input()
print('The number you have entered is {number_1}')
When we run the above piece of code, in the output screen simply it waits for the
user input without displaying anything.
When input( ) function is used with a message, it prompts with a given message for
the input value. When the user enters the input value it reads the entered value as a
string and assigns it to the left-hand-side variable.
# using input() to take user input
[Type here]
num = input('Enter a number: ')
In the above example, we have used the input() function to take input from the
user and stored the user input in the num variable.
It is important to note that the entered value 10 is a string, not a number.
So, type(num) returns <class 'str'> .
To convert user input into a number we can use int() or float() functions as:
Num = int(input(enter anumber))
Here, the data type of the user input is converted from string to integer .
Always the input( ) function reads input value as string value only.
To read the value of any other data type, there is no input function in Python.
Explicitly we need to convert to the required data type using type casting.
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.
Ex:
a=5
Python interpreter will automatically interpret variabl
es 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.
Ex:
a=10
b="Hi Python" c = 10.5
[Type here]
Output:
<type 'int'>
<type 'str'>
<type 'float'>
Standard Datatypes:
• Python provides various standard data types that define the storage method on each of them.
• The data types defined in Python are given below.
• Numbers
• String
• list
• Tuple
• Dictionary
• In Python, there are four types of numbers that can be assigned to a variable given as follows
• Int (signed Integer object) : they are the negative or non-negative numbers with no decimal
point. There is no limit on an integer in python. However, the size of the integer is constrained by
the amount of the memory our system has.
• float (floating point numbers) : The float type is used to store the decimal point (floating point)
numbers.
• Complex (complex numbers): Complex numbers are of the form a+bj where a is the real part of
the number and bj is the imaginary part of the number. It is not as much used in the
programming.
Program:
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))
Output:
[Type here]
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 on strings.
• 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'.
Program:
print(s)
Output:
String
Program:
print (str1[0:2]) #printing first two character using slice operator print (str1[4]) #printing 4th
Output:
he o
[Type here]
hello STUDENTS hello STUDENTS
List
Program:
Output:
[2]
[1, 'hi']
Tuple
[Type here]
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.
Program:
Output:
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2) Traceback (most recent call last):
[Type here]
Dictionary
Program:
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:
Boolean
[Type here]
Program:
<class 'bool'>
<class 'bool'>
Set
Program:
print(set2)
print(set2)
[Type here]
set2.remove(2) print(set2) Output:
The operator can be defined as a symbol which is responsible for a particular operation between
two operands.
• Arithmetic operators
• Comparison operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Arithmetic Operators:
Arithmetic operators are used to perform arithmetic operations between two operands.
Operator Description
+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 => a+b = 30
It is used to subtract the second operand from the first operand. If the first
- (Subtraction) operand is less than the second operand, the value results negative. For
example, if a = 20, b = 10 => a - b = 10
It returns the quotient after dividing the first operand by the second operand.
/ (division)
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 = 20, b =10
(Multiplication) => a * b = 200
It returns the reminder after dividing the first operand by the second operand.
% (reminder)
For example, if a = 20, b = 10 => a%b = 0
It is an exponent operator represented as it calculates the first operand power to
** (Exponent)
the second operand.
// (Floor
It gives the floor value of the quotient produced by dividing the two operands.
division)
[Type here]
a = 10
b = 3
print("a + b =” ,a + b)
print("a - b =”,a - b)
print(“a * b = “,{a * b})
print(f"a / b = {a / b}")
print(f"a % b = {a % b}")
print(f"a ** b = {a ** b}")
print(f"a // b = {a // b}")
Comparison operators:
Comparison operators are used to comparing the value of the two operands and returns Boolean
true or false accordingly.
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 becomestrue.
>
< If the first operand is less than the second operand, then the condition becomes true.
a = 10
b = 3
print(a < b)
print(a <= b)
print(a > b)
print(a >= b)
print(a == b)
print(a != b)
[Type here]
Assignment Operators:
The assignment operators are used to assign the v+alue of the right expression to the left
operand.
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.
[Type here]
a = 10
b = 3
a += b
print(f"a += b => {a}")
a -= b
print(f"a -= b => {a}")
a *= b
print(f"a *= b => {a}")
a /= b
print(f"a /= b => {a}")
a %= b
print(f"a %= b => {a}")
a **= b
print(f"a **= b => {a}")
a //= b
print(f"a //= b => {a}")
Bitwise Operators
The bitwise operators perform bit by bit operation on the values of the two operands.
Example:
if a = 7
b=6
then, binary (a) = 0111 binary (b) = 0110 hence, a & b = 0110
a | b = 0111 a ^ b = 0001
~ a = 1000
Operator Description
& (binary
If both the bits are 1, then the result is 1. Otherwise, 0.
and)
The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will
| (binary or)
be 1.
[Type here]
^ (binary xor) The resulting bit will be 1 if both the bits are different; otherwise, the resulting bit
will be 0.
It calculates the negation of each bit of the operand, i.e., if the bit is 0, the resulting
~ (negation)
bit will be 1 and vice versa.
a = 10
b = 15
print(f"{bin(a)} & {bin(b)} = {bin(a & b)}")
print(f"{bin(a)} | {bin(b)} = {bin(a | b)}")
print(f"{bin(a)} ^ {bin(b)} = {bin(a ^ b)}")
print(f"~{bin(a)} = {bin(~a)}")
Logical Operators:
The logical operators are used primarily in the expression evaluation to make a decision.
Operator Description
If both the expression are true, then the condition will be true. If a and b are the two
and
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
[Type here]
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.
a = 10
b = 3
c = 20
print(a < b and a > c)
print(a < b or a > c)
print(not a > b)
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
It is evaluated to be true if the first operand is found in the second operand (list, tuple,
in
or dictionary).
It is evaluated to be true if the first operand is not found in the second operand (list,
not in
tuple, or dictionary).
list = [1, 4, 10, 40, 5]
a = 10
b = 3
print(a in list)
print(b in list)
print(a not in list)
print(b not in list)
print('s' in 'BSsmartclass')
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.
It is evaluated to be true if the reference present at both sides do not point to the same
is not
object.
[Type here]
Operator Precedence:
The precedence of the operators is essential to find out since it enables us to know which
operator should be evaluated first. The precedence table of the operators in Python is given
below.
Operator Description
The exponent operator is given priority over all the others used in the
**
expression.
~+- The negation, unary plus, and minus.
* / % // The multiplication, divide, modules, reminder, and floor division.
+- Binary plus, and minus
>> << Left shift. and right shift
& Binary and.
^| Binary xor, and or
Comparison operators (less than, less than equal to, greater than, greater then
<= < > >=
equal to).
<> == != Equality operators.
[Type here]
Built in functions in python: The built-in functions are those functions that are pre-defined
in Python.
Python abs()
The abs() function returns the absolute value of the given number. If the number is a
complex number, abs() returns its magnitude.
Example
number = -20
absolute_number = abs(number)
print(absolute_number)
# Output: 20
Python any()
The any() function returns True if any element of an iterable is True. If not, it
returns False.
Example
boolean_list = ['True', 'False', 'True']
print(result)
# Output: True
Python all()
The all() function returns True if all elements in the given iterable are true. If not, it
returns False.
Example
boolean_list = ['True', 'True', 'True']
print(result)
# Output: True
Python bin()
The bin() method converts a specified integer number to its binary representation and
returns it.
Example
number = 15
29
# convert 15 to its binary equivalent
print('The binary equivalent of 15 is', bin(number))
# Output: 1 is True
Python chr()
The chr() method converts an integer to its unicode character and returns it.
Example
print(chr(97))
# Output: a
print(chr(98))
# Output: b
Python len()
The len() function returns the number of items (length) in an object.
Example
languages = ['Python', 'Java', 'JavaScript']
print(length)
# Output: 3
30
UNIT-II
Control Statements:
• Control Statements are used to transfer the control from one part of the program to another
depending on a condition.
• These statements are also called as conditional statements.
Conditional Statements:
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.
31
Syntax:
if expression: statement
Program:
Output:
32
Syntax:
if condition:
#block of statements
else:
#another block of statements
Program:
if age>=18:
else:
Output:
Enter your age 90
You are eligible to vote
# write a program to enter any character,if the character is in lowercase then convert it into
uppercase and if it is an uppercase character,then convert it into lowercase.
33
Syntax:
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Program:
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
#program on calculator
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
if choice == '1':
print(num1, "+", num2, "=", num1+ num2)
min1 = 150001
max1 = 300000
rate1 = 0.10
min2 = 300001
max2 = 500000
rate2 = 0.20
min3 = 500001
rate3 = 0.30
A word on Indentation:
• 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.
Looping Statements:
• The programming languages provide various types of loops which are capable of repeating some
specific code several numbers of times.
• The looping simplifies the complex problems into the easy ones.
36
• 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.
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.
Syntax:
statement(s)
Program: Write a Python program to display characters of a string using for loop.
str='Hello'
for ch in str:
print(ch)
Output:
H
ello
Program: Write a program to print multiplication table of a given number
list = [1,2,3,4,5,6,7,8,9,10]
n = int(input[(“enter the number”)
for i in list:
c = n*i
print(c)
Output:
5
10
15
20
25
30
35
37
40
45
38
50
Program: Write a python program to print the sum of the given list.
list = [10,30,23,43,65,12]
sum = 0
for i in list:
sum = sum+i
print("The sum is:",sum)
Output:
The sum is: 183
Syntax:
range(start,stop,step size)
for i in range(10):
print(i)
Output:
0
1
2
3
4
5
6
7
8
9
Program: Python Program to print even number using step size in range().
n = int(input("Enter the number "))
39
for i in range(2,n,2):
40
print(i)
Output:
Enter the number 20 2
4
6
8
10
12
14
16
18
Nested Loop:
• 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.
Syntax:
for iterating_var1 in sequence: #outer loop
for iterating_var2 in sequence: #inner loop
#block of statements #Other statements
Program:
* *
***
print("\n")
3. Write a program to accept a number from a user and calculate the sum of all
numbers from 1 to a given number
s=0
n = int(input("Enter number "))
# run loop n times
# stop: n+1 (because range never include stop number in result)
for i in range(1, n + 1):
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.
• When we don't know the number of iterations then the while loop is most effective to use.
Syntax:
while expression: statements
• Here, the statements can be a single statement or a group of statements.
42
• The expression should be any valid Python expression resulting in true or false.
• The true is any non-zero value and false is 0.
Program:
count = 1
while (count < 3):
count = count+1
print("Hello Python")
Output:
Hello Python Hello Python Hello Python
statements statements
else: else:
statements statements
• The else suite will be always executed irrespective of the statements in the loop are executed or
not.
Program:
for i in range(5):
print("Yes")
else:
print("No")
Output:
43
Yes Yes Yes Yes Yes No
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.
• The break is commonly used in the cases where we need to break the loop for a given condition.
Program:
str = "python"
for i in str:
if i == 'o':
break
print(i)
Output:
pyth
Continue Statement:
• The continue statement skips the remaining lines of code inside the loop and start with the next
iteration.
Program:
str = "python"
for i in str:
if i == 'o':
continue
print(i);
44
Output:
pythn
Program:
i=0
while(i < 10):
i = i+1
if(i == 5):
continue print(i)
Output:
1
2
3
4
6
7
8
9
10
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.
• If we want to bypass any code pass statement can be used.
• The difference between the comments and pass is that, comments are entirely ignored by the
Python interpreter, where the pass statement is not ignored.
Program:
45
Program:
for i in [1,2,3,4,5]:
if(i==4):
pass
46
print("This is pass block",i)
print(i)
Output:
1
2
3
This is pass block 4 4
5
• We can create empty class or function using the pass statement. # Empty Function
def function_name(args):
pass
47
Count the total number of digits in a number
Write a program to count the total number of digits in a number using a while
loop.
# increment counter by 1
count = count + 1
Write a program to u
n=5
k=5
for i in range(0,n+1):
for j in range(k-i,0,-1):
print(j,end=' ')
print()
Examples:
• print(num)
49
• Fibonacci series
num1, num2 = 0, 1
print("Fibonacci sequence:")
# run loop 10 times
for i in range(10):
# print next number of a series
print(num1, end=" ")
# add last two numbers to get next number
res = num1 + num2
# update values
num1 = num2
num2 = res
num = 5
factorial = 1
if num < 0:
print("Factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
# run loop 5 times
for i in range(1, num + 1):
# multiply factorial by current number
factorial = factorial * i
print("The factorial of", num, "is", factorial)
50