python_IA1_scheme
python_IA1_scheme
COLLECiEOF
ENGINEERING
Slm:o 19:92
An Autonomous Institution
Permanently Affiliated to VTU, Belagavl, Approved by AICTE, Accredited by NAAC, NBA
Recognized by UGC with 12(f) & 12(B) Status
Course Code: MVJ22PLCK25D Duration of the Paper: 1.5 Hrs. Maximum Marks: 50
PART A
PARTB
result = 10 / mun
print("Result is:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.") (3M)
output: (2M)
21.0
3.5
Error: Invalid argument.
t the
Explanation: (SM) am due to errors instead we wan
• If we don't want to crash the progr
program to. detect errors handle them and then continue to run.
• A ZeroDivisionError happens when ev~r we try to divid e a number by zero.
return
From theline number given in the error message, we know that the
statement in spam() is causing an error ·
• Errors can be handled with try and except statements. claus e. The
• The code that could potentially have an error is put in a try
program
error
• execution moves to the start of a following except clause if an
happens
• We can put the previous divide-by-zero code in a try clausthis e and have an
except clause contain code to handle what happe ns when error occurs.
calls in a try block will also be
• Note that any errors that occur in function
caught. the execution
• The reason print(spam(l)) is never executed is because once to the try clause.
jumps to the code in the except clause, it does not return
Instead, it just continues moving down as normal.
lOM
7. import random
secret_number = random.randint(l, 20)
print("I'm thinking of a number between 1 and 20. ")
for guessesTaken in range(l, 7):
guess= int(input("Take a guess: "))
if guess < secret_number:
print("Your guess is too low.")
elif guess > secret_number:
print("Your guess is too high.") ~M
~e: .
break # Correct guess
if guess = secret_number:
print("Goodjob! You guessed it in {guessesTaken} tries.")
else: (SM)
print("Nope. The number I was thinking of was {secret_number}.")
output:
My nam e is
Jimmy Fiv e Times (0)
Jimmy Fiv e Times (1)
Jimmy Fiv e Times (2)
Jimmy Five Tim es (3)
Jimmy Fiv e Tim es (4)
Explanation: (#M ) ~M
is run five times.
• Th e cod e in the for loo p's clause le i is set to 0.
iab
• Th e first tim e it is run, the var pri nt Jim my Fiv~ Tim es (0).
the cla use wil l
• The pri nt( ) call in n thr oug h all the cod e ins ide the for
loop' s
• Aft er Pyt hon fmi she s an iter atio tem ent
use , the exe cut ion goe s bac k to the top of the loop, and the for sta
cla
increments i by one. wit h i
five iterations thr oug h the cla use ,
• This is wh y range(5) results in n 3, and the n 4.
being set to 0, the n 1, the n 2, the to
wil l not include, the inte ger pas sed
• Th e variable i will go up to, but
range().
the entire pro gra m.
(b) sys.exit(): Im me dia tely terminates but the pro gra m con tinu es.
break: Exits a loop (like for or while) returns a value. (2M )
ally
return: Ex its a function and option
Example:
(Each example or one example with all the statements) (IM)
import sys
def example_function():
while True:
choice = input("Enter 'quit' to exit: ")
if cho ice= "quit":
sys.exit() # Program ends here
print("Still running... ")
example_function()
Comparison and contrast: (2M)
StateMent Purpose Scope
Ten\l\iMtes t~e evitire Ciloba/ (stops t~e
sys.exit()
pro9raw. executiovi script)
break Exits t~e viearest loop Local (affects loops)
Exits a fuvictiovi avid Local (affects Fuvictiovi
return
optioMII~ returns a value executiovi)
Solution Marks
Question Allocated
No. naries contain lOM
9. ► Nested dictionaries and lists are data structures where dictio
other dictionaries/lists or vice versa. dictionaries are
► Lists are useful to contain an ordered series of values, and
useful for associating keys with values (2M)
output:
Number of things being brought:
-Apples 7
- Cups 3
- Cakes 0
- Ham Sandwiches 3
- Apple Pies 1
Explanation of the program written: (6M)
For this example:
► Inside the totalBrought() function, the
for loop iterates over the keyvalue
pairs in guests 1.
► Inside the loop, the string of the gue
st's name is assigned to k, and the
assigned to.
dictionary of picnic items they're bringing isdict
in this ionary, it's value (the
► If the item parameter exists as a key
. quantity) is added to nurnBrought 2.
► If it does not exist as a key, the get() met
hod returns 0 to be added to
nurnBrou ht. SM
I0(i) Program: (2M)
test_list = [4, 5; 4, 5, 6, 6, 5]
count={}
for c in test list:
count.setdefault(c,0)
count[c]=count[c]+ I
print(count)
output: (2M)
{4:2, 5:3, 6: 2}
Ex.e_lanation (IM):
Explanation: (5M)
• The list responses holds possible answers .
• The program randomly selects a response using random.choice().
• Lists allow us to easily store and access multiple potential respon~es. f l'-"\
• The expression you use as the index into messages: random .randmt (0,
len(messages) - 1). This produces a random number to use for the index,
regardless of the size of messages. That is, you'll get a random number
between Oand the value oflen(messages) - 1
QUIZ
\ M Q..f'Y1C ~OLtA ,\.. ...
SIGNATURE OF FACULTY
I, ( · Sh.oJ< ~ L,_ f ~
l. H-~ ~, Jr. r r/
3 . J · J tA.-rc;Jfit' ;J. /4
4 • Cr . .