Introduction to Python Programming
Introduction to Python Programming
INTRODUTION TO PYTHON
1.1 Introduction and overview
General-purpose Object Oriented Programming language.
High-level language
Developed in late 1980 by Guido van Rossum at National Research Institute for
Mathematics and Computer Science in the Netherlands.
It is derived from programming languages such as ABC, Modula 3, small talk, Algol- 68.
It is Open Source Scripting language.
It is Case-sensitive language (Difference between uppercase and lowercase letters).
One of the official languages at Google.
Python is a general purpose programming language that makes it applicable in almost all domains
of software development. Python as a whole can be used to develop any type of applications.
Here, we are providing some specific application areas where python can be applied.
Web Applications
Desktop GUI Applications
Software Development
Scientific and Numeric
Business Applications
Console Based Application
Audio or Video based Applications
Python 3.0 was released on December 3rd, 2008. It was designed to rectify certain flaws in the earlier
version. This version is not completely backward-compatible with previous versions. However, many of
its major features have since been back-ported to the Python 2.6.x and 2.7.x version series. Releases of
Python 3 include utilities to facilitate the automation of Python 2 code translation to Python 3.
Python 1.0 January 1994 Functional programming tools (lambda, map, filter and
reduce).
Support for complex numbers.
Functions with keyword arguments
Python 3.9 - Current October 2020 Dictionary Merge & Update Operators
Version New removeprefix() and removesuffix() string methods
Builtin Generic Types
Page 2
Python’s traditional runtime execution model: Source code you type is translated to byte code,
which is then run by the Python Virtual Machine (PVM). Your code is automatically compiled,
but then it is interpreted.
Example:
>>>6+3
Output: 9
Page 3
Fig: Interactive Mode
>>> 5
5
>>> print(5*7)
35
>>> "hello" * 2
'hellohello'
Note: >>> is a command the python interpreter uses to indicate that it is ready.
The interactive mode is better when a programmer deals with small pieces of code.
ii. Script Mode: In this mode source code is stored in a file with the .py extension and use
the interpreter to execute the contents of the file. To execute the script by the interpreter,
you have to tell the interpreter the name of the file.
Example:
if you have a file name [Link] , to run the script you have to follow the following steps:
Page 4
Step-3: Output will be displayed on python shell window.
Page 5
There are two types of comments in python:
i. Single line comment
ii. Multi-line comment
i. Single line comment: This type of comments start in a line and when a line ends, it is
automatically ends. Single line comment starts with # symbol.
Example: if a>b: # Relational operator compare two values
ii. Multi-Line comment: Multiline comments can be written in more than one lines. Triple
quoted ‘ ’ ’ or “ ” ”) multi-line comments may be used in python. It is also known as
docstring.
Example:
‘’’ This program will calculate the average of 10 values.
First find the sum of 10 values
and divide the sum by number of values
‘’’
Page 6
PYTHON
FUNDAMENTALS
All the keywords are in lowercase except 03 keywords (True, False, None).
Page 7
2. Identifier: The name given by the user to the entities like variable name, class-name,
function-name etc.
3. Literal: Literals are the constant value. Literals can be defined as a data that is given
in a variable or constant.
Literal
String Literal
Numeric Boolean Special
Collections
Page 8
B. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single as well as
double quotes for a String.
Eg:
"Aman" , '12345'
C. Boolean literal: A Boolean literal can have any of the two values: True or False.
None is used to specify to that field that is not created. It is also used for end of lists in
Python.
E. Literal Collections: Collections such as tuples, lists and Dictionary are used in Python.
Page 9
Operators:
The operator is a symbol that performs a specific operation between two operands, according
to one definition.
An operator performs the operation on operands.
Operators are divided into 7 categories in Python according to their type of operation.
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication, etc.
Page
10
Assignment Operators
Comparison Operators
These operators compare the values on either sides of them and decide the relation among
them. They are also called Relational operators.
Page
11
Logical Operators
Python logical operators are used to combile two or more conditions and check the
final result. There are following logical operators supported by Python language.
These operators compare the left and right operands and check if they are equal, the same object, and have the same
memory location.
Example :
number1 = 5
number2 = 5
number3 = 10
Page
12
Output :
True
True
These operators search for the value in a specified sequence and return True or False accordingly. If the value is found
in the given sequence, it gives the output as True; otherwise False. The not in operator returns true if the value specified
is not found in the given sequence. Let’s see an example:
Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. These operators
are used to compare binary numbers.
Example :
number1 = 4 # 0100 in binary
number2 = 3 # 0011 in binary
print("& operation- ", number1 & number2) # AND
print("| operation- ", number1 | number2) # OR
Page
13
print("^ operation- ", number1 ^ number2) # XOR
print("~ operation- ", ~number2) # negation
print("<< operation- ", number1 << 1) # shift left by 1 bit
print(">> operation- ", number1 >> 1) # shift right by 1bit
Output :
& operation- 0
| operation- 7
^ operation- 7
~ operation- -4
<< operation- 8
>> operation- 2
Statements
A line which has the instructions or expressions.
Expression:
An expression is a collection of values, variables, operators and function calls that can be
evaluated by python interpreters if the expression is valid.
Page
14
Operator Precedence
The Python interpreter executes operations of higher precedence operators first in any
given logical or arithmetic expression. Except for the exponent operator (**), all other
operators are executed from left to right.
Operators Meaning
() Parentheses
** Exponent
+, - Addition, Subtraction
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, Comparisons, Identity, Membership
not in operators
or Logical OR
Page
15
4. Separator or punctuator : , ; , ( ), { }, [ ]
Page
16
Multiple Statements on a Single Line:
The semicolon ( ; ) allows multiple statements on the single line given that neither statement
starts a new code block.
Example:-
x=5; print(“Value =” x)
Creating a variable:
Example:
x=5
y = “hello”
Variables do not need to be declared with any particular type and can even change type after
they have been set. It is known as dynamic Typing.
x = 4 # x is of type int
x = "python" # x is now of type str
print(x)
Page
17
Python allows assign a single value to multiple
variables. Example: x = y = z = 5
You can also assign multiple values to multiple variables. For example −
x , y , z = 4, 5, “python”
4 is assigned to x, 5 is assigned to y and string “python” assigned to variable z respectively.
x=12
y=14
x,y=y,x
print(x,y)
Now the result will be
14 12
Lvalue and Rvalue:
An expression has two values. Lvalue and Rvalue.
Lvalue: the LHS part of the expression
Rvalue: the RHS part of the expression
Python first evaluates the RHS expression and then assigns to LHS.
Example:
p, q, r= 5, 10, 7
q, r, p = p+1, q+2, r-1
print (p,q,r)
Now the result will be:
6 6 12
Page
18
OUTPUT using print( ) statement:
Syntax:
print(object, sep=<separator string >, end=<end-string>)
Page
19
If you want to know the type of variable, you can use type( ) function :
Syntax:
type (variable-name)
Example:
x=6
type(x)
The result will be:
<class ‘int’>
Page
20
Type Casting:
To convert one data type into another data type.
Example:
x = int(1) # x will be 1 y =
int(2.8) # y will be 2 z =
int("3") # z will be 3
float( ) - constructs a float number from an integer literal, a float literal or a string literal.
Example:
x = float(1) # x will be 1.0 y
= float(2.8) # y will be 2.8 z =
float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
str( ) - constructs a string from a wide variety of data types, including strings, integer
literals and float literals.
Example:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Page
21
DATA HANDLING
Data Types
Primitive Collection
Data Type Data Type
Number String
int
float
complex
Example:
w=1 # int
y = 2.8 # float
z = 1j # complex
Page
22
integer : There are two types of integers in python:
int
Boolean
x=1
y = 35656222554887711
z = -3255522
Boolean: It has two values: True and False. True has the value 1 and False has the
value 0.
Example:
>>>bool(0)
False
>>>bool(1)
True
>>>bool(‘ ‘)
False
>>>bool(-34)
True
>>>bool(34)
True
float : float or "floating point number" is a number, positive or negative, containing one
or more decimals. Float can also be scientific numbers with an "e" to indicate the power
of 10.
Example:
x = 1.10
y = 1.0
z = -35.59
a = 35e3
b = 12E4
c = -87.7e100
Page
23
complex : Complex numbers are written with a "j" as the imaginary part.
Example:
>>>x = 3+5j
>>>y = 2+4j
>>>z=x+y
>>>print(z)
5+9j
>>>[Link]
5.0
>>>[Link]
9.0
Real and imaginary part of a number can be accessed through the attributes real and imag.
Page
24
3.2 MUTABLE & IMMUTABLE Data Type:
Mutable Data Type:
These are changeable. In the same memory address, new value can be stored.
Example: List, Set, Dictionary
Immutable Data Type:
These are unchangeable. In the same memory address new value cannot be stored.
Example: integer, float, Boolean, string and tuple.
RESULT
OPERATOR NAME SYNTAX
(X=14,
Y=4)
+ Addition x+y 18
_ Subtraction x–y 10
* Multiplication x*y 56
// Division (floor) x // y 3
% Modulus x%y 2
Page
25
Example:
>>>x= -5
>>>x**2
>>> -25
RESULT
OPERATOR NAME SYNTAX
(IF X=16,
Y=42)
False
> Greater than x>y
True
< Less than x<y
False
== Equal to x == y
True
!= Not equal to x != y
False
>= Greater than or equal to x >= y
True
<= Less than or equal to x <= y
iii. Logical operators: Logical operators perform Logical AND, Logical OR and Logical
NOT operations.
Page
26
a. Relational expressions as operands:
X Y X and Y
False False False
False True False
True False False
True True True
X Y X or Y
False False False
False True True
True False True
True True True
Page
27
b. numbers or strings or lists as operands:
In an expression X or Y, if first operand has true value, then return first operand X as a
result, otherwise returns Y.
X Y X or Y
false false Y
false true Y
true false X
true true X
>>>0 or 0
0
>>>0 or 6
6
>>>‘a’ or ‘n’
’a’
iv. Bitwise operators: Bitwise operators acts on bits and performs bit by bit operation.
Page
28
Examples:
Let Outpu
a = 10
t: 0
b=4
14
print(a & b)
-11
print(a | b) 14
2
print(~a)
40
print(a ^ b)
print(a >> 2)
print(a << 2)
v. Assignment operators: Assignment operators are used to assign values to the variables.
OPERA
TOR DESCRIPTION SYNTAX
Page
29
Divide AND: Divide left operand with right operand and then a/=b
/=
assign to left operand a=a/b
Modulus AND: Takes modulus using left and right operands and a%=b
%=
assign result to left operand a=a%b
Divide(floor) AND: Divide left operand with right operand and a//=b
//=
then assign the value(floor) to left operand a=a//b
Exponent AND: Calculate exponent(raise power) value using a**=b
**=
operands and assign value to left operand a=a**b
Performs Bitwise AND on operands and assign value to a&=b
&=
left operand a=a&b
Performs Bitwise OR on operands and assign value to left a|=b
|=
operand a=a|b
Performs Bitwise xOR on operands and assign value to a^=b
^=
left operand a=a^b
Performs Bitwise right shift on operands and assign value to left a>>=b
>>=
operand a=a>>b
Performs Bitwise left shift on operands and assign value to left a <<=b a=
<<=
operand a << b
vi. Other Special operators: There are some special type of operators like-
a. Identity operators- is and is not are the identity operators both are used to check if
two values are located on the same part of the memory. Two variables that are equal
does not imply that they are identical.
is True if the operands are identical True if the operands are not identical
is not
Example:
Let
a1 = 3
b1 = 3
a2 = 'PythonProgramming'
b2 = 'PythonProgramming'
a3 = [1,2,3]
b3 = [1,2,3]
Page
30
print(a2 is b2) # Output is False, since lists are mutable.
print(a3 is b3)
Output:
False
True
False
Example:
>>>str1= “Hello”
>>>str2=input(“Enter a String :”)
Enter a String : Hello
>>>str1==str2 # compares values of string
True
>>>str1 is str2 # checks if two address refer to the same memory address
False
Example:
Let
x = 'Digital India'
y = {3:'a',4:'b'}
print('D' in x)
print('digital' not in x)
print('Digital' not in x)
print(3 in y)
print('b' in y)
Boolean expressions
A boolean expression is an expression that is either true or false. The following examples use the operator ==, which
compares two operands and produces True if they are equal and False otherwise:
>>> 5 == 5
True
>>> 5 == 6
False
Page
31
FLOW OF CONTROL
1. Conditional statements
2. Iterative statements.
3. Transfer statements
Decision making is about deciding the order of execution of statements based on certain conditions. Decision structures
evaluate multiple expressions which produce TRUE or FALSE as outcome.
In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the
program accordingly. Conditional statements give us this ability. The simplest form is the if statement:
Page
32
1. if statement: It is a simple if statement. When condition is true, then code which is associated
with if statement will execute.
Syntax of the if statement
if condition:
statement 1
statement 2
statement n
Example:
a=40
b=20
if a>b:
print(“a is greater than b”)
print('Next lines of code')
3. elif statement (Chained Conditionals): It is short form of else-if statement. If the previous conditions
were not true, then do this condition". It is also known as nested if statement.
Syntax:
if condition-1:
statement 1
elif condition-2:
statement 2
elif condition-3:
statement 3
...
else:
statement
Page
33
Example:
a=input(“Enter first number”)
b=input("Enter Second Number:")
if a>b:
print("a is greater")
elif a==b:
print("both numbers are equal")
else:
print("b is greater")
Nested conditionals
In Python, the nested if-else statement is an if statement inside another if-else statement. It is allowed in
Python to put any number of if statements in another if statement. One conditional can also be nested within
another. We could have written the three-branch example like this:
Syntax :
if conditon_outer:
if condition_inner:
statement of inner if
else:
statement of inner else:
statement ot outer if
else:
Outer else
statement outside if block
Example :
num1 = int(input('Enter first number '))
num2 = int(input('Enter second number '))
Page
34
Loop: Execute a set of statements repeatedly until a particular condition is satisfied.
while loop: With the while loop we can execute a set of statements as long as a condition is true. It
requires defining an indexing variable.
Example: To print table of number 2
i=2
while i<=20:
print(i)
i+=2
1. for loop : The for loop iterate over a given sequence (it may be list, tuple or string).
Note: The for loop does not require an indexing variable to set beforehand, as the for command
itself allows for this.
primes = [2, 3, 5, 7]
for x in primes:
print(x)
Page
35
The range( ) function:
it generates a list of numbers, which is generally used to iterate over with for loop.
range( ) function uses three types of parameters, which are:
a. range(stop)
b. range(start, stop)
Note:
Example:
for x in range(4):
print(x)
Output:
0
1
2
3
b. range(start, stop): It starts from the start value and up to stop, but not including
stop value.
Example:
Page
36
Output:
2
3
4
5
c. range(start, stop, step): Third parameter specifies to increment or decrement the value by
adding or subtracting the value.
Example:
print(x)
Output:
3
5
7
Page
37
JUMP or TRANSFER STATEMENTS:
There are two jump statements in python:
1. break
2. continue
1. break statement : With the break statement we can stop the loop even if it is true.
Example:
in while loop in for loop
i = 1 languages = ["java", "python",
while i < "c++"] for x in languages:
6: if x ==
print(i) "python":
if i == break
3: print(x)
break
i += 1
Output: Output:
1 java
2
3
Note: If the break statement appears in a nested loop, then it will terminate the very loop it is
in i.e. if the break statement is inside the inner loop then it will terminate the inner loop only
and the outer loop will continue as it is.
2. continue statement : With the continue statement we can stop the current iteration, and
continue with the next iteration.
Example:
in while loop in for loop
i = 0 languages = ["java", "python",
while i < "c++"] for x in languages:
6: i += 1 if x ==
if i == "python":
3: continue
continu print(x)
e
print(i)
Output: Output
1 : java
2 c++
4
5
6
Page
38
Loop else statement:
The else statement of a python loop executes when the loop terminates normally. The else
statement of the loop will not execute when the break statement terminates the loop.
The else clause of a loop appears at the same indentation as that of the loop keyword while or
for.
Syntax:
for loop while loop
Nested Loop :
A loop inside another loop is known as nested loop.
Syntax:
for <variable-name> in <sequence>:
for <variable-name> in <sequence>:
statement(s)
statement(s)
Example:
for i in range(1,4):
for j in range(1,i):
print("*", end=" ")
print(" ")
Page
39
Programs related to Conditional, looping and jumping statements
1. Write a program to check a number whether it is even or odd.
num=int(input("Enter the number: ")) if
num%2==0:
print(num, " is even number")
else:
print(num, " is odd number")
Page
40
5. Write a program to check a number whether it is palindrome or not.
num=int(input("Enter a number : "))
n=num
res=0
while num>0:
rem=num%10
res=rem+res*10
num=num//10
if res==n:
print("Number is Palindrome") else:
print("Number is not Palindrome")
Page
41
sum=sum+i
Page
42
if num==sum:
print(num, "is perfect number")
else:
print(num, "is not perfect number")
In python, we have an in-built exit( ) function which is used to exit a python program. When it
encounters the exit( ) function in the system, it terminates the execution of the program completely.
Example :
After writing the above code (python exit() function), Ones you will print “ val ” then the
output will appear as a “ 0 1 2 “. Here, if the value of “val” becomes “3” then the program is forced
to exit, and it will print the exit message too.
Page
43
FUNCTIONS IN
PYTHON
Definition: Functions are the subprograms that perform specific task. Functions are the
small modules.
Types of Functions:
There are two types of functions in python:
Built in functions
1. Library Functions: These functions are already built in the python library.
2. Functions defined in modules: These functions defined in particular modules. When you want
to use these functions in program, you have to import the corresponding module of that function.
3. User Defined Functions: The functions those are defined by the user are called user defined
functions.
Page
44
To work with the functions of math module, we must import math module in program.
import math
S. No. Function Description Example
1 sqrt( ) Returns the square root of a number >>>[Link](49)
7.0
2 ceil( ) Returns the upper integer >>>[Link](81.3)
82
3 floor( ) Returns the lower integer >>>[Link](81.3)
81
4 pow( ) Calculate the power of a number >>>[Link](2,3)
8.0
5 fabs( ) Returns the absolute value of a number >>>[Link](-5.6)
5.6
6 exp( ) Returns the e raised to the power i.e. e3 >>>[Link](3)
20.085536923187668
Example:
def display(name):
1. Formal Parameter: Formal parameters are written in the function prototype and function header of the
definition. Formal parameters are local variables which are assigned values from the arguments when the
function is called.
2. Actual Parameter: When a function is called, the values that are passed in the call are called actual
parameters. At the time of the call each actual parameter is assigned to the corresponding formal parameter in
the function definition.
Example :
def ADD(x, y): #Defining a function and x and y are formal parameters
z=x+y
print("Sum = ", z)
a=float(input("Enter first number: " ))
b=float(input("Enter second number: " ))
ADD(a,b) #Calling the function by passing actual parameters
In the above example, x and y are formal parameters. a and b are actual parameters.
Calling the function:
Once we have defined a function, we can call it from another function, program or even the Python prompt. To
call a function we simply type the function name with appropriate parameters.
Syntax:
function-name(parameter)
Example:
ADD(10,20)
OUTPUT:
Sum = 30.0
Page
46
How function works?
def functionName(parameter):
… .. …
… .. …
… .. …
… .. …
functionName(parameter)
… .. …
… .. …
OUTPUT:
Page
47
(7, 7, 11)
Example-3: Storing the returned values separately:
def sum(a,b,c):
return a+5, b+4, c+7
s1, s2, s3=sum(2, 3, 4) # storing the values separately
print(s1, s2, s3)
OUTPUT:
7 7 11
b. Function not returning any value (void function) : The function that performs some operationsbut
does not return any value, called void function.
def message():
print("Hello")
m=message()
print(m)
OUTPUT:
Hello
None
Scope of a variable is the portion of a program where the variable is recognized. Parameters and variables
defined inside a function is not visible from outside. Hence, they have a local scope.
1. Local Scope
2. Global Scope
1. Local Scope: Variable used inside the function. It can not be accessed outside the function. In this scope,
The lifetime of variables inside a function is as long as the function executes. They are destroyed once we
return from the function. Hence, a function does not remember the value of a variable from its previous calls.
2. Global Scope: Variable can be accessed outside the function. In this scope, Lifetime of a variable is the
period throughout which the variable exits in the memory.
Page
48
Example:
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
OUTPUT:
This is because the variable x inside the function is different (local to the function) from the one outside.
Although they have same names, they are two different variables with different scope.
On the other hand, variables outside of the function are visible from inside. They have a global
scope.
We can read these values from inside the function but cannot change (write) them. In order to modify the value
of variables outside the function, they must be declared as global variables using the keyword global.
RECURSION:
Definition: A function calls itself, is called recursion.
OUTPUT:
enter the number: 5
The factorial of 5 is 120
OUTPUT:
How many terms you want to display: 8 0 1
1 2 3 5 8 13
Page
50
lambda Function:
lambda keyword, is used to create anonymous function which doesn’t have any name.
While normal functions are defined using the def keyword, in Python anonymous functions are defined using the
lambda keyword.
Syntax:
Lambda
lambdafunctions can have
arguments: any number of arguments but only one expression. The expression is evaluated and
expression
returned. Lambda functions can be used wherever function objects are required.
Example:
value = lambda x: x * 4
print(value(6))
Output:
24
In the above program, lambda x: x * 4 is the lambda function. Here x is the argument and x * 4 is the
expression that gets evaluated and returned.
2!
Solution:
def fact(x):
j=1 res=1
while j<=x:
res=res*j
j=j+1
return res
Page
51
n=int(input("enter the number : "))
i=1
sum=1
while i<=n:
f=fact(i)
sum=sum+1/f
i+=1
print(sum)
Page 52
Page 53