Unit 2
Unit 2
CHAPTER 2
Python interpreter and interactive mode; values and types: int, float, boolean, string, and list;
variables, expressions, statements, tuple assignment, precedence of operators, comments;
modules and functions, function definition and use, flow of execution, parameters and
arguments; Illustrative programs: exchange the values of two variables, circulate the values of n
variables, distance between two points
1
Problem Solving and Python Programming 2020
2
Problem Solving and Python Programming 2020
Source code
Output
Python
data
Interpreter
Input data
3
Problem Solving and Python Programming 2020
4
Problem Solving and Python Programming 2020
5
Problem Solving and Python Programming 2020
Data types
1. Complex 1. Strings
2. Integer
3. Floating 2. Tuples Dictionary
point 3. Lists
4. Boolean
Fig 2.3: List of data types in Python
Integer (type int)
An integer data type represents the whole numbers. It represents positive and negative
numbers. Integer data type have unlimited size in Python.
Example: -3, 2 etc
Types of integer data type:
i) Regular integer
ii) Binary literals (base 2)
iii) Octal literals (base 8)
iv) Hexa decimal literals (base 16)
6
Problem Solving and Python Programming 2020
i) Regular integer
They are normal integers.
Example:
>>>a=9293
>>>b= -136
ii) Binary literals (base 2)
A binary literal is of the form zero followed by an uppercase B or lowercase b. The
literals are 0 and 1.
Example:
>>>bin=0b1111
>>>print(bin)
Output:
15
iii) Octal literals (base 8)
An octal literal is a number prefixed with zero followed by either uppercase O or lower
case o. The literals are 0 to 7.
Example:
>>>oct=0O24
>>>print(oct)
Output:
20
iv) Hexa decimal literals (base 16)
A hexa decimal literal is prefixed by 0(zero) followed by an upper case X or a lower case
x. The literals are 0 to9, [a-f/A-F].
Example:
>>>hex=0x9A
>>>print(hex)
Output:
154
7
Problem Solving and Python Programming 2020
8
Problem Solving and Python Programming 2020
>>>X+Y
+ Concatenation-Adds values of 2 strings
python program
>>>x[0:3]
[] Slice-Gives the character from the given range.
pyt
>>>x[1:2]
[:] Range slice-Give the characters from the given range.
y
9
Problem Solving and Python Programming 2020
>>>print str[0:3]
Hel
>>>print str[5:]
Python
>>>print str*2
HelloPython HelloPython
>>>print str+”welcome”
HelloPython welcome
Lists
List data type contains elements of various data types. Values in a list are called elements
or items of list. The list is enclosed by square brackets [ ], where items are separated by commas.
List values can be accessed using slice operator ([] or [:]) .The index 0 represents beginning of
the list and -1 represents ending of the list.
list[0] represents beginning of list.
list[-1] represents ending of list.
Syntax:
listname= [value1,value2,…value n]
Example:
>>>mylist = [10, 10.5, ‘programming’]
Example Program:
>>>mylist= ()
>>>mylist=[‘python’,10,10.5,’program’]
>>>print mylist
[‘python’,10,10.5,’program’]
>>>print mylist[1:3]
[10, 10.5]
>>>print mylist[2:]
[10.5,’program’]
>>>print mylist*2
[‘python’,10,10.5,’program’,’python’,10,10.5,’program’]
10
Problem Solving and Python Programming 2020
>>>print mylist[-1]
[‘program’]
VARIABLES
Variable is a name that is assigned to a value. The value can be changed during execution
of a program. While creating a variable, memory space is reserved in memory. Based on the data
type of a variable, the interpreter allocates memory.
Syntax: variable name=value
Example: price=20
Rules for naming variables
Variable name can be any length.
They can contain both letters and numbers. But they cannot begin with numbers.
Both upper case and lower case letters are used.
Variable names are case sensitive.
Example: midname, midName, MidName are different variables.
Variable name cannot be any one of the keywords.
Assigning values to variables
The equal (=) sign is used to assign the values to variables.
Left of = operator is the name of the variable.
Right of = operator is the value of variable.
Example:
>>>X=5
>>>name=”Python”
>>>print X
5
>>>print name
Python
In the above program X and name are variables. The value of X is 5 and the value of name is
Python.
11
Problem Solving and Python Programming 2020
EXPRESSIONS
Expression is a combination of values, variables, operators and operands. A value itself is
considered as an expression.
Example:
17 #expression
x #expression
x+17 #expression
Expression consists of combination of operators and operands.
Example:
5+ (8*k) #expression
The above expression consists of 2 sub expressions. That is 5 and (8*k).Here sub expression
(8*k) is evaluated first.
Evaluation of expressions:
When expression is typed at the prompt, the interpreter evaluates it, and finds the value of
expression.
Program:
>>>12+8 #expression
20
>>>n=100 #expression
>>>print(n) #expression
100
>>>100 #expression
100
STATEMENTS (or) I/O STATEMENTS
Statement is a section of code (or) instruction that represents a command (or) action.
Types of statements
i) Assignment statements
ii) Simultaneous assignment statements
iii) Input statements
iv) Print statements
12
Problem Solving and Python Programming 2020
i)Assignment statements
Assignment statements assigns right of = symbol to left of = symbol.
Example:
>>>Name=’CSE’
>>>age=100
>>>Name
CSE
>>>age
100
ii) Simultaneous assignment statements
Simultaneous assignment statement is used to assign more number of values to more
variables simultaneously.
Example:
>>>x,y=10,20
>>>x
10
>>>y
20
>>>sum, diff=x+y, y-x
>>>sum
30
>>>diff
10
14
Problem Solving and Python Programming 2020
Here left side is a tuple of variable. The right side is a tuple of expression.
Working of tuple assignment
i) The first variable in the tuple of left side is assigned to first expression in tuple of right side.
ii) Similarly, the second variable in the tuple of left side is assigned to second expression in
tuple of right side. Number of variables on left side and the number of expressions on the right
side must be same.
Example: Program on tuple assignment
>>>#empty tuple
>>>mytuple=( )
>>>mytuple
()
>>>#tuples having same datatypes
>>>mytuple=(1,2,3,4,5)
>>>mytuple
(1, 2, 3, 4, 5)
>>>#tuples having different datatypes
>>>mytuple=(1,”Python”,2.5)
>>>mytuple
(1,”Python”, 2.5)
>>>#tuple assignment
>>>X, Y, Z= mytuple
>>>X
1
>>>Y
Python
>>>Z
2.5
15
Problem Solving and Python Programming 2020
PRECEDENCE OF OPERATORS
Operator:
An operator is a special symbol that is used to perform particular mathematical or logical
computations like addition, multiplication, comparison and so on. The value of operator is
applied to be called operands. For e.g., in the expression 4 + 5, 4 and 5 are operands and + is an
operator. The following tokens are operators in Python:
+ - * ** / // %
Operator precedence:
When an expression contains more than one operator, precedence is used to determine
the order of evaluation. The order of evaluation depends on rules of precedence.
Rules of precedence
i) Parenthesis has the highest precedence.
Example: 5*(9-3)
Here expression in parenthesis is evaluated first.
ii) Exponentiation has next highest precedence.
Example: 1+2**3=9
iii) Multiplication and division have next higher precedence than addition and subtraction.
Example: 3*2-1=5
iv) Operators with same precedence are evaluated from left to right (Except exponentiation).
The following table summarizes the operator precedence in Python, from the highest
precedence to the lowest precedence. Operators in the same box have the same precedence and
group from left to right (except for comparisons statements).
16
Problem Solving and Python Programming 2020
x[index:index] Slicing
left to right
** Exponentiation right-to-left
+x Unary plus
-x Unary minus left to right
~x Bitwise NOT
* Multiplication
/ Division
left to right
// Floor division
% Remainder
+ Addition left to right
- Subtraction
Bitwise Left Shift and Right
<<, >> left to right
Shift
& Bitwise AND left to right
^ Bitwise XOR left to right
| Bitwise OR left to right
in, not in
Membership tests
is, is not
Identity tests Chain from left to right
<, <=, >, >=, <>, !=,
Comparisons
==
Not Boolean NOT left to right
And Boolean AND left to right
Or Boolean OR left to right
E (Exponent)
MD (multiplication and division)
AS (addition and subtraction)
Arithmetic evaluation is carried out using two phases from left to right. During the first phase
highest priority operators are evaluated. The second phase lowest priority operators are
evaluated.
Example:
6+4/2 is 8, not 5.
Example:
>>>X, Y, Z=2, 3, 4
>>>value=X-Y/3+Z*3-1
>>>print(“Result=”,value)
Result=12
COMMENTS
Comments are the non-executable statements explain what the program does. For large
programs it often difficult to understand what is does. The comment can be added in the program
code with the symbol #.
Comment contains information for persons reading the program. Comment lines are
ignored during program execution. Comment lines have no effect on the program results.
Example:
print ‘Hello, World!’ # print the message Hello, World!; comment
v=7 # creates the variable v and assign the value 7; comment
Types of comments
i) Single line comments
ii) Multi line comments
i) Single line comments
Single line comments describes information in one line(short),and they start with the
symbol #.Everything from the # to the end of the line is ignored, it has no effect on the execution
of the program.
18
Problem Solving and Python Programming 2020
Example:
>>>#This is a print statement
>>>print(“Hello python”)
Hello python
ii) Multi line comments
Multi line comments describes information in detail (multiple line).Here,more than
one line of comments can be added to the program in between the triple quotes(” ” ”).
Example:
”””This is print statement
This line print “Hello python”
Written by ABC, April 2017”””
MODULES AND FUNCTIONS
Modules
Module is a file containing python definitions and statements. We use modules to break
down large programs into small manageable and organized files. Modules provide reusability of
code. Modules are imported from other modules using the import command.
i) When module gets imported, Python interpreter searches for module.
ii) If module is found, it is imported.
iii) If module is not found,”module not found” will be displayed.
Modules
19
Problem Solving and Python Programming 2020
20
Problem Solving and Python Programming 2020
c=a+b
return c
ii) Save it as sum.py
iii) Import the module using import command
>>>import sum
>>>print sum.add(10,20)
Functions
A function is a group of statements that perform a specific task. If a program is large, it is
difficult to understand the steps involved in it. Hence, it is subdivided into a number of smaller
programs called subprograms or modules. Each subprogram specifies one or more actions to be
performed for the larger program. Such subprograms are called as functions. Functions may or
may not take arguments and may or may not produce results.
Function is defined as a block of organized, reusable code that is used to perform single,
related action. Function provides better modularity and high degree of reusing.
Advantages of using functions:
i) Better modularity
ii) High degree of reusing
iii) Better readability
iv) Easy to debug and testing
v) Improved maintainability
Functions
21
Problem Solving and Python Programming 2020
Built-in Functions:
Built-in functions are predefined functions. User can use the functions but cannot
modify them. Python has the following built-in functions.
i) input():read the input from user.
>>>name=input (“Enter the name”)
ii) print():print values to screen.
>>>print (“Hello python”)
iii) type():gives the type of value.
>>>type (12)
<type ‘int’>
iv) min():find minimum value from several values.
>>>min (5,7,8,9)
5
v) max():find maximum value from several values.
>>>max (10,100,50,70)
100
vi) pow():find power of given value.
>>>pow (3,2)
9
User defined functions:
The functions defined by the users according to their requirements are called user-defined
functions. The users can modify the function according to their requirements.
Example:
multiply(), sum_of_numbers(), display()
Elements of user defined functions:
(i) Function definition
(ii) Function-Use (or) function call
22
Problem Solving and Python Programming 2020
23
Problem Solving and Python Programming 2020
Example Program:
1. def sum(a,b):
2. c=a+b
3. return c
4. print(“The sum is:”, sum(10,5))
Python interpreter starts at line 1 of above program. In line 1, there is a function
definition. So it skips the function definition, and go to line 4.In line 4, function call is present.
So it goes back to function definition and execute it. After return statement, it again comes to
line 4 and execute it.
ARGUMENTS AND PARAMETERS
Arguments
Argument is the value, supply to function call. This value is assigned to corresponding
parameter in the function definition. Arguments are specified within a pair of paranthesis,
separated by commas.
Types of arguments
i) Required arguments
ii) Keyword arguments
iii) Default arguments
iv) Variable-Length arguments
i) Required arguments
Required arguments are the arguments passed to a function in correct positional order.
Here number of arguments in function call should match exactly with function definition.
Example Program:
def sum(a,b):
c=a+b
return c
print(“The sum is:”,sum(6,4))
Output:
The sum is:10
24
Problem Solving and Python Programming 2020
25
Problem Solving and Python Programming 2020
26
Problem Solving and Python Programming 2020
print(“Second number:”,b)
swap(a,b)
Output:
Enter the first number: 20
Enter the second number: 10
Before Swap:
First number: 20
Second number: 10
After Swap:
First number: 10
Second number: 20
Using temp function:
n1=input (“Enter the value of a:”)
n2=input (“Enter the value of b:”)
print (“Before Swap:”)
print (“Value of a:”,n1)
print (“Value of b:”,n2)
temp =n1
n1=n2
n2=temp
print(“After Swap:”)
print(“Value of a:”,n1)
print(“Value of b:”,n2)
Output:
Before Swap:
Value of a: 10
Value of b: 15
After Swap:
Value of a: 15
Value of b: 10
27
Problem Solving and Python Programming 2020
28
Problem Solving and Python Programming 2020
29
Problem Solving and Python Programming 2020
Translate program one statement at a Scans the entire program and translates the
1
time. whole into machine code.
30
Problem Solving and Python Programming 2020
values the operator is applied to are called operands. For eg, in the expression 4 + 5, 4 and 5 are
operands and + is an operator.
5. What is the difference between * operator and ** operator?
* is a multiplication operator which multiplies two operands.
Example: 3*2 returns 6.
** is an exponent operator that performs exponential (power) calculation.
Example: 3**2 returns 9.
6. Compare arguments and parameters.
Arguments Parameters
1.It is the value, which is given to 1.It is the name, which is given in
function call. function definition.
2.Syntax: 2.Syntax:
functionname(arguments) def functionname(parameter):
31
Problem Solving and Python Programming 2020
32
Problem Solving and Python Programming 2020
33
Problem Solving and Python Programming 2020
~ - One’s Complement
>> - Right shift
<< - Left shift
^ - Bitwise XOR
22. What are the features of the Python language?
Easy to learn
Interpreted
Interactive
Object Oriented
High Level language
23. Name four types of scalar objects in python has. (JANUARY 2018)
The commonly used scalar types in Python are:
Int- Any integer.
Float-Floating point number (64 bit precision).
Bool-True, False.
Str-A sequence of characters.
24. What is tuple? How literals of type tuple are written? Give example (JANUARY 2018)
Tuple is an immutable sequence of values, they are separated by commas. The value can
be any type and they are indexed by integer. The literals of type tuple are written as,
(), (9,), (8, 9, 0)
25. What are keywords? Give example. (JANUARY 2019)
The python interpreter uses keywords to recognize the structure of the program and they
cannot be used as variable names.Python2 has 31 keywords. Example: class, print
26. State the reason to divide programs into functions. (JANUARY 2019)
Creating a new function gives an opportunity to name a group of statements, which
makes program easier to read and debug. Functions can make a program to smaller by
eliminating the repeated code.
34
Problem Solving and Python Programming 2020
27. Compare interpreter and compiler. What type of translator is used for Python?
(JANUARY 2020)
Interpreter - Translates program one statement at a time Compiler - Translates program one
statement at a time. Python uses interpreter as a translator
28. Write a python program to print sum of cubes of the values of n variables.
(JANUARY 2020)
n=int(input())
sum=0
for i in range(1,n+1):
sum=sum+i**3
print(sum)
35
Problem Solving and Python Programming 2020
36
Problem Solving and Python Programming 2020
ii)Discuss about keyword arguments and default arguments in python with examples(4+4)
(JANUARY 2020)
18.i)Write a python program print the maximum among ‘n’randomly generate ‘d’ numbers by
storing them in a list(10) (JANUARY 2020)
ii)Evaluate the following expression in python
(i)24//6%3
(ii)float(4+int(2.39)%2)
(iii)2 **2**3 (6) (JANUARY 2020)
37
Problem Solving and Python Programming 2020
1.Explain how to write and execute a program in python illustrate the steps for writing a python
program to check whether the number is palindrome or not.
2. Formulate with an example program to pass the list arguments to a function.
3. Do the Case study and perform the following operation in tuples i) Maxima ii) minima iii) sum
of two tuples iv) duplicate a tuple v) slicing operator vi) obtaining a list from a tuple vii)
Compare two tuples viii) printing two tuples of different data types.
4. Formulate with an example program to find out all the values in the list that is greater than the
specified number.
5. Write a program to find out the square root of two numbers.
38
Problem Solving and Python Programming 2020
Additional Programs
1. Python program to calculate the average of numbers in a given list.
n=int(input("Enter the number of elements to be inserted: "))
a=[]
for i in range(0,n):
elem=int(input("Enter the element: "))
a.append(elem)
avg=sum(a)/n
print("Average of elements in the list",round(avg,2))
Output:
Enter the number of elements to be inserted: 3
Enter the element: 23
Enter the element: 45
Enter the element: 56
Average of elements in the list 41.33
2. Python program to exchange the values of two numbers without using a temporary
variable.
def swap(a,b):
a,b=b,a
print(“After Swap:”)
print(“First number:”,a)
print(“Second number:”,b)
a=input(“Enter the first number:”)
b=input(“Enter the second number:”)
print(“Before Swap: ”)
print(“First number:”,a)
print(“Second number:”,b)
swap(a,b)
Output:
Enter the first number: 20
39
Problem Solving and Python Programming 2020
40
Problem Solving and Python Programming 2020
41
Problem Solving and Python Programming 2020
42
Problem Solving and Python Programming 2020
Output:
Enter the lower limit for the range:1
Enter the upper limit for the range:16
1
3
5
7
9
11
13
15
9. Python program to find the sum of digits in a number.
n=int(input("Enter the number:"))
tot=0
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
print("The total sum of digits is:",tot)
Output:
Enter the number:1892
The total sum of digits is: 20
10. Python program to count the number of digits in a number
n=int(input("Enter the number:"))
count=0
while(n>0):
count=count+1
n=n//10
print("The number of digits in the number are:",count)
43
Problem Solving and Python Programming 2020
Output:
Enter the number:123
The number of digits in the number are: 3
11. Python program to check if a number is a palindrome.
n=int(input("Enter the number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is palindrome")
else:
print("The number is not a palindrome")
Output:
Enter the number:121
The number is palindrome
12. Python program to take the temperature in Celsius and convert it to Fahrenheit.
Celsius=int(input("Enter the Temperature in Celsius:"))
f=(Celsius*1.8)+32
print("Temperature in Fahrenheit is:",f)
Output:
Enter the Temperature in Celsius:32
Temperature in Fahrenheit is: 89.6
13. Python program to print squares of numbers.
for i in range(1,5,1):
print(i*i)
Output:
1 4 9 16
44
Problem Solving and Python Programming 2020
100
Problem Solving and Python Programming 2020
101