S11BLH21 Unit3Notes
S11BLH21 Unit3Notes
inpython python
SCHOOL OF COMPUTING
1
S11BLH21- Programming in python
inpython python
INTRODUCTION
History of Python- Introduction to the IDLE interpreter (shell) – Data Types - Built-in function
- Conditional statements - Iterative statements- Input/output Functions- Python database
communication – Data analysis visualization using python
1. Program
a. About Python
2
S11BLH21- Programming in python
inpython python
It is very flexible with the console program, Graphical User Interface (GUI)
applications, Web related programs etc.
3
S11BLH21- Programming in python
inpython python
Fig 2 indentation
It is a command line shell which gives immediate output for each statement,
while keeping previously fed statements in active memory. This mode is used
when a user wishes to run one single line or small block of code. It runs very
quickly and gives instant output. A sample code is executed using interactive
mode as below.
thon
5
S11BLH21- Programming in python
inpython python
The symbol “>>>” in the above screen indicates that the Python environment
is in interactive mode.
ii) From the start menu select Python (As shown below)
6
S11BLH21- Programming in python
inpython python
When the programmer wishes to use more than one line of code or a block of
code, script mode is preferred. The Script mode works the following way:
ii) After clicking on the menu “IDLE (Python 3.7 32- bit)”
, a new window with the text Python 3.7.2 Shell will be opened
as shown below:
7
S11BLH21- Programming in python
inpython python
iii) Select File → New, to open editor. Type the complete program.
iv) Select File again; Choose Save.
8
S11BLH21- Programming in python
inpython python
VARIABLES:
9
S11BLH21- Programming in python
inpython python
10
S11BLH21- Programming in python
inpython python
In the above three variables x,y,z is assigned with same value 25.
11
S11BLH21- Programming in python
inpython python
Expression:
12
S11BLH21- Programming in python
inpython python
Fig 14 expression
Fig 15 expression
Invalid Expression:
Always values should be assigned in the right hand side of the variable, but in
the below example ,the value is given in the left hand side of the variable, which
is an invalid syntax for expression.
13
S11BLH21- Programming in python
inpython python
Data Types:
A Data type indicates which type of value a variable has in a program. However
a python variables can store data of any data type but it is necessary to identify
the different types of data they contain to avoid errors during execution of
program. The most common data types used in python are str(string),
int(integer) and float (floating-point).
Float: Values that use decimal point and therefore may have fractional point
E.g.: 3.415, -5.15
By default when a user gives input it will be stored as string. But strings cannot
be used for performing arithmetic operations. For example while attempting to
perform arithmetic operation add on string values it just
14
S11BLH21- Programming in python
inpython python
Fortunately python have an option of converting one date type into another data
type (Called as “Casting”) using build in functions in python. The build function
int() converts the string into integer before performing operation to give the
right answer. (As in the below Program)
i) List
The List is an ordered sequence of data items. It is one of the flexible and very
frequently used data type in Python. All the items in a list are not necessary to
be of the same data type.
Declaring a list is straight forward methods. Items in the list are just separated
by commas and enclosed within brackets [ ].
ii) Tuple
Tuple is also an ordered sequence of items of different data types like list. But,
in a list data can be modified even after creation of the list whereas Tuples are
immutable and cannot be modified after creation.
The advantages of tuples is to write-protect data and are usually very fast when
compared to lists as a tuple cannot be changed dynamically.
16
S11BLH21- Programming in python
inpython python
The elements of the tuples are separated by commas and are enclosed inside
open and closed brackets.
Table 2 Tuple
List Tuple
>>> list1[12,45,27] >>> t1 = (12,45,27)
>>> list1[1] = 55 >>> t1[1] = 55
>>> print(list1) >>> Generates Error Message#
Because Tuples are immutable
>>> [12,55,27]
i) Set
The Set is an unordered collection of unique data items.Items in a set are not
ordered, separated by comma and enclosed inside { } braces. Sets are helpful
inperforming operations like union and intersection. However, indexing is not
done because sets are unordered.
Table 3 Set
List Set
>>> L1 = [1,20,25] >>> S1= {1,20,25,25}
>>> print(L1[1]) >>> print(S1)
>>> 20 >>> {1,20,25}
>>> print(S1[1])
>>>Error , Set object does not supportindexing.
17
S11BLH21- Programming in python
inpython python
List Vs Set
ii) Dictionary
In Python, dictionaries are defined within braces {} with each item being apair
in the form key:value. Key and value can be of any type.
>>> d1={1:'value','key':2}
>>> type(d)
18
S11BLH21- Programming in python
inpython python
Simple Functions
Function Description Output
abs() Return the absolute value of a >>> a = -10
number. The argument may be >>> print(abs(a))
an floating point number or a >>> 10
integer.
max() Returns the largest number from >>> max(12,20,30)
the list of numbers >>> 30
min() Returns the smallest number >>> min(12,20,30)
from the list of numbers >>> 12
pow() Returns the power of the given >>> pow(5,2)
number >>>25
round() It rounds off the number to the # E.g. 1:
nearest integer. >> round(4.5)
20
S11BLH21- Programming in python
inpython python
>> 5
# Eg 2
>> round(4.567,2)
>> 4.57
Mathematical Functions (Using math module)
ceil(x) It rounds x up to its nearest >>math.ceil(2.3)
integer and returns that integer >> 3
>>math.ceil(-3.3)
>> -3
floor(x) It rounds x down to its nearest >>math.floor(3.2)
integer and returns that integer >> 3
>>math.floor(-3.4)
>> -4
Function Description Example
cos(x) Returns the cosine of x , where >> math.cos(3.14159/2)
x represents angle in radians >> 0
>> math.cos(3.14159)
>> -1
sin(x) Returns the sine of x, where x >> math.sin(3.14159/2)
represents angle in radians >> 1
>> math.sin(3.14159)
>> 0
exp(x) Returns the exponential of x to >> math.exp(1)
the base ‘e’. i.e. ex >> 2.71828
log(x) Returns the logarithm of x for >>> math.log(2.71828)
the base e (2.71828) >>> 1
import math
Conditional Statements
C Program Python
22
S11BLH21- Programming in python
inpython python
x = 500 x = 500
y = 200 y = 200
if (x > y) if x > y:
{ print("x is greater than y")
printf("x is greater than y") elif x == y:
} print("x and y are equal")
else if(x == y) else:
{ print("x is less than y")
printf("x and y are equal")
}
else
{ Indentation (At least one White Space
printf("x is less than y") instead of curly bracket)
}
x = 500
y = 200
if x > y:
print("x is greater than y")
If statement :
23
S11BLH21- Programming in python
inpython python
The ‘if’ statement is written using “if” keyword, followed by a condition.If the
condition is true the block will be executed. Otherwise, the control will be
transferred to the firststatement after the block.
Syntax:
if<Boolean>:
<block>
In this statement, the order of execution is purely based on the evaluation of
boolean expression.
Example:
x = 200
y = 100
if x > y:
print("X is greater than Y")
print(“End”)
Output :
X is greater than Y
End
In the above the value of x is greater than y , hence it executed the print
statement whereas in the below example x is not greater than y hence it is not
24
S11BLH21- Programming in python
inpython python
x = 100
y = 200
if x > y:
print("X is greater than Y")
print(“End”)
Output :
End
Elif
The elif keyword is useful for checking another condition when one condition
is false.
Example
mark = 55
if (mark >=75):
print("FIRST CLASS")
25
S11BLH21- Programming in python
inpython python
print("PASS")
Output :
In the above the example, the first condition (mark >=75) is false then the
control is transferred to the next condition (mark >=50), Thus, the keyword elif
will be helpful for having more than one condition.
Else
The else keyword will be used as a default condition. i.e. When there are many
conditions, whentheif-condition is not trueand all elif-conditionsare also not
true, then else part will be executed..
Example
26
S11BLH21- Programming in python
inpython python
mark = 10
27
Fig 21 else keyword
Iterative Statements
Sometimes certain section of the code (block) may need tobe repeated again
and again as long as certain condition remains true. In order to achieve this, the
iterativestatements are used.The number of times the block needs to be repeated
is controlled by the test condition used in that statement. This type of
statement is also called as the “Looping Statement”. Looping statements add a
surprising amount of new power to the program.
Suppose the programmer wishes to display the string “Sathyabama !...” 150
times. For this,one can use the print command 150 times.
30
150 times
print(“Sathyabama
!...”)
print(“Sathyabama
!...”)
…..
…..
The above method is somewhat difficult and laborious. The same result can
be achieved by a loop using just two lines of code.(As below)
for count in
range(1,150) :
print (“Sathyabama
Types of looping statements
1) for loop
2) while loop
31
Flow Chart:
# Sum.py
total = 0
n = int (input ("Enter a Positive Number"))
for i in range(1,n+1):
total = total + i
print ("The Sum is ", total)
Note:Why (n+1)? Check in table given below.
32
Output:
In the above program, the statement total = total + i is repeated again and again
‘n’ times. The number of execution count is controlled by the variable ‘i’. The
range value is specified earlier before it starts executing the body of loop. The
initial value for the variable i is 1 and final value depends on ‘n’. You may also
specify any constant value.
The range() function can be called in three different ways based on the number
of parameters. All parameter values must be integers.
Table 7 range()
Type Example Explanation
33
range(end) for i in range(5): This is begins at 0.Increments
print(i) by 1. End just before the
value of end parameter.
Output :
0,1,2,3,4
range(begin,end) for i in range(2,5): Starts at begin, End before
print(i) end value, Increment by 1
Output :
2,3,4
range(begin,end,step) for i in range(2,7,2) Starts at begin, End before
print(i) end value, increment by
step value
Output :
2,4,6
# harmonic.py
total = 0
for i in range(1,n+1):
total+= 1/i
Example:
factorial = 1
if n < 0:
elif n == 0:
else:
35
for i in range(1,n + 1):
factorial = factorial*i
print("The factorial of" ,n, "is", factorial)
Output:
Fig 25factorial
The while loop allows the program to repeat the body of a loop, any number
of times, when some condition is true.The drawback of while loopis that, if
the condition not proper it may lead to infinite looping. So the user has to
carefully choose the condition in such a way that it will terminate at a
particular stage.
36
Flow Chart:
Syntax:
while (condition):
37
In this type of loop, The executionof the loopbody is purely based on the output
of the given condition.As long as the condition is TRUE or in other words until
the condition becomes FALSE the program will repeat the bodyof loop.
Table 8 Example
38
n2 = 1
count = 0
# count -- To check number of terms
if n <= 0: # To check whether valid number of terms
print ("Enter a positive integer")
elif n == 1:
print("Fibonacci sequence up to",n,":")
print(n2)
else:
print("Fibonacci sequence of ",n, “ terms :” )
while count < n:
print(n1,end=' , ')
nth = n1 + n2
n1 = n2
n2 = nth
count = count + 1
Programmer often has a need to interact with users, either to get data or to
provide some sort of result.
For Example: In a program to add two numbers, first the program needs to have
an input of two numbers ( The numbers which they prefer to add) and after
processing, the output should be displayed. So to get the input of two
39
numbers, the program need to have an Input Statement and in order to display
the result i.e. the sum of two numbers, it needs to have an Output Statement.
Input Statement: Helpful to take input from the user through input
devices like keyboard.In Python, the standard input function is ‘input()’
input()
Example:
The above statement will wait till the user, enters the input value.
Output:
Enter a number:
>>>num
Output Statement:
40
The output statement is used to display the output in the standard output
devices like monitor (screen).The standard output function “print()” is
used.
Syntax:
print(‘prompt’)
Example 1:
Output:
Example 2:
X=5
Output:
The value of X is 5
Example 3:
print(1,2,3,4)
41
Output: 1 2 3 4
Example 4:
print(100,200,300,4000,sep='*')
Output:
100*200*300*4000
Example 5:
print(1,2,3,4,sep='#',end='&')
Output:
1#2#3#4&
Output formatting
>>>x = 5; y = 10
>>>print('The value of x is {} and y is {}'.format(x,y))
The value of x is5and y is10
42
Output
I love
bread
and
butterI
love
butter
and
bread
43