UNIT-I
INTRODUCTION TO PYTHON
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is
designed to be highly readable. It uses English keywords frequently where as other languages use
punctuation, and it has fewer syntactical constructions than other languages.
Python is Interpreted − Python is processed at runtime by the interpreter. You do not
need to compile your program before executing it. This is similar to PERL and PHP.
Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
Python is a Beginner's Language − Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple
text processing to WWW browsers to games.
Python was developed by Guido van Rossum in the late eighties and early nineties at the National
Research Institute for Mathematics and Computer Science in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk,
and Unix shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public
License (GPL).
Python is now maintained by a core development team at the institute, although Guido van Rossum still
holds a vital role in directing its progress.
Python Versions
Python programming language is being updated regularly with new features and supports. There are lots
of update in Python versions, started from 1994 to current release.
A list of Python versions with its released date is given below.
Python Version Released Date
Python 1.0 January 1994
Python 1.5 December 31, 1997
Python 1.6 September 5, 2000
Python 2.0 October 16, 2000
Python 2.1 April 17, 2001
Python 2.2 December 21, 2001
Python 2.3 July 29, 2003
Python 2.4 November 30, 2004
Python 2.5 September 19, 2006
Python 2.6 October 1, 2008
Python 2.7 July 3, 2010
Python 3.0 December 3, 2008
Python 3.1 June 27, 2009
Python 3.2 February 20, 2011
Python 3.3 September 29, 2012
Python 3.4 March 16, 2014
Python 3.5 September 13, 2015
Python 3.6 December 23, 2016
Python 3.7 June 27, 2018
Python 3.8 October 14, 2019
Python Features
Python provides many useful features which make it popular and valuable from the other programming
g 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.
Statements
A statement is an instruction that the Python interpreter can execute. We have seen two kinds of
statements: print and assignment.
When you type a statement on the command line, Python executes it and displays the result, if there is
one. The result of a print statement is a value. Assignment statements don't produce a result.
A script usually contains a sequence of statements. If there is more than one statement, the results
appear one at a time as the statements execute.
For example, the script
print 1
x=2
print x
produces the output
1
2
Again, the assignment statement produces no output.
CONTROL STATEMENTS
3.1 Decision making Statements :
• Decision-making is the anticipation of conditions occurring during the execution of a
program and specified actions taken according to the conditions.
• Python programming language assumes any non-zero and non-null values as TRUE,
and any zero or null values as FALSE value.
• Decision making Statements:
– if
– if else
– if-elif-else
– nested if
Simple if
• if statement contains a logical/boolean expression using which the data is compared
and a decision is made based on the result of the comparison.
Syntax
if expression:
statement(s)
statement-x
• If the boolean expression evaluates to TRUE, then the block of statement(s) inside the
if statement is executed.
• In Python, statements in a block are uniformly indented after the : symbol.
• If boolean expression evaluates to FALSE, then the first set of code after the end of
block is executed.
>>>if 5>3:
print("hai")
Output:
hai
3.1.2 if-else
• The if-else statement is the most common type of selection statement. It is also called
a two-way selection statement, because it directs the computer to make a choice
between two alternative courses of action
• Python syntax for the if-else statement:
if <condition>:
<sequence of statements–1>
else:
<sequence of statements–2>
The condition in the if-else statement must be a Boolean expression—that is, an expression
that evaluates to either true or false
Multi-Way if Statement(if-elif-else)
• The process of testing several conditions and responding accordingly can be described
in code by a multi-way selection statement.
• The syntax of the multi-way if statement is the following:
if <condition-1>:
<sequence of statements-1>
elif <condition-n>:
<sequence of statements-n>
else:
<default sequence of statements>
• The multi-way if statement considers each condition until one evaluates to True or
they all evaluate to False.
• When a condition evaluates to True, the corresponding action is performed and
control skips to the end of the entire selection statement.
• If no condition evaluates to True, then the action after the trailing else is performed.
Nested if -else
• Nested if-else statements means an if-else statement inside another if/else statement
or both.
• Syntax:
if <expression1>:
if <expression2>:
statement block1
else:
statement block2
else:
if <expression3>:
statement block3
else:
statement block4
Code
a=int(input("Enter 1st number:"))
b=int(input("Enter 2nd number:"))
c=int(input("Enter 3rd number:"))
if a>b:
if a>c:
print(a,"is biggest")
else:
print(c,"is biggest")
else:
if b>c:
print(b,"is biggest")
else:
print(c,"is biggest")
Output:
nestedif()
Enter 1st number:5
Enter 2nd number:2
Enter 3rd number:8
8 is biggest
LOOPING STATEMENTS
• In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. There may be a situation when you
need to execute a block of code several number of times.
• A loop statement allows us to execute a statement or group of statements multiple
times.
• Looping Statements supported by Python :
– for
– while
WHILE LOOP
• The while loop is also called an entry-control loop, because its condition is tested at
the top of the loop.
• This implies that the statements within the loop can execute zero or more times.
• Syntax:
while <condition>:
<sequence of statements>
Code :
i=1
while(i<=10):
print(i,end=" ")
i=i+1
Output:
1 2 3 4 5 6 7 8 9 10
for loop :
• The for statement in Python has the ability to iterate over the items of any
sequence, such as a list or a string.
• The basic form of for loop is
for <variable> in range(<lowerbound>,<upperbound+1)):
<statement-1>
.
.
<statement-n>
Examples:
>>>for i in “Surya”:
print(i,end=“,”)
output
S,u,r,y,a,
>>>for i in range(5,10):
print(i)
output
5
9
Nested Loops :
• Python programming language allows the use of one loop inside another loop. The
following section shows a few examples to illustrate the concept.
• Syntax for nested for loop:
for iterating_var in sequence:
for iterating_var in sequence:
statement(s) –block1
statement(s)- block2
• The syntax for a nested while loop statement in Python programming language is
as follows:
while expression:
while expression:
statement(s)-block1
statement(s)-block2
Examples:
>>>for i in range(1,4):
for j in range(1,4):
print(“*” ,end=‘ ‘)
print(“\r”)
Output:
***
***
***
Python loops
Example
Print i as long as i is less than 6:
i=1
while i < 6:
print(i)
i += 1
output
1
2
3
4
5
Example
Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
output
1
2
3
Example
Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
output
1
2
4
5
6
The else Statement
With the else statement we can run a block of code once when the condition no longer is true:
Example
Print a message once the condition is false:
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
output
1
2
3
4
5
i is no longer less than 6
# Python program to illustrate
# while loop
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
Output:
Hello Geek
Hello Geek
Hello Geek
FOR LOOPS
PGM TO PRINST 1 TO 10
For i in range(1,11):
Print(i)
output
1
2
3
4
5
6
7
8
9
10
Example
Using the start parameter:
for x in range(2, 6):
print(x)
OUTPUT
2
3
4
5
The range() function defaults to increment the sequence by 1, however it is possible to specify the
increment value by adding a third parameter: range(2, 30, 3):
Example
Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
OUTPUT
2
5
8
11
14
17
20
23
26
29
Else in For Loop
The else keyword in a for loop specifies a block of code to be executed when the loop is finished:
Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
OUTPUT
0
1
2
3
4
5
Finally finished!
Note: The else block will NOT be executed if the loop is stopped by a break statement.
Example
Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
OUTPUT
0
1
2
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
OUTPUT
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
Python Program to Find the Factorial of a Number
1. num = int(input("Enter a number: "))
2. factorial = 1
3. if num < 0:
4. print(" Factorial does not exist for negative numbers")
5. elif num == 0:
6. print("The factorial of 0 is 1")
7. else:
8. for i in range(1,num + 1):
9. factorial = factorial*i
10. print("The factorial of",num,"is",factorial)
Output:
Enter a number: 10
The factorial of 10 is 3628800
Python program to print all prime numbers between 1 to N
# Take input from user
upto = int(input("Find prime numbers upto : "))
print("\nAll prime numbers upto", upto, "are : ")
for num in range(2, upto + 1):
i=2
for i in range(2, num):
if(num % i == 0):
i = num
break;
# If the number is prime then print it.
if(i != num):
print(num, end=" ")
Output
Find prime numbers upto : 100
All prime numbers upto 100 are :
3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Python Program to Check Armstrong Number
num = int(input("Enter a number: "))
sum = 0
n1 = len(str(num))
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** n1
temp //= 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
Output
371 is an Armstrong number
Check Armstrong number (for 3 digits)
# Python program to check if the number is an Armstrong number or not
# take input from the user
num = int(input("Enter a number: "))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
# display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
Output 1
Enter a number: 663
663 is not an Armstrong number
Output 2
Enter a number: 407
407 is an Armstrong number
Check Armstrong number of n digits
num = 1634
# Changed num variable to string,
# and calculated the length (number of digits)
order = len(str(num))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
# display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
1634 is an Armstrong number
Python Program to Find Strong Number
Below is the code of the Python program to print the given number is a strong or not.
Example -
1. # Variable to store sum of the numbers
2. sum=0
3. # Ask user to enter the number
4. num=int(input("Enter a number:"))
5. # temporary variable store copy of the original number
6. temp=num
7. # Using while loop
8. while(num):
9. # intialize with 1
10. i=1
11. # fact variable with 1
12. fact=1
13. rem=num%10
14. while(i<=rem):
15. fact=fact*i # Find factorial of each number
16. i=i+1
17. sum=sum+fact
18. num=num//10
19. if(sum==temp):
20. print("Given number is a strong number")
21. else:
22. print("Given number is not a strong number")
Output:
Enter a number: 145
Given number is a strong number.
Strong Number in Python using For Loop
In this program to find a Strong number in Python, we have used a for loop.
number = int(input("Enter number: "))
s=0
temp = number
while(temp > 0):
fact = 1
rem = temp % 10
for i in range(1, rem + 1):
fact = fact * i
print("Factorial of %d = %d " %(rem, fact))
s = s +fact
temp = temp // 10
print("Sum of factorials of the number %d = %d " %(number,s))
if(s == number):
print("Strong Number")
else:
print("Not a strong number")
Output for the input values test-case-1:-
Enter number: 135
Factorial of 5 = 120
Factorial of 3 = 6
Factorial of 1 = 1
Sum of factorials of the number 135 = 127
Not a strong number.
Output for the input values test-case-2:-
Enter number: 145
Factorial of 5 = 120
Factorial of 4 = 24
Factorial of 1 = 1
Sum of factorials of the number 145 = 145
Strong Number.
# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Run Code
Output
How many terms? 7
Fibonacci sequence:
0
1
1
2
3
5
8
# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Run Code
Output
How many terms? 7
Fibonacci sequence:
0
1
1
2
3
5
8