0% found this document useful (0 votes)
25 views10 pages

Chapter - 4

Uploaded by

arifalam78709
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)
25 views10 pages

Chapter - 4

Uploaded by

arifalam78709
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/ 10

fndontl,

SOLVED QUESTIONS Cho4 hn n


1. What are tokens in Python? How many types of tokens are allowed in Python?
Ans. Token is the smallest individualunit in a program.
Types of tokens allowed in Python are as follows:
la) Keywords: False, True, for, while
(b) identifiers: a, A, Ist, dict1
(c) Literal: "python", 5, 9, 'class11'
(d) Operator: +, -, /,, **, %, |/
(e) Punctuators: &, ^, ?, #, @, !
2. What are the different cormponents of avariable?
Ans. A variabie has three main components:
(a) identity (rmernoryaddress) of the variable
(b) Type (data type) of the variable
(c) Value of the variable

4.42 Computer Science with Python-XI


aConsider the following statements in Python interpreter and describe the output/statement required:
la) Print a message "Hello World"
(b) a = 10
b = 12
= a b
C
print (c)
(c) To retrieve the data type of the inputted string "Hello" stored inside the variable 'a'
(d) To describe the data type of variable "b'!.
le) To retrieve the address of variables a and b.
(f) State the output:
>>> b= 12
>>> d = b

>>> id (d)
>>> id (b)
g) >>> a = " Hel lon
10
(h) To display the value for a', a anda.
(i) >>> a = 15
>>> b = 4
>>> a/b
>>> a/ /b
assignment statements.
variables,a and b, using multiple
) To swap the values of two
d=10,27,4+5,10-7
(k) >>> a,b, c,
>>> a//d
>>> d**d
>>> b/c
>>> a + b t c - d

("Hello World")
Ans. (a) >>> print
Hello World
(b) >>> a = 10
>>> b = 12
>>> c = a +
>>> print (c)
22
(c) >>> a = "Hello"
>>>type (a)
<class ' s t r ' >

(d) >>> type (b)


<class 'int '>
(e) >>> id (a)
52193248
>>> id (b)
1616896960
(() >>> d = b
>>> d
12
>>> b
12
>>> id (d)
1616896960

>>> id (b)
1616896960
4.43
()>>> a "He)lo" lo!
i H e i l o H e l

ie, He:
Me He
He Hei He He

(h)>>a

a,E,3, o=10,27,4-5,10-5

>>>

43
4. Which of the following
identifier names are invalid and why?
(a) Sera-1.
(b) 1st Room (NCERT
(C, FdredS
(d) Total Marks
e) tal Marrs
B) Fercentage (f) total-Marks
Ans. Foliowing identifier (h) True
names are invalid:
S.No. Invalid ldentifier
Reason
(a) Serial no.
(b) lst koo Identifier cannot contain
(c) HundredS Identifier name cannot special symbol
(d) Total Marts ldentifier cannot containbegin with number
(f) total-Mar ks ldentifier cannot contain special symbol
(h) TIue ldentifier cannot contain space
5. What is the difference ldentifier cannot be a special symbol
Ans. The reserved words of
between a keyword
and a keyword
have aspecialvariable?
Python, which
Keywords are reserved words
that can be fixed
been defined. For example,
for, if, used in our meaning for the
interpreter, are called they
Variable is the user-defined name elif, else, def, True, program only for the
keywords.
have
reserved. These are defined by the given to a value thatFalse, etc. purpose for which
is stored
must begin with either a letter or user but they can in the
have memorv. Variables
underscore. For example,letters, digits and fixed/
are not

4.44 _age, name, the symbol underscore. They

result_1, etc.
What is a function? How is it useful?
in Pvthon is a named
block of statements within
function

Ans. A a program that performs a specific task.


example, the following program
For ex has afunction within it,
# prog .py namely greet_msg).
def greet msg():
print ("Hello there!|")
name = input ("Your name : ")
print (name, qreet msg ))
Functions are useful as they can be reused anywhere by invoking the function. So, for the
functionality, one need not rewrite the
same
code every time it is needed, rather,
again. through functions it can be
used again and
followine:
7 Find the error in the
def minus (total, decrement )
output = total decrement
return output

Ans. The function header has colon missing at the end and the following two statements are not indented. So, we
oedto add colon (:) at the end of the header line and indent the two lines following the
function header.
Thus, the corrected code will be:
def minus (total, decrement):
output = total decrement
retun output
8Differentiate between mutable and immutable objects.
Ans. Mutable object: Objects whose values can be changed after they are created and assigned values are
called mutable objects. For example, list, dictionary, etc.
Immutable object: Objects whose values cannot be changed after they are created and assigned values are
called immutable objects. For example, int, float, string, tuple, etc.
9. Ritu is confused between 3*2 and 3**2. Help her know the difference between the two expressions.
Ans. The statement 3*2 multiplies 3 by 2 and produces the result 6 while 3**2 calculates 3 raised to the
power 2 and produces the result 9.
10. How many types of strings aresupported in Python?
Ans. Python allows two types of strings:
la) Single line Strings-Strings that are terminated in a single line enclosed within single and double
quotes.
(b) Multiline Strings-Strings storing multiple lines of text enclosed within three single or double quotes.

11. Differentiate between implicit and explicit type conversion.


Ans. Implicit type conversion is a conversion performed by the compiler without the programmer's
expression
intervention. It is applied generally whenever multiple data types are intermixed in an
(mixed mode expression)to not lose information.
expression to aspecific type. It is also
txplicit type conversion is user-defined conversion that forces an
known as type casting.
12. What are variable-naming conventions?
Ans. Following are the rules that need to be followed while naming variables:
underscore followed by any number of digits
and/or letters.
(a) A Variable must start with a letter or
variable name.
(D) No reserved word or standard should be used as the
underscore) should be included in the variable name.
(J NO Special character (other than
(a) Variable names are case-sensitive.
13. What is None in Python?
that has not
one special data type called None. None data type is used to indicate something
rytnon has
yet been created, It is a non-NULL, unidentified value.

4.45
hon ProgrammingFundamentals
True',
following
literals.:
5: " f iv e " ) , "True",
14. ldentify the types of the "four ",
(4:
23.789, 237g9, True, 300])
[100,
200,
"Ealse", None,
False,. Floating point
Ans. 23. 789
integer
23789
Boolean
True Mapping (Dictionary)

"five")
14: "four " 5:
String
True
String
"True"
Sequence (Tuple)

Boolean
False
"False" String
None None
Sequence (List)
100,200, 300)
15. Write the corresponding Python statements:
value 200to variable b.
(a) AssIgn value 100to variable A and
(b) Assign value 10 to variables a, b and c.
x and assign the variable x to variable y.
(C) ASSIgn value 20 to x and delete 5 from
Ans. (a) A=100
B=200
(b) a=b=c=10
(c) x=20
X=X-5

y=x
16. Find the output generated by the following codes:
(a) x=2 (b) x=8
y=3 y-2
x+=y X+=y
print (x, y) Y-=X
Ans. 5 3 print (x,y)
Ans. 10 -8
(c) a=5
(d) p=10
b=10
q-20
at=a+b
b*=atb
p*=q//3
print (a,b) qt=ptq* *2
Ans. 20 300 print (p, )
Ans. 60 480
(e) p-5/2
q-p*4 (f) p=2 /5
I=ptq qp*4
pt=ptgtr r=ptq
rt=ptqtr pt=ptq-r
g-=ptq*r r*=p-qtr
print (P, q,) qt=ptq
Ans. 27.5 -642.5 62.5 print (p, q, r)
Ans. 0. 4
3.6 1.5999999999999996

4.46
Putor-t/

Computer Science with


17. What is the difference between an expression and a statement in Python?

Ans.

S. No. Expression Statement

(a) An expression is a combination of symbols, Statement is defined as any programming


operators and operands. instruction given in Python as per the syntax.
An expression represents some value. Statement is given to execute a task.
(b
The outcome of an expression is always a Statement may or may not return a value as the
(c) result.
value.
For example, 3 * 7+ 10 is an expression. For example, print ("Hello") is a statement.
(d)

ldentify
in the following Python statement and write the correct state ment.
the error
18.
print ("My name is", first name) is made
an undefined variable first name. The correction
Tho given statement is trying toprint the value of
defining the variable name before using it, i.e.,
= 'Rinky !
s>> first name
first name)
S>>print ("My name is", as the
to input value 15 and obtain 30
The following Code is not giving the desired output. We want
19
problem?
output. Could you identify the
Number:")
num = input ("Enter
result = num * 2
will
when we input the value 15, it
Print (result)
string, so
function as it returns value as a multiplied by 2, the
Ans. The problem is with input() and not as integer 15. So, when num variable is
string '15' used while accepting the input.
assign to num variable as problem, int() function is to be
and not 30. To solve this
output is '1515
Python; it should be print().
is not a valid statement of
Also, Print()
be:
The correct code will
("Enter Number:"))
num = int (input
result =num * 2
formula:
print (result) Fahrenheit using the
Celsius and convert it into
in
to obtain temperature
20. Write a program
F= C*9/5+32
Fahrenheit
Ans. #Celsius to Celsius :")
(input ("Enter
temp in
cels = float Celsius is :",
cels)
("Temperature in
print
32
f = cels * 9/5 + Fahrenheit is :", f)
("Temperature in
print
code?
output of the following
21. What willbe the
name = 'Neeru!

age = 21
"now but",)
"you are", 21,
print (name, 1, "next year")
be", age +
Print ("you will
given code will be:
Ans. The output of the
but
Neeru, you are 21 now
you will be 22 next year Explain.
following code?
will be the output of the
c2. What
X, y= 2, 6
X, y = y, x + 2
print (x, y) respectively.
variablesx and y, 6,4:
Ans. 6 4 assigns values 2
and 6 to is 6, 2 + 2, i.e.,
first line of code right-hand side, i.e., y, x + 2, which
txplangtion: The evaluates the
line) of code first gets 4.
The next line
(second so x gets 6 and y
i.e., x, y = 6, 4;
assigns this to x, y,
And then the output is 6 4.
The third line prints x and y so 447
ryhon Programming Fundamentals
Cost price and
23. Write a Python code to price of an item.
calculate and display the selling
accepted by the user.
Ans. cOstPrice = int (input ('Ent er cost phee
profit int (input ('Enter profit:')
SellingPrice cost Price t profit
print ('Selling Pri ce:', sellingPrice)
24. What will be the output of the following code?
A, B, C, D= 9.2, 2.0, 4, 1
print (A/4)
print (A 4)
print (B**)
print (A*B)
Ans. 2. 3
2.0
16.0
18.4

25. Evaluate (to True or False) each of the following expressions:


(a) 14 <= 14
(b) 14 < 14
(c) -14 > -15
(d) -15 >=15
Ans. (a) True
(b) False
(c) True
(d) False
26. Write logical expressions corresponding to
the
expressions (assuming values of variables as num1, following statements in Python and evaluate the
num2, num3, first, middle, last):
(a) The sum of 20 and -10 is less than 12. (NCERT)
(b) num3 is not more than 24 OR num3 < 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
(e) Declare an empty list Stationery. string 'last'.
Ans. (a) 20+ (-10) < 12
(b) not (num3 > 24)
(c) (6.75 > numl) and
(6.75 < num2 )
(d) (middle > first)
and (middle < last)
(e) Stationery == [ ]
27. A year is a leap year if it
is
are also divisible by 400. divisible by 4, except that years divisible by
Write aprogram that asks 100 are not leap years
or not. the user for a year and unless
print whether it is a leap Y
Ans. vear = int (input
("Please Enter the Year
if vear%400 == 0 or Number you wish: "))
year% 4 == 0 and year%100
print (year, "is a Leap Year") != 0 :
else:
print (year, "is Not a Leap Year")
28. Write a ryurnon program
display total price. that accepts cost orice and
ouantity of oencil from the user.
Calculdte
Ans. costprice = int
(input ('Ent et
aty = int (input ('Ent
er uant t
totalpriceCOst p ice t y
print ("Tot à l price is:"
DIice)
29. Assume that a ladder is put
upright
ladder and the angle that it forms against a wall (et variables length arnd angle store the length ot the
with the ground as it leans against
compute the height reached by the ladder on the wall Write a Python prograrn to
the wall for the following values of
(a) 16feet and 75 degrees length and angje
(b) 20feet and 0 degree
(c) 24 feet and 45 degrees
(d) 24 feet and 8O degrees
Ans. import math (NCERT)
enath 1nt nput "EnteI the
anaind lengthof ladder: ")
1nt input "Enter the angle
in dearoe: "
anginr =math.iàdiàns (angind)
sin =math. Sln (anginr)
heioht iound (length sin, 2)
nrint("The height reached by ladder ",
height)
30. Write aprogram 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. (NCERT)
Ans. nm =input ("Enter Your Name")
age = int (input ("Enter Your age") )
VI = 2025 + (100 - age) #Taking 2025 as Current Year
print (nm, ":You will turn 100 in", yr)
31. Differentiate between Syntax and Runtime errors. Give an appropriate example.
Ans. Syntax Error: Violation of formal rules of a programming language such as misspeling a keyword or
incorrect indentation, etc., results in syntax error.
For example,
len ('hello') = 5
File "<stdin>", line 1
SyntaxError: can't assign to function call
Runtime Error: These errors are generated during a program execution due to resource limitation such as
division by zero, trying to access an identifier or file which doesn't exist, etc. Python has provision of
check points to handle these errors known as Exception Handling.
For example,
a=10

C=a/b
WOuld result in
ZercDivisicnError: division by zero
32. Explain R-value and L-value using example. to L-vaiue
the left side of an assignment operator refers
Ans. In a normal expression. the variable to operator
addressable. The expressionafter the assignment
(lett-value)because it resides in memoryand is identifiable location in
represent an object occupying some
refers to R-value (right-value). It does not
memory.
an L-Value
# X is
For example, X=1
an L-value
Y=20 # Y is
R-Value
Z=X+Y # X+Y is an

4.49
Python Programming Fundamentals
33. Write the outout of the following
a) numl 4

num2 num1
(num , num2 )
numl PIint

(b) numl , n u m ,6
num1, Dum num
Drint (numl, num2)

(c) numl, num


num ? 1
num3, num? numl
num 3 )
Pint (num1, numz,
Ans. (a) 4 5
(b) 6 4
'num 3' is not de f ined
(c) NameEr IOr: name

34. Write a program to swap two numbers using a third varidbie. (NC
AnS. a int (input ("Enter First Number"))
b- int (input ("Enter Second Number"))
print ("Before Swapping Values are")
print ("Value of First Variable a is", a)
print ("Value of Second Variable b is", b)
C= a
a = b
b= C

print ("After Swapping Values are")


print ("Value of First ariable a is", a)
print ("Value of Second Variable b is", b)
35. Write a program to swap twonumbers without using athird variable. (NO
Ans. a= int (input ("Enter First Number") )
b = int (input ("Enter Second Number"))
print ("Before Swapping Values are")
print ("Value of First Variable a is", a)
print ("Value of Second Variable b is", b)

b= a - b
a = a - b
print ("After Swapping Values are")
print ("Value of First Variable a is", a)
print ("Value of Second Variable b
is", b)
OR
a = int(input ("Enter First
Nunber"))
b = int (input ("Enter
SeCond Numbe r") )
print ("Before Swapping Values
are")
print ("Value of FiIst Variable a
i_" a)
print ("Value of Second
Variable b is", b)
a, b = b, a
print ("After Swapping Values are")
print ("Value of First Variable a
is" al
print ("Value of Second Variable b i

4.50
Computer Science with Pythe
36. Givethe output of the
following expressions:
(a) (5<10) and
(10<5) or (3<18) and not R- 18
(b) A, B, C=9,12,3
X-A-B/3+C*2-1
Y-A-B/ (3+C) *(2-1)
Z=A- (B/ (3+C) *)-1
print ("X-", X)
print ("Y", Y)
print ("", )
Ans. (a) False
(b) N-10.0

Z-4.0

ASSERTION AND REASONING BASED QUESTIONS


The following questions contain two statements: Assertion and Reasoning. Each question has
four
(0), (i), (iüi), (iv)-only one of which is correct. In the light of these statements, choose the most choices
option.
appropriate
(i) Both A and R are true and R is the correct explanation of A.
(i) Both AandR are true but R is not the correct explanation of A.
(iii) A is true butR is false.
(iv) A is false but R is true.

1. Assertion (A): Each component of a programming statement is known as a token.


Reasoning (R): Token is not executed by Python interpreter, only used in program coding.
2. Assertion (A): Python is a dynamically typed language.
Reasoning (R): The data type of a variable is declared as per the type of value assigned to it.
3. Assertion (A): In Python, strings, lists and tuples are called sequences.
Reasoning(R): Sequence is referred to as an ordered collection of values having similar or different data
types.
4. Assertion (A): Comments are non-executable statements that are ignored by the interpreter
Reasoning (R):Comments are used to explain the code and to make it more informative for the users. They
are basically statements used to put remarks.
5. Assertion (A): Aset of valid characters recognized by Python constitutes a character set.
Reasoning (R): Character set in Python is a subset of Python tokens.
6. Assertion (A): 'Rollnumber and rollnumber' are same identifiers.
Reasoning (R): Python is a case-sensitive language.
7. Assertion (A): Literals are same as identifiers.
Reasoning (R): A variable is a label for a location in memory.
4. () 5. (i) 6. (iv) 7. (iv)
Ans. 1. (i) 2. (i) 3. (i)

4.51
Python Programming Fundamentals

You might also like