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

Python Fundamrntal Book Questions

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Python Fundamrntal Book Questions

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Chapter 4 : PYTHON FUNDAMENTALS 91

Program to obtain three numbers and print their sum.

rogram # to input 3 numbers and print their sum


num1int( input("Enter number 1: "))
num2 int( input("Enter number 2 : "))
num3 int(
input("Enter number 3: "))
Sum num1 + num2 + num3
print("Three numbers are: ", num1, num2, num3)
print("Sum is: ", Sum)
The output produced by above program is as
shown below:
Enter number 1 7
Enter number 23
Enternumber 3: 13
Three numbers are 7 3 13
Sum i s : 23

Program to obtain length and breadth of a rectangle and calculate its area.
1.2
rogram
# to input length and breadth of a rectangle and calculate its area
length float( input("Enter length of the rectangle: "))
breadth float ( input ("Enter breadth of the rectangle: "))
area = length * breadth

print ("Rectangle specifications ")


print (" Length ", length, end = *)
print ("breadth = ", breadth)

print ("Area = ", area)

is
The output produced by above program as
shown below:

Enter length of the rectangle: 8.75


Enter breadth of the rectangle: 35.0

Rectangle specifications
Length 8.75 Breadth = 35.0
Area = 306.25

4.3 and GST and then print Invoice along with both CGST and SGST
Program to get selling price rate

values.
lrogram
INFORMAT CS PRACTI
92
sgst: state govt gst *
central govt gst
s SP: selling price cgst:
item n a m e : ")
item input("Enter item "+ item +": ") )
("Enter selling price of
SP float (input
"Enter GST rate (%): "))
gstRate float (input (
cgst SP* ( (gstRate/2)/ 100)
sgst cgst
will buy at this price
amount = SP + Cgst + sgst # consumer

print ("\t INVOICE")

print("Item: ", item)


print("Price: ", SP)
print(" CGST (@", (gstRate/2), "%) :",cgst)
print(" SGST (@ (gstRate/2), "%): ", sgst)
print("Amount payable: ", amount)

The output produced by above program is as shown below

Enter item name : Head Phones


Enter selling price of item Head Phones 2195
Enter GST rate (%) : 18

INVOICE

Item Head Phones


Price 2195.0
CGST (@ 9.0 %) : 197.55
SGST (@ 9.0 %) 197.55
Amount payable 2590.1000000000004

LET US REVISE

APythonprogram can contain various components like expressions, statements, comments, ndéemt
An
functions,
expression is a legal combination of symbols that represents a value.
A statement is a programing instruction.

Comments are non-executable, additional information added in


In Python,
program for readability.
comments begin with a# character.
Commentscan be single-line comment, multi-line comments and inline
comments.
Function is a named code that can be reused with a
program.
A block/suite/code-block is a group of statements that are
Blocks
part of another statement.
represented through indentation.
are

A variable in
Python is defined only when some value is
assigned to it.
Python supports dynamic typing i.e., a variable can hold values
The input() is used to obtain of difjerent types at different e
input from user; it always returnsa string type of
Output is generated through print( ) (by calling print value.
function) statement.
Chapter 4: PYIHON FUNDAMENTALS 93

Solved Problems

1, What is the difference between a keyword and an identifier?


Solution. Keyword is a special word that has a special meaning and purpose. Keywords are reserved
and are a few. For exanmple, it, elit, else etc. are keywords.
Identifier is a user-defined name given to a part of a program viz. variable, object, function etc.
ldentifiers are not reserved. These are defined by the user but they can have letters, digits and a
symbol underscore. They must begin with either a letter or underscore. For instance, _chk, chess, trial
etc. are identifiers in Python.

. What are literals in Python ? How many types of literals are allowed in Python ?
Solution. Literals mean constants i.e, the data items that never change their value during a program
run. Python allows five types of literals:
) String literals
(i) Numeric literals
(ii) Boolean literals
(iv) Special Literal None
(o) Literal Collections like tuples, lists etc.

3. How many ways are there in Python to represent an integer literal ?


Solution. Python allows three types of integer literals:
(a) Decimal (base 10) integer literals
(b) Octal (base 8) integer literals
() Hexadecimal (base 16) integer literals
(a) Decimal Integer Literals. An integer literal consisting of a sequence of digits is taken to be
decimal integer literal unless it begins with 0 (digit zero).
For instance, 1234, 41, +97, -17 are decimal integer literals.
(b) Octal Integer Literals. A sequence of digits starting with 0o (digit zero followed by letter o)
is taken to be an octal integer. For instance, decimal integer 8 will be written as 0o10 as octal integer.
(810=10g) and decimal integer 12 will be written as 0o14 as octal integer(1210 =14)
)Hexadecimal Integer Literals. A sequence of digits preceded by 0x or 0X is taken to be an
hexadecimal integer.
For instance, decimal 12 will be written as 0XC as hexadecimal integer.
Thus number 12 will be written either as 12 (as decimal), Oo14 (as octal) and 0XC (as hexadecimal).

4 What will be the sizes of following constants:


\a, "la", "Reemal's", ' \ ' "it's", "XY\ XYJ
YZ" YZ"

Solution.
Size is 1 as there is 1 character (escape sequence) and it is a string literal enclosed in

single quotes.
Size is 1 as there is 1 character enclosed in double quotes.
"\a"
94 INFORMAT PRACi
is string having 7characters enclosed
"Reema's" Size is 7 because it a
in double quoke
for apostrophe and is considered a sinol
escape sequence
Size is 1. It is a character constant and is containing just one character
character.)
Size is 4. Python allows single quote without escape sequence in a d
"it's"
single string e.g, 'nuoeto
and a double without escape sequence in a quoted quoe
quote

"xy\ Size is 4. It is a multi-ine string create with in the basic string


yz"
" " xy J

vz"" Size is 5. Triple quoted multi-line string, EOL ( ) character is also counteds
ted in
5. How many types of strings are supported in Python ?
Solution. Python allows two string types
) Single-line Strings Strings that are terminated in single line
(i) Multi-line Strings Strings storing multiple lines of text.
6. How can you create multi-line strings in Python?
Solution. Multi-line strings can be created in two ways:
(a) By adding a backslash at the end of normal single-quote or double-quote strings eg,
Text "Welcome \
To
Python"
(6) By typing the text in triple quotation marks. (No backslash needed at the end of line)=
Str1= "u u " Welcome

To

Python

7. What factors guide the cnoice of identifiers in programs ?


Solution.
(i) Anidentifier must start with a letter or
underscore followed by any number of dugi
(i) No reserved word or standard identifier
should be used.
(ii) No special character (other than underscore) should be included in the iatentitier.
8 Write the
following real constants in
exponent form: 17.251, 151.02, 0.00031, U.*0-
Solution.
(i) 17.251 =0.17251 104 x =

0.17251 E02
(ii) 151.02 =0.15102x10 =
0.15102E03
(iii) 0.00031 =0.31 10
=0.31E-3
(iv) 0.452 =0.0452 10 x = 0.0452E01

9. What is None literal in


Python ?
Solution. Python has one
special literal called None.
The None literal is used to S i m p l ew o r d s

indicate
absence of value. It is also used to something that has not yet beern crea
indicate the end of lists in
Python.
PYTHON FUNDAMENTALS 95
Chapter 4:

10. Identify the types of following literals:


23.789 23789 True True' "True"
False "False'" 0XFACE O0213 O0789

Solution.
23.789 Floating point
23789 integer
True Boolean
True' String
"True" String
False Boolean
"False'" String
OXFACE Integer (Hexadecimal)
00213 Integer(Octal)
00789 Invalid token ( beginning with 0 means it is octal number but digits
8 and 9 are invalid digits in ociai numbers)
None None

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

Solution
Expression Statement
Legal combination of symbols Programming instruction as per Python syntax

Represents something Does something


Python evaluates it Python executes it

End result is a value Need not result in a value

Example Examples:
2.3 print ("Hello")
(3+5)/ 4 i fa >0:

State
12. Which of the following are syntactically correct strings? reasons.

(a) "This course is great !"


"

(b) 'She shouted "Hello! very loudly.'

(c) "Goodbye
(d) 'This course is great !'
(e) "Hello
) " I 1iked the movie "Bruce Almighty' very much."
Solution. Strings (a), (b), (d) and () are syntactically correct. (Strings (b) and (f) are also valid as single

quote strings double--quotes inside them and vice versa.)


can use

don't match.
String (c) ( "Goodbye' ) is incorrect because opening and closing quotes
String (e) ("Hello) is invalid because it has no closing quotes.

statement ?
13. What is the error in following Python program with one

print ("My name is'", name)


Suggest a solution.
96
INFORMATIC PRACTICE
Solution. The above statement is trying to print the value of an
undefined
solution to above problem is to define the variable name before using it, ie
i.e., ariable name.
name 'Tanya'
print ("My name is", name)
14. The following code is not giving desired output. We want to input value as 20 and
nd obtoin
you pinpoint the problem? obtain ns

output as 40.0
Number input( "Enter Number")
DoubleTheNumber = Number * 2
Print (DoubleTheNumber)

Solution. The problem is that input() returns value as a string, so the input value 20 is reh
string '20' and not as
integer 20. So the returned
output is not 40.
Also Print() is not legal function of
Python; it should be print().
15. What would be the correction
forproblem of previous question ?
Solution. By using int( ) with
input(), we can convert the string into integer value, i.e., as
Number int(input ("Enter Number"))
DoubleTheNumber =Number *2
print (DoubleTheNumber)
Now the program will
print desired output as 40 if 20 is
typed
16.
as
input.
Why is following code giving errors ?
name "Rehman"

print ("Greetings ! !")


print ("Hello", name)
print ("How do you do ")
Solution. The problem with above
code is inconsistent inden
statement unless it is inside a suite indentation. In Python, we canno
and we can indent
Thus, corrected code will only as much is required.
be:
name = "Rehman"

print ("Greetings!!!")
print ("Hello", name)
print ("How do you do ?")
17. Write a
program to calculate profit percentage from the sales of
Solution. goods that you nmade.

cgos cost of goods sold


revenue amount
at which goods are sold
pl profit or loss

cgos =

float (input("Enter cost of goods sold:"))


Chapter 4: PYTHON FUNDAMENTALS 97

revenue= float (input( "Enter revenue amount: ")


pl revenue cgos
*
prPerc= pl /cgos 100
print("Cost of goods: ", cgos)
print("Revenuegenerated ", revenue)
print("Profit % : ", prPerc)

What will be the output produced by following code?


value = 'imar'
age = 17

print (name, ", you are", 17, "now but", end ")
print (" you will be ", age +1, "next year")
Solution.
Simar, you are 17 now but you will be 18 next year.

19. What will be the output offollowing code?


X, y=2, 6

X, y = y, x+2
print (x, y)
Solution.
6 4

Explanation. First line of code assigns values 2 and 6 to variables x and y respectively.
Next line (second line) of code first evaluates right hand side i.e, y, x+2 which is 6, 2+2 i.e., 6, 4
and then assigns this to x, y ie., x, y=6,4;so x gets 6 and y gets 4.
Third line prints x and y so the output is 6 4.

20. Predict the output of following:


x, y = 7, 2

X, y, X X*1, y +3, x+10


print (x, y)
Solution.
17 5

GLOSS ARY
Constant A dota item that never changes its value during a program run.

Identifier Name given by user for a part of the program.


Keyword Reserved word having special meaning and purpose.
Lexical Unit Other name of token.
Literal Constant.
Token The smallest individual unit in a
program
String literal Sequence of choracters enclosed in any type of quotes
Variable Named stored location whose value con be manipulated during program run.
Expression Legal combination of symbols that represents a value
INFORMAT PYA
98

Assignments
Selecded
Questions/Conceptual Questions
Answer
Type A: Short
1. What are tokens in Python ? How many types of tokens are allowed in Python 2

Examplify your answer SCa


identifiers?
2. How are keywords different from OR C
What are literals in Python ? How many types of literals are allowed in Python ?
4. Can nongraphic characters be used in Python ? How ? Give examples to support vour and
answem
5. How are floating constants represented in Python ? Give examples to support your answer.
6. How are string-literals represented and implemented in Python ?
7. Which of these is not
legal numeric type in Python ? (a) int (b) float (c) decimal.
a

8. Which argument of
print( ) would you set for:
() changing the default separator
(space)? (i) printing the following line in current line ?
9. What are
operators? What is their function ? Give examples of some
10. What is an
unary and binary opera
expression and a statement ?
11. What all
components can a Python program contain ?
12. What do you understand
13.
by block/code block/suite in Python ?
What is the role of indentation
Python ? in
14.
What are variables? How are they
15. What do important for a
program
you understand by undefined variable in
16. What is
Dynamic Typing feature of Python ? Python ?
17. What would
the
18. What is following code do: X =Y 7? =

the error in
19. following code X, Y 7? =

Following variable definition is


creating problem X =0281, find reasons.
Lomments are useful and
Elaborate with examples. easy way to enhance readability and understandability Oa

Type B: Application Based


*Onhe
Questions
(a) x = 55
following, find out which assignment
(b) y = 037
statement will produce an error. Stare
son(s) toa

(e) length =450.17 ()z =0o98


ic
(d) 56thnumber 3300
(h) float .17E )Taylor ="Instant' (g) this variable 87.E02
03 (i) FLOAT
=

=
0.17E 03
2
-

Find out
the
error(s) in
following code
temperature =90 fragmernts
(ii) a 30
print temprature b = a+ b
(ii) a, b, c 2, print (a And b)
8,9
print (a, b, c) X = 24
C,b, a =a, b, c (io)
4 X
print (a b; c)
() (vi) else = 21 5
print ("X ="
X)
Chapter 4: PYTHON FUNDAMENTALS 99
?
3. What will be the output produced by following code fragment (s)
X = 10 (i) first 2

X= X+ 10 second =3
third = first * second
X = X - 5

print (X) print (first, second, third)


X, Y = X - 2, 22 first first + second + third

print (X, Y) third second * first


print (first, second, third)

#side given as 7
ii) side =
int(input('side'))
area side * side

print (side, area)


4. What is the problem with the following code fragments ?

) a 3
print (a)
b 4
print (b)
S a+b

print (s)

(ii) name "Prejith"


age 26
print ("Your name & age are ", name + age)

(ii) a 3
S a+ 10
a = "New'"

a/10
5. Predict the output
X = 40

y X+ 1
X 20, y +X
print (x, y)
6. Predict the output
X, y = 20, 60

y, X,y =
X, y - 10, x+ 10

print (x, y)
7. Predict the output
() a,b 12, 13 (b) a, b = 12, 13

C, b a*2, a/2 print (print (a + b))


print (a, b, c)
100
INFORMATICS PRACTICES
8. Predict the output
a, b, c 10, 20, 30
P, 9, r=C - 5, a+ 3, b - 4

print ('a, b, c:', a, b, C, end = "")


print ('p, 9, r ' p, 9, r)
9. Find the errors in following code fragment

(a) y X+5 (b) print (x =y = 5) (c) a input("value")


print (x, Y) b a/2
print (a, b)
10. Find the errors in
following code fragment: (The input entered is XID
c
int(input ( "Enter your class") )
print ("Your class is", c)
11. Consider the following code:
name
input("What is your name?")
print (Hi', name, ',')
print ("How are you doing?")
was intended to print
output as
Hi <name>, How
are you doing?
But it is printing the output as
Hi <name>,
How are you doing?
What could be the problem ? Can you suggest the
12. Find the solution for the same?
errors in following code fragment:
C
input ( "Enter your class" )
print ('Last year you were in
13. What will be class") c -1
returned by Python as result of
(a) > type(®) following statements?
(6) »»
type(int (®) )
(d)>»type(
g)
"0°) () >>» type(1.0) ().type(int("0°)
type(float (0)) )
Match
>>»
type(float (1.0)) ()
» type(int (1.0))
your result after
executing above statements.
»»
type( 3/2)
14. What
will be the output produced by
following code?
(a)>str(print())+"One"
(b) str
>
(print ("hello")
)+"One"
Match your result after
15. What will be the
executing above statements.
Can you
output produced by explain why this result
ca
me?
() print following code ?
(b)
(print("Hola")
)
print (print ("Hola", end
*)) =
"

Match your result after


executing above statements. Can
you explain why this result came
ne?
PYTHON FUNDAMENTALS
101
Chapter 4:
shell. Why is the last assignment
16. Carefully look at the following code and its execution on Python
giving error ?

a =Bo12
>print(a)
10
>»b O013
>>C =078
File "<python-input-41-27fbe2fd265f>", 1ine 1
C 0078
A

SyntaxError:invalid syntax
17. Predict the output
a, b, c = 2, 3, 4

a, b, C=a*a, a*b, a*c


print(a, b, c)
variable. Consider the following code and tell if the
18. The id() can be used to memory address
get the of a
?
id() functions will return the same value or not (as the value to be printed via print))? Why
[There are four print( ) function statements that are printing id of variable num below)

num 13
print( id (num) )
num = num + 3

print(id(num))
num = num 3

print( id (num))
num "Hello"

print( id (num))
19. Consider below given two sets of codes, which are nearly identical, along with their execution in Python
shell. Notice that first code-fragment after taking input gives error, while second code-fragment does
not produce error. Can you tell why ?

(a)
print (num float (input("value1:")) )
=

lnput taken as per execution of input()


value1:67
Traceback (most recent call last):

File "<python-input-56-78b83d911bc6>", line 1, in <module>


print (num float (input("value1:")) )
TypeError: "num' is an invalid keyword argument for this function

(b)
print (float (input("value1:")) )
value1:67
Code successfully executed. No error reported.
67.0
102
INFORMATIc PRACT
20. Predict the output of the following code:

days int(input("Input days: ")) * 3600 * 24

hours =int (input ("Input hours: ")) * 3600


minutes =
int(input("Input minutes: ")) *60
seconds =
int (input("Input seconds: "))
time days + hours + minutes + seconds
print("The amounts of seconds", time)
If the input given is in this order : 1,2,3, 4

Type C: Programming Practice/Knowledge based


1.
Questions
Write a
program that
displays a joke. But display the
(Hint. You may
input( ))use punchline only when the user presses enter
2. Write a
ke
program to read today's date
the current month. (only del part) from user. Then
3. Write a
display how many days are letin
program that generates the
5 following output
10
9

Assign value 5 to a variable


1 to
generate 9. using assignment
operator ( Multiply it with 2
4. to generate 10 and
Modify above program so as to subtrar
5. Write the print output as
program with maximum three lines 5@10@9.
variables and then of code and
6.
print them. that
assigns first 5 multiples ofa
Write Python
7. Write a short
program that accepts marks in 5 number t
subjects and outputs
inches. (1 footprogram
that asks for
12 inches, 1 your height in average marks.
8. Write a
=

inch 2.54 cm). centimetres


=
and then
program to read a
number n and
converts your height to feet
9. Write a print n, n ai
10. Write a
program to
compute simple interest and andnt.
11. Write a
program to
input a number and compound interest.
program read details like
to print its first five
line and then in name, class, age of a multiples.
Make sure to have
separate lines. student and then
two blank lines in print the details
12. Write a these two
different types of
firstly in sane
program to read
three
first and
second, second and thirdnumbers in three variables prints.
and
13. Write a numbers swap first two
program that accepts cost respectively. variables with the sums of
prints Gross profit, netof sold goods (Cgos) revenue
[Hint: Net
profit and net
profit percentage. generated, operatine
profit Revenue cgos oc] (oc) and

You might also like