0% found this document useful (0 votes)
5 views56 pages

Introduction to Python Programming

Chapter 5 introduces Python as an open-source, high-level, interpreter-based programming language suitable for various computing tasks. It covers fundamental concepts such as comments, identifiers, data types, operators, and debugging, along with features of Python and the differences between low-level and high-level languages. The chapter also explains the use of Python keywords, variables, and the execution modes of the Python interpreter.
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)
5 views56 pages

Introduction to Python Programming

Chapter 5 introduces Python as an open-source, high-level, interpreter-based programming language suitable for various computing tasks. It covers fundamental concepts such as comments, identifiers, data types, operators, and debugging, along with features of Python and the differences between low-level and high-level languages. The chapter also explains the use of Python keywords, variables, and the execution modes of the Python interpreter.
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

Chapter - 5

GETTING STARTED WITH PYTHON

WEIGHTAGE OF CHAPTER
5 Marks
VSA SA LA
& HOTS Total
1 Mark 2 Marks 3 Marks
2 MCQ 01
01 01 18
1 Fib 1 Hots
Synopsis

 Python is an open-source, High Level, Interpreter based Language that can be used for a
multitude of scientific and non-scientific computing purposes.
 Comments are Non-executable statements in a program.
 An Identifier is a user defined name given to a variable or a constant in a program.
 The process of identifying and removing errors from a computer program is called debugging.
 Trying to use a variable that has not been assigned a value gives an error.
 There are several data types in Python — integer, Boolean, float, complex, string, list, tuple, sets,
none and dictionary.
 Datatype conversion can happen either Explicitly NOTES or Implicitly.
 Operators are constructs that manipulate the value of operands. Operators may be unary or
binary.
 An expression is a combination of values, variables and operators.
 Python has an input() function for taking user input.
 Python has a print() function to output data to a standard output device.
 Python Keywords:
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
 



 Operators:
1. Arithmetic Operators [ +, -, * , / , % , // ,**]
2. Relational Operators [==,!=, >, <, >=, <= ]
3. Assignment Operators [=, +=, -=, *=, /=, %=, //=, **=]
4. Logical Operators [ and, or, not]
5. Identity Operators [ is, is not]
6. Membership Operators [ in, not in]
 Precedence of operators
Order of Operators Description
Precedence
1 ** Exponentiation (raise to the power)

2 ~ ,+, - Complement, unary plus and unary minus

3 * ,/, %, // Multiply, divide, modulo and floor division

4 +, - Addition and subtraction


5 <= , < , > , >=, == , != Relational and Comparison operators

6 <= , < , > , >=, == , != Relational and Comparison operators

7 is, is not Identity operators


8 in, not in Membership operators
9 not Logical Operators
10 and
11 or

 Type Conversion
1. Explicit / type casting
2. Implicit / type coercion

 Debugging
1. Syntax Errors
2. Logical Errors
3. RunTime errors
INTRODUCTION TO PYTHON
1 Mark Questions

1. What is a program?
An ordered set of instructions to be executed by a computer to carry out a specific task is called
a program.

2. What is a Programming Language?


The language used to specify this set of instructions to the computer is called a programming
language.

3. What is Source Code?


A program written in a high-level language is called source code.

4. What is an Object Code?


Object code refers to low level code which is understandable by machine. Object code is
generated from source code after going through compiler or other translator.

5. Give examples of high-level programming languages.


Python, C++, Visual Basic, PHP, Java.

6. What is the extension used for saving python files?


.py

7. Where do the python scripts get saved by default?


Python installation folder.

2 Mark Questions

1. What is a program and Programming language?


Program: An ordered set of instructions to be executed by a computer to carry out a specific task is
called a program.
Programming Language : The language used to specify this set of instructions to the computer is
called a programming language.

2. Differentiate between Low level language and high-level language.


Low Level Languages High Level Languages

 The language of 0’s and 1’s  The language which is easily


understandable by humans.
 It is a machine friendly language  It is a programmer friendly language
 It is difficult to write or  It is easy to write or comprehend
comprehend instructions. instructions.

3. Differentiate between Compiler and an Interpreter.


Compiler Interpreter

➔ Translates the entire source code, as a ➔ Translates the program statements


whole into the object code. one by one, first translating and
then executing.

➔ Error messages are generated after ➔ Error messages are displayed in


scanning the whole program. every single line.

➔ C, C++, C#, etc are programming ➔ Python, Ruby, Perl, SNOBOL,


languages that are compiler-based. MATLAB, etc are programming
languages that are interpreter-
based.
➔ It takes a large amount of time to ➔ It takes less time to analyze the
analyze the source code but overall source code.
execution time is faster.

➔ Compile once and run anytime. ➔ Interpreted programs are


Compiled program does not need to interpreted line-by-line every time
be compiled every time. they are run.

FEATURES OF PYTHON
5 Mark Questions
 Briefly explain the Features of Python.
 Python is a high level language. It is a free and open source language.
 It is an interpreted language, as Python programs are executed by an interpreter.
 Python programs are easy to understand as they have a clearly defined syntax and relatively simple
structure.
 Python is case-sensitive. For example, NUMBER and number are not the same in Python.
 Python is portable and platform independent, meaning it can run on various operating systems
and hardware platforms.
 Python has a rich library of predefined functions.
 Python is also helpful in web development. Many popular web services and applications are built
using Python.
 Python uses indentation for blocks and nested blocks.

WORKING WITH PYTHON


1 Mark Questions

1. What is the other name for Python Interpreter?


Ans: Python Shell.

2. Which symbol in the python prompt is used, where the interpreter is ready to take instructions?
Ans: >>>

3. What is required to run or execute any Python programs?


Ans: To write and run (execute) a Python program, we need to have a Python interpreter installed
on our computer or we can use any online Python interpreter.

EXECUTION MODES
2 Mark Questions

1. Mention the 2 ways to use the Python Interpreter.


The two ways to use the python interpreter are:
a)Interactive mode b) Script mode

2. Briefly explain how python can be executed using interactive and script mode.
Interactive Mode: Allows execution of individual statements instantaneously.
Script mode: Allows us to write more than one instruction in a file called Python source code file
that can be executed.

3. What are the benefits of executing python code in Interactive Mode?


 Working in the interactive mode is convenient for testing a single line code for instant execution.
 In the interactive mode, we cannot save the statements for future use and we have to retype the
statements to run them again.
5 Mark Questions
1. Briefly explain the 2 ways to use Python Interpreter.

Interactive Mode:
● To work in the interactive mode, we can simply type a Python statement on the >>> prompt
directly.
● As soon as we press enter, the interpreter executes the statement and displays the result.
● This mode is convenient for testing a single line code for instant execution.
● But in the interactive mode, we cannot save the statements for future use and we have to retype
the statements to run them again.

Script Mode:
● In the script mode, we can write a Python program in a file, save it and then use the interpreter to
execute it.
● Python scripts are saved as files where file name has extension “.py”.
To execute the Python Program in script mode click Run->Run Module from the menu or press F5
from the keyboard.

2. Briefly explain the ways of executing python programs in script mode.


To execute a script, we can either:
a) a)Type the file name along with the path at the prompt. For example, if the name of the file is
[Link], we type [Link]. We can otherwise open the program directly from IDLE as
shown in Figure 1.

b) While working in the script mode, after saving the file, click [Run]->[Run Module] from the menu
as shown in Figure 2.

c) The output appears on shell as shown in Figure 3.

Figure 1 : Python source code file ([Link])


Figure 2 : Execution of Python in Script mode using IDLE

Figure 3 : Output of a program executed in script mode

PYTHON KEYWORDS
1 Mark Questions

1. What are Keywords?


Keywords are reserved words. Each keyword has a specific meaning to the Python interpreter,
and we can use a keyword in our program only for the purpose for which it has been defined.

2. Is Python a case-sensitive language?


Yes, Python is a case sensitive language.

3 Mark Questions
1 List all the Keywords available in Python.
False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass


break except in raise

PYTHON IDENTIFIERS
1 Mark Questions
[Link] an identifier.
In programming languages, identifiers are names used to identify a variable, function, or other
entities in a program.

5 Mark Questions
1. Mention the rules for naming an identifier in Python. Also give examples for valid and invalid
identifiers.
The rules for naming an identifier in Python are as follows:
● The name should begin with an uppercase or a lowercase alphabet or an underscore sign (_).
This may be followed by any combination of characters a–z, A–Z, 0–9 or underscore (_). Thus, an
identifier cannot start with a digit.
● It can be of any length. (However, it is preferred to keep it short and meaningful).
● It should not be a keyword or reserved word given in Table 5.1.
● We cannot use special symbols like !, @, #, $, %,etc., in identifiers.

Example for Valid Identifiers:

To find the average of marks obtained by a student in three subjects, we can choose the identifiers as
marks1, marks2, marks3 and avg rather than a, b, c, or A, B, C.
avg = (marks1 + marks2 + marks3)/3
Similarly, to calculate the area of a rectangle, we can use identifier names, such as area, length, breadth
instead of single alphabets as identifiers for clarity and more readability.
area = length * breadth
Example for Invalid Identifiers:
Serial_No, 1st_Room, Hundred$ etc.

VARIABLES
1 Mark Questions

1. What is a variable?
A variable in a program is uniquely identified by a name (identifier). Variable in Python refers to an
object — an item or element that is stored in the memory.
2 Mark Questions
1. Illustrate with an example of how a variable can be created and assign values to it.
In Python we can use an assignment statement to create new variables and assign specific values to
them.
Eg: gender = 'M'
message = "Keep Smiling"
price = 987.9

3 Mark Questions
1. Write a program to display values of variables in Python.
message = "Keep Smiling"
print(message)
userNo = 101
print('User Number is', userNo)

2. With an example explain how variables are declared implicitly in python.


●Variable declaration is implicit in Python, which means variables are automatically declared and
defined when they are assigned a value the first time.
●Variables must always be assigned values before they are used in expressions as otherwise it will lead
to an error in the program.
●Wherever a variable name occurs in an expression, the interpreter replaces it with the value of that
particular variable.
Eg: gender = 'M'
message = "Keep Smiling"
price = 987.9

3/5 Mark Questions


1. Write a Python program to find the area of a rectangle given that its length is 10 units and
breadth is 20 units.
Ans: length = 10
breadth = 20
area = length * breadth
print(area)

COMMENTS
1 Mark Questions
[Link] Comments.
Comments are used to add a remark or a note in the source code. Comments are not executed by the
interpreter.

5 Mark Questions
1. Briefly explain the benefits of using comments in the python programming language with an
example.
 They are added with the purpose of making the source code easier for humans to understand.
 They are used primarily to document the meaning and purpose of source code and its input and
output requirements, so that we can remember later how it functions and how to use it.
 For large and complex software, it may require programmers to work in teams and sometimes, a
program written by one programmer is required to be used or maintained by another programmer.
 In such situations, documentations in the form of comments are needed to understand the working
of the program.
 In Python, a comment starts with # (hash sign).
 Everything following the # till the end of that line is treated as a comment and the interpreter simply
ignores it while executing the statement.

Example:
#Variable amount is the total spending on
#grocery
amount = 3400
#totalMarks is sum of marks in all the tests
#of Mathematics
totalMarks = test1 + test2 + finalTest

3 Mark Questions

1. Write a Python program to find the sum of two numbers.


#To find the sum of two numbers
num1 = 10
num2 = 20
result = num1 + num2
print(result)

EVERYTHING IS AN OBJECT
3 Mark Question
1. Explain briefly with an example how everything is treated as an object in python programming.
● Python treats every value or data item whether numeric, string, or other type (discussed in the
next section) as an object in the sense that it can be assigned to some variable or can be passed to
a function as an argument.
● Every object in Python is assigned a unique identity (ID) which remains the same for the
lifetime of that object.
● This ID is akin to the memory address of the object. The function id() returns the identity of an
object.
Example:
>>> num1 = 20
>>> id(num1)
1433920576 #identity of num1
>>> num2 = 30 - 10
>>> id(num2)
1433920576 #identity of num2 and num1
#are same as both
refers to #object 2

DATA TYPES
1 Mark Questions
1. What is a Data Type?
Data type identifies the type of data values a variable can hold and the operations that can be
performed on that data.

2 Mark Questions
1. With a neat diagram illustrate the different data types in Python.

NUMBER
1 Mark Questions
1. List the 2 constants of Boolean Data Type
True value is non-zero
False is the value zero

2. Mention the built-in function used to determine the data type of the variable.
type():

3 Mark Questions
1. With a neat tabular representation, explain Number data type with examples.
Type/Class Description Examples
Table :
int Integer numbers -12,-3,0,125,2
Numeric Data
float real/floating point numbers -2.04,4.0,14.23 Types

complex Complex numbers 3+4j,2-2j


>>> num1 = 10
>>> type(num1)
<class 'int'>
>>> float1 = -1921.9
>>> type(float1)
<class 'float'>
>>> float2 = -9.8*10**2
>>> print(float2, type(float2))
-980.0000000000001 <class 'float'>
>>> var2 = -3+7.2j
>>> print(var2, type(var2)) (-3+7.2j) <class 'complex'>

5 Mark Questions
[Link] a python program which determines the data type of the variable using built-in-function.
>>> num1 = 10
>>> type(num1)
<class 'int'>
>>> num2 = -1210
>>> type(num2)
<class 'int'>
>>> var1 = True
>>> type(var1
<class 'bool'>
>>> float1 = -1921.9
>>> type(float1)
<class 'float'>
>>> float2 = -9.8*10**2
>>> print(float2, type(float2))
-980.0000000000001 <class 'float'>
>>> var2 = -3+7.2j
>>> print(var2, type(var2)) (-3+7.2j) <class 'complex'>

SEQUENCE
1 Mark Questions
1. Define a sequence.
A Python sequence is an ordered collection of items, where each item is indexed by an integer.
2. List the sequence data types available in Python.
The three types of sequence data types available in Python are
● Strings
● Lists
● Tuples.

5 Mark Questions
1. Define a String. Briefly explain the data type String with an example.
Definition : String is a group of characters.
●These characters may be alphabets, digits or special characters including spaces. String values are
enclosed either in single quotation marks (e.g., ‘Hello’) or in double quotation marks (e.g., “Hello”)..
●The quotes are not a part of the string, they are used to mark the beginning and end of the string for
the interpreter.
Eg:
>>> str1 = 'Hello Friend'
>>> str2 = "452"
We cannot perform numerical operations on strings, even when the string contains a numeric value, as
in str2

2. Define a List. Briefly explain the data type List, with an example program
Definition : List is a sequence of items separated by commas and the items are enclosed in square
brackets [ ].
Eg:
#To create a list
>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list list1
>>> print(list1)
[5, 3.4, 'New Delhi', '20C', 45]

3. Define a tuple. Briefly explain the data type Tuple with an example program.
Definition: Tuple is a sequence of items separated by commas and items are enclosed in parenthesis ( ).
●This is unlike list, where values are enclosed in brackets [ ]. Once created, we cannot change the tuple.
Eg:
#create a tuple tuple1
>>> tuple1 = (10, 20, "Apple", 3.4, 'a') #print the elements of the tuple tuple1
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')

4. Define a set. Briefly explain the data type Set with an example program.
Definition:Set is an unordered collection of items separated by commas and the items are enclosed in
curly brackets { }.
●A set is similar to a list, except that it cannot have duplicate entries.
●Once created, elements of a set cannot be changed.
Eg:
#create a set
>>> set1 = {10,20,3.14,"New Delhi"}
>>> print(type(set1))
<class 'set'>
>>> print(set1)
{10, 20, 3.14, "New Delhi"}

#duplicate elements are not included in set


>>> set2 = {1,2,1,3}
>>> print(set2)
{1, 2, 3}

NONE
5 Mark Questions
1. Define None data [Link] with an example program.
Definition: None is a special data type with a single value.
●It is used to signify the absence of value in a situation. None supports no special perations, and it is
neither the same as False nor 0 (zero).
Eg:
>>> myVar = None
>>> print(type(myVar))
<class 'NoneType'>
>>> print(myVar)
None

MAPPING
1 Mark Questions
1. Define Mapping data type.
Mapping is an unordered data type in Python.

2. Name the only one standard mapping data type in Python.


Dictionary.

5 Mark Questions
1. With an example program explain the standard mapping data type Dictionary in Python. OR What
are the rules to be followed while declaring a dictionary?
● Dictionary in Python holds data items in key-value pairs. Items in a dictionary are enclosed in curly
brackets { }.
● Dictionaries permit faster access to data. Every key is separated from its value using a colon (:) sign.
● The key : value pairs of a dictionary can be accessed using the key.
● The keys are usually strings and their values can be any data type.
● In order to access any value in the dictionary, we have to specify its key in square brackets [ ].

Eg:
#create a dictionary
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
>>>print(dict1['Price( kg)'])
120

MUTABLE & IMMUTABLE DATA TYPES


Mark Questions
1. Define Mutable Data types
Variables whose values can be changed after they are created and assigned are called mutable.
2. Define Immutable Data types
Variables whose values cannot be changed after they are created and assigned are called immutable.
3. List the classification of Python data types
Ans: [Link] Data type
2. Immutable Data type

2 Mark Questions
1. Draw a diagram for the classification of data types.

2. Differentiate between Mutable Data Type and Immutable Data Type.


Mutable Data Type Immutable Data Type
a) Variables whose values can be a) Variables whose values cannot be changed
changed after they are created after they are created and assigned are
and assigned are called mutable. called immutable.

b) Eg: Lists, Sets, Dictionary. b) Eg:Integers,Float,Boolean,Complex,Strings,


Tuples.

5 Mark Questions
1. Explain with a neat labeled diagram, how memory is allocated for variables with values being
assigned to them.

>>> num1 = 300


This statement will create an
object with value 300 and
the object is referenced by
the identifier num1.

>>> num2 = num1


The statement num2 = num1 will
make num2 refer to the value 300,
also being referred by num1, and
stored at memory location
number, say 1000. So, num1
shares the referenced location
with num2.
In this manner Python makes the assignment effective by copying only the reference, and not the data:
>>> num1 = num2 + 100
This statement 1 num1 = num2 + 100 links the variable num1 to a new object stored at memory location
number say 2200 having a value 400. As num1 is an integer, which is an immutable type, it is rebuilt.

DECIDING USAGE OF PYTHON DATA TYPES


3 Mark Question
1. Explain how users can decide the usage of python Data Types.
Lists
● It is preferred to use lists when we need a simple iterable collection of data that may go for
frequent modifications.
● For example, if we store the names of students of a class in a list, then it is easy to update the list
when some new students join or some leave the course.
Tuples
● Tuples are used when we do not need any change in the data. For example, names of months in
a year.
● When we need uniqueness of elements and to avoid delicacy it is preferable to use sets, for
example, list of artefacts in a museum.
Dictionaries
● If our data is being constantly modified or we need a fast lookup based on a custom key or we
need a logical association between the key : value pair, it is advised to use dictionaries.
● A mobile phone book is a good application of dictionary.

OPERATORS
1 Mark Questions
1. What is an Operator?
An operator is used to perform specific mathematical or logical operation on values.

2. What is an Operand?
The values that the operators work on are called operands.

2 Mark Questions
1. With an example explain what is an operator and an operand.
An operator is used to perform specific mathematical or logical operations on values.
The values that the operators work on are called operands.
For example, in the expression 10 + num, the value 10, and the variable num are operands and the +
(plus) sign is an operator.

ARITHMETIC OPERATORS
1 Mark Question
1. What is the usage of Arithmetic Operators?
Python supports arithmetic operators that are used to perform the four basic arithmetic operations as
well as modular division, floor division and exponentiation.

5 Mark Questions
[Link] the concept of Arithmetic Operators in Python with an example.
Oper Operation Description Example
ator
+ Addition Adds the two numeric values on >>> num1 = 5
either side of the operator >>> num2 = 6
>>> num1 + num2
This operator can also be used to 11
concatenate two strings on either >>> str1 = "Hello"
side of the operator >>> str2 = "India"
>>> str1 + str2
'HelloIndia'
- Subtraction Subtracts the operand on the right >>> num1=5
from the operand on the left >>> num2 =6
>>> num1 - num 2
-1
* Multiplication Multiplies the two values on both >>> num1 = 5
side of the operator. >>> num2 = 6
>>> num1 * num2 30
Repeats the item on left of the >>> str1 = 'India'
operator if first operand is a string >>> str1 * 2 'IndiaIndia'
and second operand is an integer
value
/ Division Divides the operand on the left by >>> num1=8
the operand on the right and returns >>> num2 =4
the quotient >>> num1 / num 2
0.5
% Modulus Divides the operand on the left by >>> num1=13
the operand on the right and returns >>> num2 =5
the remainder >>> num1 % num 2
3
// Floor Division Divides the operand on the left by the >>> num1=13
operand on the right and returns the >>> num2 =4
quotient by removing the decimal >>> num1 // num 2
part. It is sometimes also called 3
integer division. >>>num2 // num1
0
** Exponent Performs exponential (power) >>> num1=3
calculation on operands. That is, raise >>> num2 =4
the operand on the left to the power >>> num1 ** num 2
of the operand on the right 81

RELATIONAL OPERATORS
1 Mark Question

[Link] is the purpose of Relational Operators?


Relational operator compares the values of the operands on its either side and determines the
relationship among them.

5 Mark Questions
1. Explain the concept of Relational Operators in Python with an example.
Assume the Python variables num1 = 10, num2 = 0, num3 = 10, str1 = "Good", str2 = "Afternoon" for
the following examples:

Oper Operation Description Example


ator
== Equals to If the values of two operands are >>> num1 == num2
equal, then the condition is True, False
otherwise it is False
>> str1 == str2
False
!= Not equal to If values of two operands are not >>> num1 != num2
equal, then condition is True, True
otherwise it is False >>> str1 != str2
True
>>> num1 != num3
False
> Greater than If the value of the left-side >>> num1 > num2
operand is greater than the value True
of the right- side operand, then >>> str1 > str2 True
condition is True, otherwise it is
False
< Less than If the value of the left-side >>> num1 < num3
operand is less than the value of False
the right- side operand, then >>> str2 < str1 True
condition is True, otherwise it is
False
>= Greater than or If the value of the left-side >>> num1 >= num2
equal to operand is greater than or equal True
to the value of the right-side >>> num2 >= num3
operand, then condition is True, False
otherwise it is False
>>> str1 >= str2 True
<= Less than or equal If the value of the left operand is >>> num1 <= num2
to less than or equal to the value of False
the right operand, then is True >>> num2 <= num3
otherwise it is False True
>>> str1 <= str2 False

ASSIGNMENT OPERATORS
1 Mark Question
1. What is the purpose of the Assignment Operator?
Ans: Assignment operator assigns or changes the value of the variable on its left.
5 Mark Question
1. Explain the concept of Assignment Operators in Python with an example.

Operator Description Example


= Assigns value from right-side operand to left >>> num1 =2
side operand. >>> num2= num1
>>> num2
2
>>> country = ‘India’
>>> country
‘India
+= It adds the value of the right-side operand to >>>num1 = 10
the left-side operand and assigns the result to >>>num2 = 2
the left-side operand. >>> num1 += num2
Note:x +=y is same as x=x+y >>>num1
12
>>>num2
2
>>>str1 = ‘Hello’
>>>str2 = ‘India’
>>> str1 += str2
>>> str1
‘HelloIndia’

-= It subtracts the value of the right-side operand >>>num1 = 10


to the left-side operand and assigns the result >>>num2 = 2
to the left-side operand. >>> num1 -= num2
Note:x - =y is same as x=x-y >>>num1
8

*= It multiples the value of the right-side operand >>>num1 = 2


to the left-side operand and assigns the result >>>num2 = 3
to the left-side operand. >>> num1 * = 3
Note:x *=y is same as x=x*y >>>num1
6
>>> a = ‘India’
>>> a *= 3
>>>a
‘IndiaIndiaIndia’
/= It divides the value of the right-side operand to >>>num1 = 6
the left-side operand and assigns the result to >>>num2 = 3
the left-side operand. >>> num1 / = num2
Note:x /=y is same as x=x/y >>>num1
2.0

%= It performs modulus operation using two >>>num1 = 7


operands and assigns the result to the left-side >>>num2 = 3
operand. >>> num1 % = num2
Note : x%=y is same as x=x%y >>>num1
1

// = It performs floor division using two operands >>>num1 = 7


and assigns the result to the left-side operand. >>>num2 = 3
Note : x //=y is same as x=x//y >>> num1 // = num2
>>>num1
2

**= It performs exponential(power) calculation on >>>num1 = 2


operators and assigns value to the left-side >>>num2 = 3
operand. >>> num1 **= num2
Note : x**=y is same as x=x**y >>>num1
8

LOGICAL OPERATORS
1 Mark Question
1. List the 3 logical operators supported by Python.
There are three logical operators supported by Python. These operators (and, or, not) are to be
written in lower case only.

5 Mark Question
1. Explain the concept of Logical Operators in Python with an example.
The logical operator evaluates to either True or False based on the logical operands on either side.
Every value is logically either True or False. By default, all values are True except None, False, 0 (zero),
empty collections "", (), [], {}, and few other special values. So if we say num1 = 10, num2 = -20, then
both num1 and num2 are logically True.

Operator Operation Description Example

and Logical If both the operands are True, >>> True and True
AND then condition becomes True True
>>> num1 = 10
>>> num2 = -20
>>> bool(num1 and num2)
True
>>> True and False
False
>>> num3 = 0
>>> bool(num1 and num3)
False
>>> False and False
False

or Logical OR If any of the two operands are >>> True or True


True, then condition becomes True
True >>> True or False
True
>>> bool(num1 or num2)
True
>>>False or False
False

not Logical Used to reverse the logical >>> num1 = 10


NOT state of its operand >>> bool(num1)
True
>>> not num1
>>> bool(num1)
False

IDENTITY OPERATORS
1 Mark Question
1. What is the use of an Identity Operator?
Identity operators are used to determine whether the value of a variable is of a certain type or not.

5 Mark Question
1. Explain the concept of Identity Operators in Python with an example.
● Identity operators are used to determine whether the value of a variable is of a certain type or
not.
● Identity operators can also be used to determine whether two variables are referring to the
same object or not. There are two identity operators.
Operator Description Example

is Evaluates True if the variables on either >>> num1 = 5


side of the operator point towards the >>> type(num1) is int
same memory location and False True
otherwise. var1 is var2 results to True if >>> num2 = num1
id(var1) is equal to id(var2) >>> id(num1) 1433920576
>>> id(num2) 1433920576
>>> num1 is num2
True

is not Evaluates to False if the variables on >>> num1 is not num2


either side of the operator point to the False
same memory location and True
otherwise. var1 is not var2 results to True
if id(var1) is not equal to id(var2)

MEMBERSHIP OPERATORS
5 Mark Question

1. Explain the concept of Membership Operators in Python with an example.


Membership operators are used to check if a value is a member of the given sequence or not.
Operator Description Example

in Returns True if the variable/value is found >>> a=[1,2,3]


in the specified sequence and False >>>2 in a
otherwise True
>>>’1’ in a
False

not in Returns True if the variable/value is not >>> a=[1,2,3]


found in the specified sequence and False >>> 10 not in a
otherwise True
>>>1 not in a
False

EXPRESSIONS
1 Mark Questions
1. What is an expression?
An expression is defined as a combination of constants, variables, and operators. An expression
always evaluates to a value.

2. What is a value?
A value or a standalone variable is also considered as an expression but a standalone operator is not
an expression.

2 Mark Questions
1. What is an expression? Give an example.
An expression is defined as a combination of constants, variables, and operators.
Eg:
1. 100
2. Num
3. Num - 20.4
4. 3.0 + 3.14
5. 23/3 - 5 * 7(14 - 2)
6. “Global” + “Citizen”

PRECEDENCE OF OPERATORS
1 Mark Questions
1. What are binary operators?
Binary operators are operators with two operands.
2. What is meant by precedence of Operators?
Evaluation of the expression is based on precedence of operators. When an expression contains different
kinds of operators, precedence determines which operator should be applied first. Higher precedence
operator is evaluated before the lower precedence operator.

2 Mark Question
[Link] is meant by an Unary Operator? Give examples.
The unary operators need only one operand, and they have a higher precedence than the binary
operators.
Eg: The minus (-) as well as + (plus) operators can act as both unary and binary operators, but not is a
unary logical operator.
#Depth is using - (minus) as unary operator Value = -Depth
#not is a unary operator, negates True print(not(True))

5 Mark questions
1. With a tabular representation explain the precedence of operators in Python.
● Parenthesis can be used to override the precedence of operators. The expression within () is
evaluated first.
● For operators with equal precedence, the expression is evaluated from left to right.
Order of Operators Description
Precedence

1 ** Exponentiation (raise to the power)

2 ~ ,+, - Complement, unary plus and unary minus

3 * ,/, %, // Multiply, divide, modulo and floor division

4 +, - Addition and subtraction

5 <= , < , > , >=, == , != Relational and Comparison operators

6 <= , < , > , >=, == , != Relational and Comparison operators

7 is, is not Identity operators

8 in, not in Membership operators

9 not Logical Operators

10 and

11 or

Note:
a) Parenthesis can be used to override the precedence of operators. The expression within () is
evaluated first.
b) For operators with equal precedence, the expression is evaluated from left to right.
2. How will Python evaluate the following expressions?

a) 20 + 30 * 40 b) 20 - 30 + 40
= 20 + (30 * 40) #Step 1 The two operators (–) and (+) have equal
#precedence of * is more than that of + precedence. Thus, the first operator, i.e.,
= 20 + 1200 #Step 2 subtraction is applied before the second
= 1220 #Step 3 operator, i.e., addition (left to right).
= (20 – 30) + 40 #Step 1
= -10 + 40 #Step 2
= 30 #Step 3
c) (20 + 30) * 40 d) 15.0 / 4 + (8 + 3.0)
=(20 + 30) * 40 #Step 1 =15.0 / 4 +(8.0 + 3.0) # Step 1
#using parentheses(), we have forced =15.0 /4.0 + 11.0 #Step 2
precedence of + to be more than that of * = 3.75 + 11.0 #Step 3
= 50 * 40 #Step 2 =14.75 #Step 4
= 2000 # Step 3

STATEMENT
1 Mark Questions
1 Define Statement in Python with an example.
In Python, a statement is a unit of code that the Python interpreter can execute
Eg : >>> x = 4 # assignment statement
>>>cube = x ** 3 # assignment statement
>>> print (x, cube) #print statement
4 64

INPUT AND OUTPUT


1Mark Questions
1. Which function in python is used to take input from the user?
input() function is used to take input from the user input.

2. Name the data type which the input() function will take on accepting the data from the user
It accepts all user input as string.

3. What do you mean by prompt?


Prompt is the string we may like to display on the screen prior to taking the input, and it is optional. When
a prompt is specified, first it is displayed on the screen after which the user can enter data.

4. Which function in python is used to take input from the user?


print() function is used to output the data to the Standard output device- the screen.

3/5 Mark Questions


1. Explain in brief how to take input from the user with an example.
● In Python, we have the input() function for taking the user input.
● The input() function prompts the user to enter data.
● It accepts all user input as string.
● The user may enter a number or a string but the input() function treats them as strings only.
Syntax:
input ([Prompt])
● Prompt is the string we may like to display on the screen prior to taking the input, and it is optional.
● When a prompt is specified, first it is displayed on the screen after which the user can enter data.
● The input() takes exactly what is typed from the keyboard, converts it into a string and assigns it
to the variable on left-hand side of the assignment operator (=).
● Entering data for the input function is terminated by pressing the enter key.
Eg:
>>> fname = input("Enter your first name: ")
Enter your first name: Arnab
>>> age = input("Enter your age: ") Enter your age: 19
>>> type(age)
<class 'str'>
● The variable fname will get the string ‘Arnab’, entered by the user. Similarly, the variable age will
get the string ‘19’.

2. Explain with an example of how we can typecast or change the datatype of the string data
accepted from the user to an appropriate numeric value.
The following statement will convert the accepted string to an integer. If the user enters any non-numeric
value, an error will be generated.
Eg:
#function int() to convert string to integer
>>> age = int( input("Enter your age:")) Enter your age: 19
>>> type(age)
<class 'int'>

3. Explain print() function with syntax and an example.


● Python uses the print() function to output data to standard output device — the screen
● The function print() evaluates the expression before displaying it on the screen.
● The print() outputs a complete line and then moves to the next line for subsequent output.
Syntax:
print(value [, ..., sep = ' ', end = '\n'])

1. sep: The optional parameter sep is a separator between the output values. We can use a
character, integer or a string as a separator. The default separator is space.
2. end: This is also optional and it allows us to specify any string to be appended after the last value.
The default is a new line.
Eg:
Statement Output
print("Hello") Hello
print(10*2.5) 25.0
print("I" + "love" + "my" + "country") Ilovemycountry
print("I'm", 16, "years old") I'm 16 years old
● The third print function in the above example is concatenating strings, and we use + (plus)
between two strings to concatenate them.
● The fourth print function also appears to be concatenating strings but uses commas (,) between
strings. Actually, here we are passing multiple arguments, separated by commas to the print
function.
● As arguments can be of different types, hence the print function accepts integer (16) along with
strings here.
● But in case the print statement has values of different types and ‘+’ is used instead of comma, it
will generate an error as discussed in the next section under explicit conversion.

TYPE CONVERSION
1 Mark Questions
[Link] is meant by type conversion?
As and when required, we can change the data type of a variable in Python from one type to another.

2 Mark Questions
1. List and explain the two ways of data type conversion.
The 2 ways of data type conversion are:
● Explicit (forced) conversion
● Implicit type conversion
Explicit Type Conversion: When the programmer specifies for the interpreter to convert a data type
to another type.
Implicit Type Conversion: When the interpreter understands such a need by itself and does the type
conversion automatically.

3/5 Mark Questions


1. With an example, explain the concept and working of type conversion.
Consider the following program

num1 = input("Enter a number and I'll double it: ")


num1 = num1 * 2
print(num1)

The program was expected to display double the value of the number received and stored in variable
num1. So if a user enters 2 and expects the program to display 4 as the output, the program displays
the following result:

Enter a number and I'll double it: 2


22
This is because the value returned by the input function is a string ("2") by default. As a result, in
statement num1 = num1 * 2, num1 has string value and * acts as repetition operator which results in
output as "22". To get 4 as output, we need to convert the data type of the value entered by the user to
integer. Thus, we modify the program as follows:
num1 = input("Enter a number and I'll double it: ")
num1 = int(num1) #convert string input to #integer
num1 = num1 * 2
print(num1)

Now, the program will display the expected output as follows:


Enter a number and I'll double it: 2 4

As and when required, we can change the data type of a variable in Python from one type to another.

EXPLICIT CONVERSION
1 Mark Questions

1 What is the alternate name for explicit conversion?


Ans: Type Casting.

2. What is meant by Explicit Conversion?

Ans: Explicit conversion, also called type casting, happens when data type conversion takes place
because the programmer forced it in the program.
3 / 5 Mark Questions

1 With Syntax and an example explain how explicit conversion is performed.


Ans: Explicit conversion, also called type casting, happens when data type conversion takes place
because the programmer forced it in the program.
The general form of an explicit data type conversion is:
(new_data_type) (expression)
With explicit type conversion, there is a risk of loss of information since we are forcing an
expression to be of a specific type.
For example, converting a floating value of x = 20.67 into an integer type, i.e., int(x) will
discard the fractional part .67.

2. Briefly explain the Explicit type conversion functions in Python.


Function Description
int(x) Converts x to an integer
float(x) Converts x to a floating-point number

str(x) Converts x t a string representation

chr(x) Converts ASCII value of x to character.

ord(x) Returns the character associated with the ASCII code x

3. Write a Program depicting explicit type [Link] a Program depicting explicit type conversion
conversion from int to float. from float to int.
#Explicit type conversion from int to float #Explicit type conversion from float to int
num1 = 10 num1 = 10.2
num2 = 20 num2 = 20.6
num3 = num1 + num2 num3 = (num1 + num2)
print(num3) print(num3)
print(type(num3)) print(type(num3))
num4 = float(num1 + num2) num4 = int(num1 + num2)
print(num4) print(num4)
print(type(num4)) print(type(num4))

5. Write a Program depicting explicit type conversion between numbers and Strings
#Explicit type casting
priceIcecream = 25
priceBrownie = 45
totalPrice = priceIcecream + priceBrownie print("The total in Rs." + str(totalPrice))

● On execution, program gives an error as shown in the above output, informing that the
interpreter cannot convert an integer value to string implicitly.
● It may appear quite intuitive that the program should convert the integer value to a string
depending upon the usage.
● However, the interpreter may not decide on its own when to convert as there is a risk of loss of
information.
● Python provides the mechanism of the explicit type conversion so that one can clearly state the
desired outcome.
6. Write a Program depicting explicit type casting

#Explicit type casting


priceIcecream = 25
priceBrownie = 45
totalPrice = priceIcecream + priceBrownie print("The total in Rs." + str(totalPrice))
7. Write a Program depicting explicit type conversion from string to int.

#Explicit type conversion


icecream = '25'
brownie = '45'
#String concatenation
price = icecream + brownie
print("Total Price Rs." + price)
#Explicit type conversion - string to integer
price = int(icecream)+int(brownie)
print("Total Price Rs." + str(price))

IMPLICIT CONVERSION
1 Mark Questions

1 What is meant by Implicit Conversion?

Implicit conversion, also known as coercion, happens when data type conversion is done
automatically by Python and is not instructed by the programmer.

2 What is the alternate name for implicit conversion?


Type Coercion

3 Mark Questions
1. Write a Program depicting implicit type conversion from int to float.
#Implicit type conversion from int to float
num1 = 10 #num1 is an integer
num2 = 20.0 #num2 is a float
sum1 = num1 + num2 #sum1 is sum of a float and an integer
print(sum1)
print(type(sum1))

In the above example, an integer value stored in variable num1 is added to a float value stored in
variable num2, and the result was automatically converted to a float value stored in variable sum1
without explicitly telling the interpreter.

DEBUGGING
1 Mark Questions
1. Define Debugging.
The process of identifying and removing such mistakes, also known as bugs or errors, from a program
is called debugging.

2 Mark Questions
1. List the different types of Errors occurring in programs.
● Syntax Errors
● Logical Errors
● RunTime errors

SYNTAX ERRORS
1 Mark Question
1. What is a Syntax Error?
The interpreter interprets the statements only if it is syntactically (as per the rules of Python)
correct. If any syntax error is present, the interpreter shows error message(s) and stops the execution
there.

3 Mark Question
1. Briefly explain Syntax errors with an example.
● Python has its own rules that determine its syntax.
● The interpreter interprets the statements only if it is syntactically (as per the rules of Python)
correct.
● If any syntax error is present, the interpreter shows error message(s) and stops the execution
there.
For example, parentheses must be in pairs, so the expression (10 + 12) is syntactically correct, whereas
(7 + 11 is not due to absence of right parenthesis. Such errors need to be removed before the execution
of the program.

LOGICAL ERRORS
1 Mark Question

1. What is a Logical Error?


● A logical error is a bug in the program that causes it to behave incorrectly.
● A logical error produces an undesired output but without abrupt termination of the execution of
the program.
● Semantic Errors are also called Logical Errors as they occur when the meaning of the program (its
semantics) is not correct.
5 Mark Question

1. Briefly explain Logical errors with an example.


● A logical error is a bug in the program that causes it to behave incorrectly.
● A logical error produces an undesired output but without abrupt termination of the execution of
the program.
● Since the program interprets successfully even when logical errors are present in it, it is
sometimes difficult to identify these errors.
● The only evidence of the existence of logical errors is the wrong output.
● While working backwards from the output of the program, one can identify what went wrong.
For example, if we wish to find the average of two numbers 10 and 12 and we write the code as 10 +
12/2, it would run successfully and produce the result 16. Surely, 16 is not the average of 10 and 12.
The correct code to find the average should have been (10 + 12)/2 to give the correct output as 11.

RUNTIME ERRORS
1 Mark Question
1. What are Runtime Errors?
Ans: A runtime error causes abnormal termination of the program while it is executing. Runtime error
is when the statement is correct syntactically, but the interpreter cannot execute it.

3 Mark Questions
1. Briefly explain Runtime errors with an example.
● A runtime error causes abnormal termination of the program while it is executing.
● Runtime error is when the statement is correct syntactically, but the interpreter cannot execute
it.
● Runtime errors do not appear until after the program starts running or executing.

For example, we have a statement having division operation in the program. By mistake, if the
denominator entered is zero then it will give a runtime error like “division by zero”.

2. Write a python program which illustrates Run time error


#Runtime Errors Example num1 = 10.0
num2 = int(input("num2 = "))
#if user inputs a string or a zero, it leads to runtime error
print(num1/num2)

ASSIGNEMNT - 1
1. Briefly explain the Features of Python
2. Briefly explain the 2 ways to use Python Interpreter.
3. Mention the rules for naming an identifier in Python. Also give examples for
valid and invalid identifiers.
4. Briefly explain the benefits of using comments in the python programming
language with an example.
5. Write a python program which determines the data type of the variable using
built-in-function.
6. Define a String. Briefly explain the data type String with an example.
7. Define a set. Briefly explain the data type Set with an example program.
8. Define None data type. Explain with an example program.
9. What are the rules to be followed while declaring a dictionary?
10. Explain with a neat labeled diagram, how memory is allocated for variables with
values being assigned to them.

ASSIGNEMNT - 2

1. Explain the concept of Arithmetic Operators in Python with an example.


2. Explain the concept of Relational Operators in Python with an example.
3. Explain the concept of Assignment Operators in Python with an example.
4. Explain the concept of Logical Operators in Python with an example.
5. Explain the concept of Identity Operators in Python with an example.
6. Explain the concept of Membership Operators in Python with an example.
7. With a tabular representation explain the precedence of operators in Python.

8. How will Python evaluate the following expressions?


a) (20 + 30) * 40
b) 15.0 / 4 + (8 + 3.0)
9. Explain in brief how to take input from the user with an example.
10 Explain print() function with syntax and an example.
.
11 With Syntax and an example explain how explicit conversion is performed.
.
12 Briefly explain with an example:
. a) Syntax errors
b) Logical Errors
c) Runtime errors
Exercises Questions

1. Which of the following identifier names are invalid and why?

i. Serial_no. v Total_marks

ii. 1st_Room vi. total_Marks

iii. Hundred$ vii. _Percentage

iv. Total Marks viii True

Ans
:

2. Write the corresponding Python assignment statements:


a) Assign 10 to variable length and 20 to variable breadth.
b) Assign the average of values of variables length and breadth to a variable sum.
c) Assign a list containing strings ‘Paper’, ‘Gel Pen’, and ‘Eraser’ to a variable
stationery.
d) Assign the strings ‘Mohandas’, ‘Karamchand’, and ‘Gandhi’ to variables
first, middle and last.
e) Assign the concatenated value of string variables first, middle and last to
variable fullname. Make sure to incorporate blank spaces appropriately
between different parts of names.
Ans
:

3. Write logical expressions corresponding to the following statements in Python


and evaluate the expressions (assuming variables num1, num2, num3, first,
middle, last are already having meaningful values):
a) The sum of 20 and –10 is less than 12.
b) num3 is not more than 24.
c) 6.75 is between the values of integers num1 and
num2.
d) The string ‘middle’ is larger than the string ‘first’ and
smaller than the string ‘last’.
e) List Stationery is empty.

Ans
:

4. Add a pair of parentheses to each expression so that it evaluates to True.


a) 0 == 1 == 2
b) 2 + 3 == 4 + 5 == 7
c) 1 < -1 == 3 > 4
Ans
:

5. Write the output of the following:


a) num1 = 4
num2 = num1 + 1
num1 = 2
b) num1, num2 = 2, 6
num1, num2 = num2, num1 + 2
print (num1, num2)
c) num1, num2 = 2, 3
num3, num2 = num1, num3 + 1
print (num1, num2, num3)

Ans
:

6. Which data type will be used to represent the following data values and why?
a) Number of months in a year
b) Resident of delhi or not
c) Mobile number
d) Pocket money
e) Volume of a sphere
f) Perimeter of a square
g) Name of the student
h) Address of the student.

Ans . Int data type


: a. Boolean data type
b. Int data type
c. Float data type
d. Float data type
e. float data type
f. String data type
g. String data type

7. Give the output of the following when num1 = 4, num2 = 3, num3 = 2


a) num1 += num2 + num3
print (num1)
b) num1 = num1 ** (num2 + num3)
print (num1)
c) num1 **= num2 + num3
d) num1 = '5' + '5'
print(num1)
e) print(4.00/(2.0+2.0))
f) num1 = 2+9*((3*12)-8)/10
print(num1)
g) num1 = 24 // 4 // 2 print(num1)
h) num1 = float(10)
print (num1)
i) num1 = int('3.14')
print (num1)
j) print('Bye' == 'BYE')
k) print(10 != 9 and 20 >= 20)
l) print(10 + 6 * 2 ** 2 != 9//4 -3 and 29
>= 29/9)
m) print(5 % 10 + 10 < 50 and 29 <= 29)
n) print((0 < 6) or (not(10 == 6) and (10<0)))

Ans . 9
: a. 1024
b. Syntax Error
c. 55
d. 1.0
e. 27.2
f. 3
g. 10.0
h. ValueError
i. False
j. True
k. True
l. True
m. True

8. Categorize the following as syntax error, logical error or runtime error:


a) 25/0
b) num1 = 25; num2 = 0; num1 / num2

Ans a) Run Time Error (ZeroDivisionError:division by zero)


: b) Run Time Error(ZeroDivisionError:division by zero)

9. A dartboard of radius 10 units and the wall it is hanging on are represented using a two-
dimensional coordinate system, with the board’s center at coordinate (0,0). Variables x
and y store the x-coordinate and the y-coordinate of a dart that hits the dartboard. Write
a Python expression using variables x and y that evaluates to True if the dart hits (is
within) the dartboard, and then evaluate the expression for these dart coordinates:
a) (0,0)
b) (10,10)
c) (6,6)
d) (7,8)

Ans
:

10. Write a Python program to convert temperature in degree Celsius to degree Fahrenheit.
If water boils at 100 degree C and freezes as 0 degree C, use the program to find out
what is the boiling point and freezing point of water on the Fahrenheit scale.
(Hint: T(°F) = T(°C) × 9/5 + 32)

Ans Program to convert degree Celsius to degree Fahrenheit is


: TC =0
TF = 0
TC = int(input(“Enter temperature in degree Celsius”))
TF = 9/5 * TC + 32
print(TF)
If input is 100 the output will be 212.0
If the input is 0 then output will be 32.0

11. Write a Python program to calculate the amount payable if money has been lent on
simple [Link] or money lent = P, Rate of interest = R% per annum and Time =
T years. Then Simple Interest (SI) = (P x R x T)/ 100.
Amount payable = Principal + SI.
P, R and T are given as input to the program.

Ans
:

12. Write a program to calculate in how many days a work will be completed by three
persons A, B and C together. A, B, C take x days, y days and z days respectively to do the
job alone. The formula to calculate the number of days if they work together is xyz/(xy
+ yz + xz) days where x, y, and z are given as input to the program.

Ans
:

13. Write a program to enter two integers and perform all arithmetic operations on them.
Ans
:

14. Write a program to swap two numbers using a third variable.

Ans
:

15. Write a program to swap two numbers without using a third variable.
Ans
:

OR

16. Write a program to repeat the string ‘‘GOOD MORNING” n times. Here ‘n’ is an integer
entered by the user.

Ans n=int(input(“Enter how many times you want to repeat?”))


: print(“GOOD MORNING” *n)

17. Write a program to find the average of three numbers.


Ans
:

18. The volume of a sphere with radius r is 4/3πr3. Write a Python program to find the
volume of spheres with radius 7cm, 12cm, 16cm, respectively.

Ans print(“Volume of a Sphere when radius is 7cm is “,4/3 * 22/7 * 7*7*7)


: print(“Volume of a Sphere when radius is 12cm is “,4/3 * 22/7 * 12*12*12)
print(“Volume of a Sphere when radius is 16cm is “,4/3 * 22/7 * 16 *16*16)

19. Write a program that asks the user to enter their name and age. Print a message
addressed to the user that tells the user the year in which they will turn 100 years old.

Ans
:

20. The formula E = mc2 states that the equivalent energy (E) can be calculated as the mass
(m) multiplied by the speed of light (c = about 3×108 m/s) squared. Write a program
that accepts the mass of an object and determines its energy.

Ans
:

21. Presume that a ladder is put upright against a wall. Let variables length and angle store
the length of the ladder and the angle that it forms with the ground as it leans
against the wall. Write a Python program to compute the height reached by the
ladder on the wall for the following values of length and angle:
a) 16 feet and 75 degrees
b) 20 feet and 0 degrees
c) 24 feet and 45 degrees
d) 24 feet and 80 degrees

Ans
:

HOTS

1 Schools use “Student Management Information System” (SMIS) to manage


student-related data. This system provides facilities for:
• recording and maintaining personal details of students.
• maintaining marks scored in assessments and computing results of
students.
• keeping track of student attendance.
• managing many other student-related data. Let us automate this
process step by step.
Identify the personal details of students from your school identity card and
write a program to accept these details for all students of your school and
display them in the following format.
Ans: name_of_school = input (“Enter the name of the School:- “)
stu_name = input(“Enter the name of the Student:- “)
roll = int(input(“Enter the Roll Number:- “))
class = input(“Enter the Class:- “)
address = input(“Enter the Address:- “)
city = input(“Enter the City name:’ “)
pin = int(input(“Enter the Pin Code:- “))
phone = int(input(“Enter the Parent Phone number:- “))
print()
print( “| “, name_of_school)
print(“|”)
print(“| Student Name:- “, stu_name, “ Roll No:- “, roll)
print(“| Address:- “, address)
print(“|”)
print(“| City:- “, city, “ Pin Code:- “, pin)
print(“| Parent’s/ Guardian’s Contact No:- “, phone)
print(“-” *60)

Lab Program - 1

1 Write a program to swap two numbers using a third variable.


print("Enter the first number: ")
x=input()
print("Enter the second number:")
y=input()
temp=x
x=y
y=temp
print("The value of x and y after swapping:",x)
print("The value of y after swapping:",y)

2 Write a program to enter two integers and perform all arithmetic operations on
them.
# Python Program to Perform All Arithmetic Operations on Two Given Numbers
print("Enter any two positive integer numbers:")
p, q = int(input()), int(input())
sum, sub, mul, mod, div = 0, 0, 0, 0, 0
sum = p + q
sub = p - q
mul = p * q
div = p / q
mod = p % q
print("\n")
print("SUM ", p, " + ", q, " = ", sum)
print("DIFFERENCE ", p, " - ", q, " = ", sub)
print("PRODUCT ", p, " * ", q, " = ", mul)
print("QUOTIENT ", p, " / ", q, " = ", div)
print("MODULUS ", p, " % ", q, " = ", mod)

3 Write a python program to accept length and width of a rectangle and compute
its perimeter and area
print("Enter Length of Rectangle: ")
l = int(input())
print("Enter Breadth of Rectangle: ")
b = int(input())
p = 2*(l+b)
a=l*b
print("\nPerimeter = ", p)
print("\nArea=",a)

4 Write a python program to calculate the amount payable if money has been lent
on Simple Interest. Principal or money lent=P,Rate of interest=R% per annum and
Time=T years. Then Simple Interest(SI)=(P*R*T)/100.
Amount Payable = Principal + SI
P,R and T are given as input to the program.

P = float(input('Enter the principal: '))


R = float(input('Enter the rate of interest per annum: '))
T = float(input('Enter the time in years: '))
SI = (P * R * T)/100
amount = SI + P
print('Total amount:',amount)

Multiple Choice Questions

1. An ordered set of instructions to be executed by a computer to carry out a specific


task is called a .
Program Instruction Code None of the above

2. Computers understand the language of 0s and 1s which is called .


Machine language Low level language Both a) and b) None of the above

3. A program written in a high-level language is called .


Language Source code Machine code None of the above

4. An interpreter read the program statements .


All the source at a time One by one Both a) and b) None of the above

5. Python is a
Low level language High level language Machine level language All of the above

6. Python is .
Open source language Free language Both a) and b) None of the above

7. Python support .
Compiler Interpreter Assembler None of the above

8. Python programs are .


Easy to understand Clearly defined syntax Relatively simple structure All of the above

9. Python is .
a. Case – sensitive
b. Non case – sensitive
c. Both a) and b)
d. None of the above

10. Python is platform independent, meaning .


It can run various operating systems It can run various hardware platforms Both a) and b)
None of the above

11. Python uses indentation for .


Blocks Nested Blocks Both a) and b) None of the above

12. To write and run (execute) a Python program, we need to have a .


Python interpreter installed on the computer We can use any online python interpreter
Both a) and b) None of the above

13. The interpreter is also called python .


a. Shell
b. Cell
c. Program
d. None of the above

14. To execute the python program we have to use .


Interactive mode Script mode Both a) and b) None of the above

15. allows execution of individual statements instantaneously.

Interactive mode Script mode Both a) and b) None of the above

16. allows us to write more than one instruction in a file called


Python source code.
Interactive mode Script mode Both a) and b) None of the above

17. To work in the interactive mode, we can simply type a Python statement on the
prompt directly.
>>> >> > None of the above

18. In the script mode, we can write a Python program in a , save it


and then use the interpreter to execute it.
a. Prompt File Folder All of the above

19. By default the python extension is .

a. .py
b. .ppy
c. .pp d. .pyy
20. are reserved words in python.

a. Keyword
b. Interpreter
c. Program
d. None of the above

21. The rules for naming an identifier in Python are .


Name should begin with an uppercase, lowercase or underscore It can be of any length
It should not be a keyword All of the above

22. To define variables in python special symbols is not allowed.


@ # and ! $ and % All of the above

23. A variable in a program is uniquely identified by a name .


a. Identifier
b. Keyword
c. Code
d. None of the above
24. Variable in python refers to an .
Keyword Object Alphabets None of the above

25. The variable message holds string type value and so its content is assigned within
.
Double quotes “” Single quotes ” Both a) and b) None of the above

26. must always be assigned values before they are used in


expressions.
Keyword Variable Code None of the above

27. are used to add a remark or a note in the source code.


Keyword Source Comment None of the above

28. are not executed by a python interpreter.


Keyword Source Comment None of the above

29. In python comments start from .


# @ % $
30. Python treats every value or data item whether numeric, string, or other type
(discussed in the next section) as an .
Object Variable Keyword None of the above

31. identifies the type of data values a variable can hold and the
operations that can be performed on that data.
Data type Data base Both a) and b) None of the above

32. Number data type classified into .


Int float complex All of the above

33. data type is a subtype of integer a.


[Link]
b. string
c. list
d. None of the above

34. A Python sequence is an ordered collection of items.


Number Sequence Both a) and b) None of the above

35. Sequence data type is classified into .


Strings Lists Tuples All of the above

36. is a group of characters in python.


Number String Boolean All of the above

37. In the string data type you can store .


Alphabets Digits Special character including space All of the above

38. is a sequence of items separated by commas and the items are


enclosed in square brackets [ ].
List Tuple String None of the above

39. is a sequence of items separated by commas and items are


enclosed in parenthesis ( ).
List Tuple String None of the above
40. is an unordered collection of items separated by
commas and the items are enclosed in curly brackets { }.
List Set String None of the above

41. data type cannot have duplicate entries.


List Set String None of the above

42. None is a special data type with a single value. It is used to


signify the absence of value in a situation.
List Set String None

43. in Python holds data items in


key-value pairs.

Dictionary Set String None

44. Items in a dictionary are enclosed in .


Parenthesis () Brackets [] Curly brackets {} All of the above

45. In the dictionary every key is separated from its value using
a

a. Colon (:)
b. Semicolon (;)
c. Comma (,)
d. All of the above

46. Variables whose values can be changed after they are created
and assigned are called .
Immutable Mutable Both a) and b) None of the above

47. Variables whose values cannot be changed after they are


created and assigned are called .
Immutable Mutable Both a) and b) None of the above

48. When we need uniqueness of elements and to avoid


duplicacy it is preferable to use .
List Set Tuple All of the above
49. The values that the operators work on are called
.

a. Operands
b. Assignment
c. Mathematical Operator
d. All of the above

50. that are used to perform the four basic


arithmetic operations as well as modular division, floor
division and exponentiation.

a. Arithmetic Operator
b. Logical Operator
c. Relational Operator
d. All of the above

51. calculation on operands. That is, raise the


operand on the left to the power of the operand on the right.
Floor Division (//) Exponent (**) Modulus (%) None of the above

52. compares the values of the operands on


either side and determines the relationship among them.
Arithmetic Operator Logical OperatorRelational Operator All of the above

53. assigns or changes the value of the variable on its left.


Relational Operator Assignment Operator Logical Operator All of the above

54. Which one of the following logical operators is supported by python.


And or not All of the above

55. operator is used to check both the


operands are true.

a. and
b. or
c. not
d. All of the above
56. are used to determine whether the value of a
variable is of a certain type or not.
Relational Operator Logical Operator Identity Operator All of the above
57. can also be used to determine whether two
variables are referring to the same object or not.
Relational Operator Logical Operator Identity Operator All of the above

58. Membership operators are used to check if a value is a


member of the given sequence or not.
Identity Operator Membership Operator Relational Operators All of the above

59. An is defined as a combination of constants,


variables, and operators.
Expressions Precedence Both a) and b) None of the above

60. Evaluation of the expression is based on of operators.


Expressions Precedence Both a) and b) None of the above

61. Example of membership operators.


In not in All of the above

62. Example of identity operators.


Is is not Both a) and b) None of the above

63. In Python, we have the function for taking the user input.
prompt() input() in() None of the above

64. In Python, we have the function for displaying the output.


prompt() output() print() None of the above

65. , also called type casting, happens when data


type conversion takes place because the programmer forced it in
the program.
Explicit conversion Implicit conversion Both a) and b)
None of the above

66. , also known as coercion, happens when data type


conversion is done automatically by Python and is not instructed by
the programmer.
Explicit conversion Implicit conversion Both a) and b) None of the above

67. A programmer can make mistakes while writing a program,


and hence, the program may not execute or may generate wrong
output. The process of identifying and removing such mistakes,
also known as .
Bugs Errors Both a) and b) None of the above

68. Identifying and removing bugs or errors from the program is


also known as .
Debugging Mistakes Error None of the above

69. Which of the following errors occur in python programs.


Syntax error Logical error Runtime error All of the above

70. A produces an undesired output but without


abrupt termination of the execution of the program.
Syntax error Logical error Runtime error All of the above

71. A causes abnormal termination of the


program while it is executing.
Syntax error Logical error Runtime error All of the above

72. Python is language that can be used for a


multitude of scientific and non-scientific computing purposes.
Open – source High level Interpreter – based All of the above

73. Comments are statements in a program.


Non – executable Executable Both a) and b) None of the above

74. is a user defined name given to a variable


or a constant in a program.
Keyword Identifier Data type All of the above

75. The process of identifying and removing errors from a


computer program is called .
Debugging Mistakes Error None of the above

You might also like