PSPP UNIT-2
PSPP UNIT-2
PSPP UNIT-2
Python interpreter and interactive mode, debugging; values and types: int, float, boolean, string, and
list; variables, expressions, statements, tuple assignment, precedence of operators, comments;
Illustrative programs: exchange the values of two variables, circulate the values of n variables, distance
between two points.
Introduction to Python
Python is an open source, Object Oriented and high level programming language
It was developed by Guido van Rossum in early 1990s
It is a general purpose language
It offers strong support for integration with other language and tools, as it comes with extensive
standard libraries
Its easiest language to learn and use
Python Interpreter
Compiler Interpreter
Interactive mode
Script mode
Interactive mode
It is a command line shell which gives immediate feedback for each statement
Working in interactive mode is convenient for beginners and for testing small pieces of code
1
Example
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32
>>>
The first three lines are the information about python version number and operating system
The last line >>> is a prompt (chevron) that indicates that the interpreter is ready to enter code. If the
user types a line of code and hits enter the interpreter displays the result
Drawback:
We cannot save the statements and have to retype all the statements once again to re-run them
Script mode
In script mode, we type python program in a file and then use interpreter to execute the content of the
file.
Scripts are saved to disk for future use.
Python scripts have the extension .py, meaning that the filename ends with .py
Example Output
print(1)
x=2
print(x)
2
Interactive mode Script mode
A way of using the Python interpreter A way of using the Python interpreter
by typing commands and expressions to read and execute statements in a
at the prompt script
Can’t save and edit the code Can save and edit the code
We can see the results immediately We cannot see the results immediately
Data types
• Every value in python has a data type
• It is a set of values, and the allowable operations on those values
Integer Type
An integer type (int) represents signed whole numbers
It consists of positive and negative numbers including zero
To write an integer in octal (base 8), precede it with “0o”
Example
>>0o100
64
To write an integer in hexadecimal(base 16), precede it with “0x” or “0X”
Example: 0x77
To write an integer in binary(base 2), precede it with “0b” or “0B”
Example: 0b101
Floating Type
Complex Type
• Complex numbers are of form, x+yj, where x is the real part and y is the imaginary part.
3
Example
String Type
It can be created using Single Quotes, Double Quotes and triple quotes
Example
Indexing
String Operations
– Indexing
– Slicing
– Concatenation
– Repetitions
4
Example
str="Python Program!"
>>> print(str[0]) // Indexing
P
>>> print(str[7:10]) // Slicing
Pro
>>> print(str[7:])
Program!
>>> print(str*2) // Repetition
Python Program!Python Program!
>>> print(str+"Ver 3.4") // Concatenation
Python Program!Ver 3.4
Boolean Type
List Type
Operations on List
Indexing
Slicing
Concatenation
Repetitions
Updation, Insertion and Deletion
5
['god', 6.78, 9, 'god', 6.78, 9, 'god', 6.78, 9]
Concatenation print(List1+List2)
['python', 7.79, 101, 'hello', 'god', 6.78, 9]
Updating the List List1[2]=45
print(List1)
['python', 7.79, 45, 'hello']
Inserting an element List1.insert(2,"program")
print(List1)
['python', 7.79, 'program', 45, 'hello']
Removing an element List1.remove(45)
print(List1)
['python', 7.79, 'program', 'hello']
Tuple
• A tuple is a container which holds a series of comma- separated values (items or elements) between
parentheses
• Tuples are immutable
• It can hold a mix of data types ( int , float, string, list)
• Tuples are faster than lists
• Example:
tuple1 = (element1, element2, element 3…….element n)
tuple1 = (1, 2, 3, 4, 5)
tuple2 = (‘a’, ‘b’, ‘c’, ‘d’)
Altering the tuple data type leads to error. Following error occurs when user tries to do.
>>> t[1]=2
t[1]=2
Tuple Assignment
6
An assignment to all of the elements in a tuple using single assignment statement
The left side is a tuple of variables; the right side is a tuple of values.
Naturally, the number of variables on the left and the number of variables on the right have to be the
same
Example:
>>> T2 = (100,200,300,400)
Comments
Comments make the program easily understandable by the programmer and non-programmer who
are seeing the code
Comment statements are non-executable statements so they are ignored while program execution
They have no effect on the program results
Example:
# swap.py
Example
‘’’ This is a
multi-line comments’’’
7
Python Literals
a=1.4e200
b=2.1e200
c=a*b
print(c)
String Literals
Variables
Variable name must begin with only letter (a-z, A-Z) or underscore (_)
Keywords cannot be a variable
No special symbols allowed
No blank spaces are allowed between variable names
Variable names are case sensitive
Creating Variables
8
The assignment statement (=) assigns value to a variable
Syntax : Variable=expr
Examples:
>>> n=10
>>> name="Jaya"
>>> 7wonders="taj mahal"
Syntax Error: invalid syntax
>>> student_name="bala"
>>> a=b=c=10
Keywords
Example
import keyword
print(keyword.kwlist)
Statements
Statement is a unit of code that has an effect, like creating a variable or displaying a value
>>> n=7
>>> print(n)
9
Expressions
>>> 42
>>>42
>>>a=2
>>>a+3+2
>>>7
>>>z=("hi"+"friend")
>>>print(z)
>>>hifriend
Output
Operators in Python
Operators are the constructs which can manipulate the value of operands
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator
Types of operators
o Arithmetic Operators
10
o Comparison Operators
o Logical Operators
o Assignment Operator
o Membership Operator
o Identity Operator
o Bitwise Operator
Arithmetic Operators
They are used to perform mathematical operations like addition, subtraction, multiplication etc.
Example Program
11
Comparison Operators
Example Program
x=54
y=18
print('x>y is',x>y)
print('x<y is',x<y)
print('x==y is',x==y)
print('x!=y is',x!=y)
print('x>=y is',x>=y)
print('x<=y is',x<=y)
Output
Logical Operators
12
Operator Name Example Explanation
and Logical AND x and y True if both the operands are true
Example Program
x='true'
y='false'
print(' x and y is', x and y)
print('x or y is', x or y)
print('not x is', not x)
Output
Assignment Operators
Assignment operators are used in Python to assign values to variables. a = 5 is a simple assignment
operator that assigns the value 5 on the right to the variable a on the left.
Example Program
x=12
y=15
x+=y
print("x+=y:",x)
x-=y
13
print("x-=y:",x)
x*=y
print("x*=y:",x)
x/=y
print("x/=y:",x)
x%=y
print("x%=y:",x)
x**=y
print("x**=y",x)
x//=y
print("x//=y",x)
Output
x+=y: 27
x-=y: 12
x*=y: 180
x/=y: 12.0
x%=y: 12.0
x**=y 1.5407021574586368e+16
x//=y 1027134771639091.0
Membership Operators
Membership Operators are used to test whether a value or variable is found in a sequence (list, sting,
tuple, dictionary and set)
in and not in are two membership operators
Example Program
x="Python Program"
print('y' in x)
print('p' in x)
print('hello' not in x)
print('n' not in x)
Output
Identity Operators
Identity Operators compare the memory location of two objects
The two identity operators are is and is not
14
Example Program
x1 = 5
y 1= 5
x2 = 'Hello'
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)
Output:
Bitwise Operators
& Bitwise AND X&Y Both operands are true result is true
15
Operator Precedence
Operator Description
16
<> == != Equality operators
= %= /= //= -=
Assignment operators
+= *= **=
Modules
Module
Creating a Module [user defined]
Built-in modules
o Calendar
o Math
o Random
Randint
Using choice
Way to access the module
o Through import statement
o from…import
o import all names
Module
17
Example.py
def add(a,b):
result=a+b
return result
print(add(5,6))
Output:
11
Built-in Modules
Random
Math
Calendar and date-time
1. Random
Usage/Need:
If we want a computer to pick a random number in a given range we use random function
Random Functions
Randint
o If we want a random integer, we use the randint function
o randint accepts two parameters : lowest and highest number
Example
import random
print(random.randint(0,5))
The output will be either 1,2,3,4 or 5
Using Choice
o Helps to generate a random value from the sequence
o The choice function can often be used for choosing a random element from a list
Example
import random
mylist=[2,101,False]
print(random.choice(mylist))
2. Math
The math module provides access to mathematical constants and functions
18
Example
import math
print(math.pi)
print(math.e)
print(math.factorial(5))
print(math.sin(2))
print(math.cos(0.5))
print(math.sqrt(49))
Output
19
We can import a module using import statement and access the definitions inside it using dot operator
Example
import math
print(“the value of pi is”,math.pi)
from…..import statement
Syntax: from python_filename import function_name 1, function_name 2
Example
>>> from math import pi,e
>>> print(pi)
3.141592653589793
>>> print(e)
2.718281828459045
Functions
Functions are “ self-contained” modules of code that accomplish a specific task
STEPS
Function definition
Function Call
Defining Function
Syntax
Function Call
Syntax: function_name(arg1, arg2)
Flow of execution
20
The order in which statements are executed is called the flow of execution
Execution always begins at the first statement of the program
Statements are executed one at a time, in order, from top to bottom.
Function definitions do not alter the flow of execution of the program, but remember that statements inside
the function are not executed until the function is called.
Function Prototypes
Function with no arguments and no return values
In this type no argument is passed through the function call and no output is return to main function
The sub function will read the input values perform the operation and print the result in the same block
def sum():
x=int(input("Enter a value:"))
y=int(input("Enter b value:"))
z=x+y
print(z)
sum()
Arguments
• Arguments are the value(s) provided in function call/invoke statement
• List of arguments should be supplied in same way as parameters are listed.
• Example: my_add(x,y)
21
Argument Types
1. Required Arguments
o The number of arguments in the function call should match exactly with the function definition
def my_details(name,age):
print("Name:",name)
print("Age:",age)
return
my_details("george",45)
2. Keyword Arguments
o Arguments preceded with a variable name followed by a = sign
def my_details(name,age):
print("Name:",name)
print("Age:",age)
return
my_details(name="george",age=45)
3. Default arguments
o Assumes a default value if a value is not provided in the function call for that argument.
def my_details(name,age=40):
print("Name:",name)
print("Age:",age)
return
my_details(name="George")
Illustrative Problems
22
print(d)
Exchange the values of two variables without using Output
third variable
x=int(input("Enter the first number\n")) Enter the first number
y=int(input("Enter the second number\n")) 50
print("Values before swap are %d and %d ."%(x,y)) Enter the second number
x,y = y,x 10
print("Values after swap are %d and %d ."%(x,y)) Values before swap are 50 and 10.
Values after swap are 10 and 50.
Swap two numbers using third variable Output
x=int(input("Enter the first number\n")) Enter the first number
y=int(input("Enter the second number\n")) 50
print("Values before swap are %d and %d ."%(x,y)) Enter the second number
temp=x 10
x=y Values before swap are 50 and 10.
y=temp Values after swap are 10 and 50.
print("Values after swap are %d and %d ."%(x,y))
Sum of first ‘n’ even numbers using function Output
def sum(n): Enter the limit:10
i=0 10
sum=0 Sum of even numbers= 20
while i<n:
sum=sum+i
i=i+2
return sum
n=int(input("Enter the limit:"))
print(n)
result=sum(n)
print("Sum of even numbers=",result)
Leap Year Program Output
year=int(input("Enter a given year:")) Enter a given year:1994
if(((year%4==0)and(year%100!=0)) or (year%400==0)): The given year 1994 is not a Leap
print("The given year",year,"is a Leap Year") Year
else:
print("The given year",year,"is not a Leap Year")
Simple Interest Output
x=float(input("Enter the principal amount\n")) Enter the principal amount
y=float(input("Enter the rate of interest\n")) 10000
z=float(input("Enter the time period (in years)\n")) Enter the rate of interest
si=(x*y*z)/100 7
print("Simple Interest is %.2f"%si) Enter the time period (in years)
10
Simple Interest is 7000.00
Converting Fahrenheit to Centigrade Output
fh=float(input("Enter temperature in Fahrenheit:\n")) Enter temperature in Fahrenheit:
cl=(fh-32)/1.8 45
print("Temperature in Celsius: %.2f"%cl) Temperature in Celsius: 7.22
Employee Payroll Output
name=input("Enter name: ") Enter name: Ram
basic=float(input("\nEnter Basic Salary: ")) Enter Basic Salary: 23000
hra=float(input("\nEnter HRA: ")) Enter HRA: 9500
da=float(input("\nEnter D.A.: ")) Enter D.A.: 9500
pf=(12/100)*basic PAYROLL DETAILS:
23
gs=basic+hra+da+pf Name: Mr.Ram
print("\nPAYROLL DETAILS:") BASIC PAY: Rs.23000.00/-
print("Name: Mr.%s"%name) HRA: Rs.9500.00/-
print("BASIC PAY: Rs.%.2f"%basic,end="/-") DA: Rs.9500.00/-
print("\nHRA: Rs.%.2f"%hra,end="/-") PF: Rs.2760.00/-
print("\nDA: Rs.%.2f"%da,end="/-") ***GROSS SALARY: Rs.44760.00/-
print("\nPF: Rs.%.2f"%pf,end="/-") ***
print("\n***GROSS SALARY: Rs.%.2f/-***"%gs)
Menu Driven Calculator Using Functions Output
def addition(a,b): 3
return a+b 5
def subtraction(a,b): 1
return a-b 8
def multiplication(a,b):
return a*b
def division(a,b):
return a/b
def modulo(a,b):
return a%b
def average(a,b):
return (a+b)/2
def power(a,b):
return a**b
a=int(input())
b=int(input())
select=int(input())
if select==1:
print("%d"%addition(a,b))
if select==2:
print("%d"%subtraction(a,b))
if select==3:
print("%d"%multiplication(a,b))
if select==4:
print("%.2f"%division(a,b))
if select==5:
print("%d"%modulo(a,b))
if select==6:
print("%.2f"%average(a,b))
if select==7:
print("%d"%power(a,b))
Square root of a number Output
def squareroot(f): Enter a number
return f**0.5 12
f=int(input("Enter a number\n")) The square root of 12 is 3.46
print("The square root of",f,"is %.2f"%squareroot(f))
Checking Vowels Output
ch=input("Enter a Character : \n") Enter a Character :
if(ch=='a' or ch=='A' or ch=='e' or ch=='E' or ch=='i' or a
ch=='I' or ch=='o' or ch=='O' or ch=='u' or ch=='U'): a is vowel.
print(ch, "is vowel.")
else:
print(ch, "is consonant.")
Area of Circle using Functions Output
24
def calcarea(x): 2
area=3.14*x*x The area of the circle is 12.56
return area
a=float(input())
area=calcarea(a)
print("The area of the circle is %.2f"%area)
Prime Number using Functions Output
def findprime(n): 7
if (n==1): 1
return 0
elif(n==2):
return 1 The program returns 1 if the number is
else: prime else it returns zero.
for x in range(2,n): 7 is prime number it is returning 1.
if(n%x==0):
return 0
return 1
n=int(input())
print(findprime(n))
25