0% found this document useful (0 votes)
32 views

Unit 2

Uploaded by

lavanya2web
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Unit 2

Uploaded by

lavanya2web
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Problem Solving and Python Programming 2020

CHAPTER 2

DATA, EXPRESSIONS, STATEMENTS

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

DATA, EXPRESSIONS, STATEMENTS


2. PYTHON INTRODUCTION
Python is a general purpose interpreted, object oriented, interactive, high level
programming language. It was developed by “GUIDO VAN ROSSUM” in 1991 at the National
Research Institute for Mathematics and Computer Science in Netherlands. Many of the python
features are originated from an interpreted language called ”ABC”. In order to overcome the
limitations in ABC, Python language was developed. Since the developer was the fan of the BBC
comedy show “Monty Pythons Flying Circus”, he named the language as “PYTHON”.
Features of Python:
Easy to learn: Python is a simple programming language with few keywords, simple syntax
which is easy to learn.
Interpreted: Python is processed at runtime by the interpreter.
Interactive: We interact with interpreter directly to write our programs.
Object oriented: Python program is built around objects which combine data and
functionalities.
High level language: When writing a program, no need to bother about the low level details
such as managing memory etc.
Simple: It is a simple language. Reading a Python program feels like reading English.
Portable: Python can run a variety of platforms.
Free and open source: We can freely distribute copy of Python software.
Extendable: We can add low level modules to the Python interpreter easily.
Easy to maintain: Python source code is easy to maintain.
PYTHON INTERPRETER AND INTERACTIVE MODE
Python is an interpreted programming language, because Python programs are executed
by the python interpreter. Interpreter takes high level program as input and executes the program.
Interpreter processes the source program without translating it into a machine language at a
minimum time. It read lines and performs computations alternatively. The diagrammatic
representation of Python interpreter mode is given below.

2
Problem Solving and Python Programming 2020

Source code
Output
Python
data
Interpreter
Input data

Fig 2.1: Interpreter


Compiler:
Compiler reads the entire source program and translates it to machine readable form
called object code or executable code. Once a program in compiled, the program can be executed
repeatedly without further translations.

Source code Compiler Machine code

Input data Executable Output data


program

Fig 2.2: Compiler


Difference between interpreter and compiler:
Sl.No Interpreter Compiler

Scans the entire program and translates


1 Translate program one statement at a time
the whole into machine code

2 No intermediate code is generated Generates intermediate code

3 Execution is slower Execution is faster

4 It require less memory It require more memory

5 Example: Python Example: C,C++

3
Problem Solving and Python Programming 2020

There are two different modes to use the interpreter.


Interpreter mode (or) Script mode.
Interactive mode.
Python interpreter mode
Python interpreter mode is a mode, where scripted and finished .py files are run in the
python interpreter. The Python file is stored in the extension (.py). Python programs can be
executed in the following methods.
i) Using command line window
ii)Using python’s IDLE
iii)Directly from command prompt
i) Using command line window
The following steps are followed to use the command line window.
Open command line window
At the >>>prompt, type the following
print “HELLO PYTHON”
Press enter
To exit from python, type the following.
exit.
ii) Using python’s IDLE
IDLE (Integrated Development and Learning Environment) is a tool, which is included in
Python’s installation package. If we click the IDLE icon, it open the following python shell
window.

4
Problem Solving and Python Programming 2020

iii) Directly from command prompt


The following steps are followed to use the command prompt.
Open text editor to write the program.
Type and save it by filename.py
Open command prompt, type the name of the program.
Press enter.

Python interactive mode


Python interactive mode is a command line shell which gives immediate feedback for
each statement. We interact with Python interpreter to write a program. Here the execution is
convenient for smaller programs. In interactive mode, we do the following steps.
User type the expression.
Immediately expression is executed.
Result is printed.

5
Problem Solving and Python Programming 2020

VALUES AND TYPES


Values:
Values are the basic units of data, like a number or a string that a program manipulates.
Example: 2,’Hello World’. These values belong to different data types. That is 2 is an integer
data type and Hello World is a string data type.
Types/ Data types:
A type is a category of values. Integers(type int),floating point(type float),Booleans(type
bool),strings(type str) and lists ,tuples, dictionaries are predefined data types in python. They are
called built-in data types.

Data types

Numbers None Sequence Sets Mappings

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

Floating point numbers (type float)


Numbers with fractions or decimal points are called floating point numbers. Floating
point data type is used to represent scientific notations where the upper case ‘E’ or lower case ‘e’
signifies the 10th power.
Example 1: Example 2: Example 3:
>>>3.3e3 >>>112.9e2 >>>c=2.1
3300.0 11290.0 >>>type(c)
<type ‘float’>
Boolean (type bool)
Boolean data type was found by George Boole(1815-1864).It takes 2 values(True or
False).These two values are used when evaluating comparisons, conditional expressions etc. The
common way to produce boolean value is relational operator. The various relational operators
used in python are <,>, <=,>= etc.
Example 1: Example 2: Example 3:
>>>3<4 >>>a= (3>4) >>>a= (3>4)
True >>>a >>>a
False >>>type(a)
<type ‘bool’>
Strings (type str)
String is defined as collection of characters which may consist of letters, numbers and
special symbols or a combination of these types within quotes. An individual character in a string
is accessed using an index. The index should always be an integer (positive or negative). An
index starts from 0 to n-1. Strings are immutable i.e. the contents of the string cannot be changed
after it is created. Python will get the input at run time by default as a string. Python treats single
quotes is same as double quotes.eg: ’hello’ or “hello”.
String operators:
X holds python and Y holds program.

8
Problem Solving and Python Programming 2020

Operator Description Example

>>>X+Y
+ Concatenation-Adds values of 2 strings
python program

Repetition-creates new string.(i.e.)concatenate multiple >>>X*2


*
copies of same string python python

>>>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

Membership-returns true if a character exists in the >>>t in X


in
given string. true

Membership-returns true if a character not exists in the >>>m not in X


not in
given string. true

Built-in string methods:


capitalize()-This function capitalizes the first letter of a string.
islower()-It returns true, if all the characters in given string are lower case
isupper()-It returns true, if all the characters in given string are upper case.
len(string)-Returns the length of the string.
lower()-Convert all upper case letters to lower case letters.
Example Program:
>>>str=”HelloPython”
>>>print str
HelloPython
>>>print str[0]
H

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

iii) Input statements


In input statements ‘input’ function is used to get the input from user.
Example:
>>>Name=input (“Enter the Name :”)
Enter the Name: CSE
>>>Name
CSE
13
Problem Solving and Python Programming 2020

>>>Age=input (“Enter the age :”)


Enter the age: 100
>>> Age
100
iv) Print statements
Here ‘print’ function is used to print values to screen. It takes a series of values are
separated by commas.
Example:
>>>Name=input (“Enter the Name :”)
Enter the Name: Jovitha
>>>print (‘Hello’, Name)
Hello Jovitha
>>>print (‘Welcome’, Jovitha)
Welcome Jovitha
>>>print (‘Hello \n’,Name)
Hello
Jovitha
TUPLE ASSIGNMENT
Tuple is an immutable sequence of values. (i.e.) we cannot change the elements of
tuples. Tuples are created by using parenthesis ().Tuple is an ordered collection of values of
different data types. Tuple values are indexed by integers.
Example:
>>>t=(‘a’,’b’,’c’)
>>>t
(‘a’,’b’,’c’)
Tuple assignment is an assignment with tuple of variables on left side and tuple of expressions
on right side.
>>> X, Y, Z=100, -45, 0
>>> print X, Y, Z
100 -45 0

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).

Operator Description Associativity

(expressions...) Binding or tuple display left to right

16
Problem Solving and Python Programming 2020

[expressions...] list display


{ key: value...} dictionary display

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

The acronym PEMDAS is useful way to remember the rules. That


is,P (parenthesis first)
17
Problem Solving and Python Programming 2020

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

Built-in modules User defined modules

random math date time

Fig 2.4: Types of modules

19
Problem Solving and Python Programming 2020

Built -in modules:


Built-in modules are predefined modules, which is already in Python standard library.
Python have the following built-in modules.
i) random
This module generates random numbers. If we want random integer, we use randint
function.
Example:
>>>import random
>>> print random. randint(0,5)
1 (or) 2 (or) 3 (or) 4 (or)5
ii) math
This module is used for mathematical calculations. If we want to calculate square root,
we use the function sqrt.
Example:
>>>import math
4
>>>math . factorial(4)
24
iii) datetime
This module is used to show the current date and time.
Example:
>>>import datetime
>>>datetime . time()
9:15:20
>>>datetime . date()
21.06.2018
User defined modules:
In user defined modules we do the following steps. To create module, write one or more
functions in file, then save it with .py extensions.
i) Create a file
def add(a,b):

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

User Defined Built-in functions


Functions

Fig 2.5: Types of 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

FUNCTION DEFINITION AND USE


Function definition
Functions in Python are defined using the block keyword def followed by the function
name and parenthesis ( ). Function definition includes:
(i) A header, which begins with a keyword def and ends with a colon.
(ii) A body follows function header, consisting of one or more python statements.
Syntax:
def functionname( parameters ): #Function header
statements #Function body
return(expressions)
Function use
Function call is a statement that runs a function. It consists of function name followed
by argument list in parenthesis. Function is used by function call.
Syntax:
functionname(arguments)
Example Program:
def sum(a,b):
c=a+b
return c
print(“The sum is:”, sum(10,5))
Output:
The sum is:15
In the above program sum function return the sum values of two numbers, that can be used
anywhere in the program. The return statement is used to return values from functions.
FLOW OF EXECUTION
Flow of execution is the running order of statements. A function should be defined before
its first use. The execution always begins at the first statement of the program. Statements are run
one at a time, in the order from top to bottom. Function definition does not alter the flow of
execution of program. Statements inside function definition do not run until function is called. In
flow of execution statements are executed in order.

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

ii) Keyword arguments


The keyword arguments are related to function call. Here caller identifies arguments by
parameter name.
Example Program:
def sum(a,b):
c=a+b
return c
print(“The sum is:”,sum(a=5,b=10))
Output:
The sum is:15
iii) Default arguments
Default argument is an argument that assume default value if value is not provided in
function call.
Example Program:
def sum(a,b):
c=a+b
return c
print(“The sum is:”,sum(a=5))
Output:
The sum is:15
iv) Variable-Length arguments
Variable-Length arguments are arguments that makes function call with any number of
arguments. Here (*) is placed before the name of the variable.
Example Program:
def greeting(*name):
print(“Hai”,name)
greeting(“Welcome”)
greeting(“Welcome”,”Hello”)
Output:
Hai Welcome

25
Problem Solving and Python Programming 2020

Hai Welcome Hello


Parameter
Parameter is the name given in the function definition. Parameters are specified within
the pair of parenthesis. Parameters are just like a variable.
Syntax:
def functionname(parameter1,parameter2):
statements
functionname(argument1,argument2)
Example Program:
def sum(a,b):
c=a+b
return c
print(“The sum is:”,sum(6,4))
Output:
The sum is: 10
In the above example, parameter‘s are a, b. The argument values are 6, 4. Here sum function is
defined with 2 parameters to find sum of 2 numbers. In the function call, we need to pass 2
arguments.
ILLUSTRATIVE PROGRAMS
Exchange the values of two variables
Without using temp function:
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)

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

Circulate the values of n variables


def rotate(L,n):
newlist=L[ n: ]+L[ :n ]
return newlist
list = [1,2,3,4,5]
print(“The original list is:”,list)
mylist=rotate(list,1)
print(“List rotated clockwise by 1:”,mylist)
mylist=rotate(list,2)
print(“List rotated clockwise by 2:”,mylist)
mylist=rotate(list,3)
print(“List rotated clockwise by 3:”,mylist)
mylist=rotate(list,4)
print(“List rotated clockwise by 4:”,mylist)
Output:
The original list is: [1, 2, 3, 4, 5]
List rotated clockwise by 1: [2, 3, 4, 5, 1]
List rotated clockwise by 2: [3, 4, 5, 1, 2]
List rotated clockwise by 3: [4, 5, 1, 2, 3]
List rotated clockwise by 4: [5, 1, 2, 3, 4]
Distance between two points
import math
def distance(x1,y1,x2,y2):
dx=x2 - x1
dy=y2 - y1
dsquare=dx**2 - dy**2
result=math . sqrt(dsquare)
return result
x1=int(input(“Enter the value of x1:”))
y1=int(input(“Enter the value of y1:”))

28
Problem Solving and Python Programming 2020

x2=int(input(“Enter the value of x2:”))


y2=int(input(“Enter the value of y2:”))
print(“The distance between two points:” ,distance(x1,y1,x2,y2))
Output:
Enter the value of x1:2
Enter the value of y1:4
Enter the value of x2:3
Enter the value of x1:6
The distance between two points:2.23

29
Problem Solving and Python Programming 2020

PART A (2 Marks with Answers)


1. Write short notes on python.
Python is a general-purpose, interpreted, interactive, object-oriented, and high-level
programming language. Python is created by “Guido Van Rossum” in 1991. It is derived from
several languages, including ABC, Modula-3, C, C++, Algol-68, Smalltalk, and Unix shell and
other scripting languages.
2. Compare interpreter and compiler.
Sl.No Interpreter Compiler

Translate program one statement at a Scans the entire program and translates the
1
time. whole into machine code.

2 No intermediate code is generated. Generates intermediate code.

3 Execution is slower. Execution is faster.

4 It require less memory It require more memory

5 Example: Python Example:C,C++

3. What are the advantages and disadvantages of Python?


Advantages:
Python is easy to learn for even a novice developer
Supports multiple systems and platforms.
Object Oriented Programming-driven
Allows to scale even the most complex applications with ease.
A large number of resources are available for Python.
Disadvantages:
Python is slow.
Have limitations with database access.
Python is not good for multi-processor/multi-core work.
4. Define operator.
An operator is a special symbol that asks the compiler to perform particular
mathematical or logical computations like addition, multiplication, comparison and so on. The

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):

7. What is the difference between = and == operator?


= is an assignment operator and = = is a relational operator.
= = operator returns true, if the values of two operands are equal.
= operator assigns values from right side operand to left side operand.
8. Define flow of execution in python.
Flow of execution is the order of statements run-in. A function should be defined before
its first use. The execution begins at first statements of program.
9. What are the comment lines in Python?
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

31
Problem Solving and Python Programming 2020

10. What is the need of operator precedence?


When expressions contain more than one operator, precedence is used to determine the
order of evaluation. The order of evaluation depends on rules of precedence. The rules are,
(i) Parenthesis has the highest precedence.
(ii) Exponentiations have next highest precedence.
(iii) Multiplication and division have higher precedence than addition and subtraction
(iv)Operators with same precedence are evaluated from left to right (except
exponentiation).
11. Write the syntax of function definition.
Functions in python are defined using the block keyword def followed by the function
name and parentheses ( ).Function definition includes:
(i) A header, which begins with a keyword def and ends with a colon.
(ii) A body follows function header, consisting of one or more python statements.
Syntax:
def functionname( parameters ): #Function header
statements #Function body
12. Define keyword. List few Python keywords.
Keywords are certain reserved words that have standard and pre-defined meaning in
python. We cannot use a keyword as variable name, function name or any other identifier.
Example: False, class, finally, nonlocal, yield, lambda, assert.
14. What is a variable?
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
15. What is RETURN statement?
It is used to return the control from calling function to the next statement in the program.
It can also return some values.
Example: return, return 0, return (a+b)

32
Problem Solving and Python Programming 2020

16. Define function.


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. Built-in functions, user defined functions are the two
types of functions.
17. How tuple is assigned in python.
Tuple assignment is an assignment with tuple of variables on left side and tuple of
expression on right side.
>>> X,Y,Z=100, -45, 0
>>>print X,Y,Z
100 -45 0
Here left side is a tuple of variable. The right side is a tuple of expression
18. Write short notes on strings.
String is defined as collection of characters which may consist of letters, numbers, and
special symbols or a combination of these types within quotes. Python treats single quotes is
same as double quotes.eg: ’hello’ or “hello”.
19. What are pre-defined functions? Give example.
Pre-defined functions or Built-in functions are functions already built into Python
interpreter and are readily available for use.
Example: print(), abs(), len()
20. Write in short about relational operators.
Relational operators are used to compare any two values. An expression which uses a
relational operator is called a relational expression. The value of a relational expression is either
true or false.
Example: = =, !=,>, <
3>4
Output: False
21. What are the Bitwise operators available in Python?
& - Bitwise AND
| - Bitwise OR

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

PART-B (Possible Questions)

1. Briefly discuss about the fundamental of python.


2. i) List some features of python.
ii) Explain about the input and output functions used in python.
3. i) Differentiate interactive mode and script mode.
ii) Explain operator precedence with suitable examples.
4. Define function. Explain the scope and lifetime of the variables with suitable examples.
5. Explain the various function arguments in detail.
6. Explain python modules in detail. Explain some of the built-in modules available in python.
7. Explain how variable is named and assigned in python.
8. Write a python program to exchange values of 2 variables without using functions.
9. Explain in detail about various literals used in python.
10. Write a python program to circulate values of n variables.
11. Write short notes on comments.
12. Write a python program to calculate distance between two points.
13. i )What is numeric literals? Give examples (4) (JANUARY 2018)
ii) Appraise the arithmetic operators in python with an example. (12)
14. i) Outline the operator precedence of arithmetic operators in python.(6) (JANUARY 2018)
ii) Write a python program to exchange the values of 2 variables.(4)
iii) Write a python program using function to find the sum of first ‘n’ even numbers and print
the result . (6)
15.i) Sketch the structure of interpreter and compiler. Detail the difference between them.
Explain how python works in interactive mode and script mode with example. (2+2+4)
ii)Summarize the precedence of mathematical operators in python.(8) (JANUARY 2019)
16.i)Explain the syntax and structure of user defined functions in python with examples. Also
discuss about parameter passing in function. (12)
ii)Write a python function to swap the values of two variables.(4) (JANUARY 2019)
17.i)Write a python program to rotate a list by right n times with and without slicing
techniques(4+4) (JANUARY 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

PART – C (Possible Questions)

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

Enter the second number: 10


Before Swap:
First number: 20
Second number: 10
After Swap:
First number: 10
Second number: 20
3. Python program to reverse a given number.
n=int(input("Enter number: "))
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
print("Reverse of the number:",rev)
Output:
Enter number: 124
Reverse of the number: 421
4. Python program to check whether a number is positive or negative.
a=int(input("Enter number: "))
if(a>0):
print("Number is positive")
else:
print("Number is negative")
Output:
Enter number: 45
Number is positive
5. Python program to take in the marks of 5 subjects and display the grade.
sub1=int(input("Enter the marks of first subject: "))
sub2=int(input("Enter the marks of second subject: "))

40
Problem Solving and Python Programming 2020

sub3=int(input("Enter the marks of third subject: "))


sub4=int(input("Enter the marks of fourth subject: "))
sub5=int(input("Enter the marks of fifth subject: "))
avg=(sub1+sub2+sub3+sub4+sub4)/5
if(avg>=90):
print("Grade: A")
elif(avg>=80&avg<90):
print("Grade: B")
elif(avg>=70&avg<80):
print("Grade: C")
elif(avg>=60&avg<70):
print("Grade: D")
else:
print("Grade: F")
Output:
Enter the marks of first subject: 85
Enter the marks of second subject: 95
Enter the marks of third subject: 99
Enter the marks of fourth subject: 93
Enter the marks of fifth subject: 100
Grade: A
6. Python program to print all numbers in a range divisible by a given number.
lower=int(input("Enter lower range limit:"))
upper=int(input("Enter upper range limit:"))
n=int(input("Enter the number to be divided by:"))
for i in range(lower,upper+1):
if(i%n==0):
print(i)
Output:
Enter lower range limit:1

41
Problem Solving and Python Programming 2020

Enter upper range limit:50


Enter the number to be divided by:5
5
10
15
20
25
30
35
40
45
50
7. Python program to read two numbers and print their quotient and remainder.
a=int(input("Enter the first number: "))
b=int(input("Enter the second number: "))
quotient=a//b
remainder=a%b
print("Quotient is:",quotient)
print("Remainder is:",remainder)
Output:
Enter the first number: 15
Enter the second number: 7
Quotient is: 2
Remainder is: 1
8. Python program to print odd numbers within a given range.
lower=int(input("Enter the lower limit for the range:"))
upper=int(input("Enter the upper limit for the range:"))
for i in range(lower,upper+1):
if(i%2!=0):
print(i)

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

14. Python program to print cubes of numbers.


for i in range(1,5,1):
print(i*i*i)
Output:
1 8 27 64
15. Python program to print n odd numbers.
for i in range(1,10,2):
print(i)
Output:
13579
16. Python program to print n even numbers.
for i in range(2,10,2):
print(i)
Output:
2468
17. Python program to calculate simple interest.
p=int(input(“Enter principal amount:”))
n=int(input(“Enter number of years:”))
r=int(input(“Enter the rate of interest:”))
si=p*n*r/100
print(“Simple Interest is:”,si)
Output:
Enter principal amount:5000
Enter number of years:4
Enter the rate of interest:6
Simple Interest is:1200.0

100
Problem Solving and Python Programming 2020

101

You might also like