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

python_IA1_scheme

The document outlines the internal assessment scheme for the Introduction to Python Programming course for the academic year 2024-25. It includes questions and solutions related to Python functions, error handling, data structures, and programming concepts. The assessment is structured into parts A and B, with various coding examples and explanations provided.

Uploaded by

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

python_IA1_scheme

The document outlines the internal assessment scheme for the Introduction to Python Programming course for the academic year 2024-25. It includes questions and solutions related to Python functions, error handling, data structures, and programming concepts. The assessment is structured into parts A and B, with various coding examples and explanations provided.

Uploaded by

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

1

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

Scheme And Solutions for Internal Assessment-I


A.Y. 2024-25 EVEN SEMESTER
Branch:CSE/ISE/AIML/CG/CD Semester: II
Course: Introduction to Python Programming

Course Code: MVJ22PLCK25D Duration of the Paper: 1.5 Hrs. Maximum Marks: 50
PART A

QNo. Solutions Mark


Allocated
1. len(): Returns an integer representing the number of items in an object (like a 2
string, list, tuple, or dictionary).
input(): Returns a string entered by the user from the keyboard.
print():The print() function in Python outputs the given objects to the standard
ou ut stream icall the console . It does not ex licitl return a value.
2. The def statement is used to define a function. It tells Python that you are 2
creating a reusable block of code that perfonns a specific task when called.
Eg: def greet(name):
rint "Hello, " + name
3. Global scope variables are defined outside of functions and accessible 2
throughout the program.
Local scope variables are defined inside a function and only accessible within
that function.
name = "Alice" # Global variable
def greetO:
global name
name= "Bob" # Modifies the global variable
greeting= "Hello" # Local variable
print(greeting, name)
greetO
rint name
4. Augmented assignment operators are shorthand for perfonning an operation . 2
and assigning the result to the same variable.
+=, -=, *=, /=
5. Fast and efficient key-value lookups. 2
Useful for organizing and storing related data (like settings, counters, etc.).
Allow easy data modification and retrieval by key.
Unordered and flexible - ke s can be strin s, numbers, etc.

PARTB

Question Solution Marks


No. Allocated
6. try: IOM
num = int(input("Enter a number: "))
- - · - .... .... 1'11.1UI u, •• 11 · 1· 1 , \l'lo l 1.· r 1 c P1r, t r · v L'l'\1 1 · t l'\1 1., L, U I" " •

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

Explanation: (SM) am does.


• First, a comment at the top of the code explains what the progr use the
• Then, the program imports the random module so that it canto guess.
random.randint() function to generate a numb er for the user
• The return value, a random integer betwe en 1 and 20, is stored in the ·llY\
variable secretNumber. er and
• The program tells the player that it has come up with a secret numb
will give the player six chances to guess it. is in a for
• The code that lets the player enter a guess and checks that guess
loop that will loop at most six times. ess.
• The first thin that ha ens in the loo is that the la er
),
um value is p~ sed stra igh t i~to int(
• Si~ce inputO returns a string, its r~t ger value. Th is get s sto red m a
mte
which translates the string into an ·
variable nam ed guess. her nor low er than the sec ret num ber , the n it mu st
• If the guess is neither hig
ich case you wa nt the pro gra m
be equ~l to the secret number, in wh
execution to break out of the us for loop. the
if.. .else statement che cks wh eth er
• Aft er the for loop, the previo the num ber and pri nts an app rop riat e me ssa ge
player has correctly guessed
to the screen. a variable that contains an inte ger
• In both cases, the program displays umber).
value (guessesTaken and secretN se inte ger values to strings, it pas ses the se se
• Since it mu st con cat ena te the
returns the string value form of the
yariables to the strO function, which
mtegers. enated wit h the + operators before
fmally
• No w these strings can be concat
call.
being pas sed to the print() function
SM
bers.
8. (a) range() generates a sequence of num

Syntax and Co mm on forms: (2M)


1. The for keyword -2-M
2. A variable name
3. The in keyword h up to three integers pas sed to it
4. A call to the range() me tho d wit
5. A colon use)
ed block of cod e (cal led the for cla
6. Starting on the nex t line, an indent

The com mo n forms are:


• range(stop) - from Oto stop- I stop- I
• range(start, stop) - from start to size
• range(start, stop, ste p)- wi th step
(2M) (V)
Example wit h output:
print('My nam e is')
for i in range(5): + ')')
print('Jimmy Fiv e Times (' + str(i)

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)

• sys.exit() stops the interpreter entirely.


• break only exits the current loop.
• return onl exits the current function.
PAR TC

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)

(Any relevant example)


Example with output: (2M)

allGuests = {'Alice': {'apples': 5, 'pretzels': 12},


'Bob': {'ham sandwiches': 3, 'apJ?les':2},
'Carol': {'cups': 3, 'apple pies': 1}} .
def totalBrought(guests, item):
numBrought = 0 1
fork, v in gu est s.i tem s() :-- ---, 0)- --- --·
-•. 2
numBrought = numBrought + v.get(item
return numBrought
print('Number of things being brought:')
print(' - App les'+ str(totalBrought(allGuests, 'apples')))
print(' - Cup s'+ str(totalBrought(allGuests, 'cups'))) . ,
s'))) ,
print(' - Cak es'+ str(totalBrought(allGuests, 'cakeuests , ~~sa ndw iche s)))
print(' - Ham Sandwiches'+ str(totalBrought(allG pies)))
print(' -Apple Pies '+ str(totalBrought(allGuests, 'apple

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

Reference: with exampJe ·(2M)


In Python, variables store references to obje cts, not the actual object. So,
ii) e, not a new copy.
assigning one list to another creates a referenc
Example:
a= [I, 2, 3]
b = a # b refers to the same list as a
b[0] = 100
print(a) # Output: [100, 2, 3]
copy (shallow copy): (2M) cts are still referenced.
Creates a new outer object, but inner nested obje
import copy
original= [[I, 2], [3, 4]]
shallow = copy .copy(original)
shallow[0][0] = 99
print(original) # Output: [[99, 2], [3, 4]]
deepcopy: (lM) ed structures.
Creates a fully independent copy, including nest
deep = copy .deepcopy(original)
deep[0][0] = 100
print(original) # Output remains unchanged

11. Program : (SM) -ri0M.


import random
messages = ['It is certain',
'It is decidedly so',
'Yes definitely',
'Reply hazy try again',
'Ask again later',
'Concentrate and ask again',
'My reply is no', .
'Outlook not so goo d',
'Very doubtful']
. print(messages[random.randint(O, len(messages) - l)])
., -
-,..___

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 ,\.. ...

QNo. Set A SetB SetC SetD


\
1 c.def b. 5.0 a.0 b.f4,31
2 b.= b. Iist=["apple", b. 5.0 b.0
"banana","cherry
"l
3 c. Null Equivalent c. Null Equivalent C. + a.
["Welcome","to",
"Pvthon"l
4 d. Sends a value a. d. Sends a value b. Iist-=["apple",
back to the caller ["Welcome" "to" back to the caller ''banana ","cherry"
"Python"l' ' l
5 c. Complex b. variable b.[4,3] c.Listl .append (5)
logical
Expression
6 c.+ . b.f4,31 c. import math b. variable
7 b. Deletes the c.def c.Listl .append(5) d. Sends a value
element back to the caller
c. raises the
Its a. countO b.= c.def
8
KevError
c. Listl.append(5) c. Complex b. Deletes the c. import math
9
logical element
Expression
a. CountO a.0 b. variable d. Ends the
10
program
immediately

SIGNATURE OF FACULTY

I, ( · Sh.oJ< ~ L,_ f ~
l. H-~ ~, Jr. r r/

3 . J · J tA.-rc;Jfit' ;J. /4
4 • Cr . .

You might also like