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

Python Answer

This document contains a series of questions and answers related to Python programming. It covers topics like string concatenation, variable types, conditional statements, scopes, and errors. There are 30 multiple choice and code writing questions across 4 units that test concepts like printing, variables, operators, data types, conditional logic, and error handling. The questions provide examples of Python code and ask students to determine outputs, fix errors, write missing code, and identify scopes and reserved words.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
662 views

Python Answer

This document contains a series of questions and answers related to Python programming. It covers topics like string concatenation, variable types, conditional statements, scopes, and errors. There are 30 multiple choice and code writing questions across 4 units that test concepts like printing, variables, operators, data types, conditional logic, and error handling. The questions provide examples of Python code and ask students to determine outputs, fix errors, write missing code, and identify scopes and reserved words.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

RATHNAVEL SUBRAMANIAM COLLEGE OF ARTS AND SCIENCE

(Autonomous)
SCHOOL OF COMPUTER STUDIES (UG)
B.Sc Computer Science/ Information Technology / Computer Applications
(2017 Batch)
SEMESTER VI
PYTHON PROGRAMMING

Section A
UNIT I
1. message1 = "Hello, world!" , message2 = "How are you?” [Ap][CO1]
print (message1+message2)
Ans:
Hello,world!How are you?
What will be the output of the code above?
2. What will the output of thecode?[U][CO1]
print ("Hey, an exercise!”)
a) "Hey, an exercise!" b) Hey, an exercise! C) "Hello, world” d) Hello, world
Ans:
b) Hey, an exercise!
3. Fix the code below so that it counts down from 5 to 1.[U][CO1]
print(1)
print(2)
print(3)
print(4)
print(5)
Ans:
print(5)
print(4)
print(3)
print(2)
print(1)

4. Which of the following are correct definitions of compiling? (Choose all that apply.)
[U][CO1]
(i) Reading over code before executing it to see if there are any obvious errors
(ii) Running code to actually carry out its instructions
(iii) Translating the code we write into the low-level instructions the computer
understands
Ans:
(i) Running code to actually carry out its instructions
(ii) Translating the code we write into the low-level instructions the computer
understands
5. Which of the following statements is true about compiling and running? (Choose all that
apply.) [U][CO1]
(i) Compiling is like checking your code beforehand to see if it makes sense
(ii) A program doesn't actually perform its task until it's executed
(iii) Technically, compiling also translates the code we write into low-level commands
the computer can execute
(iv) All languages require compilation, but not all require execution
Ans:
(i) Compiling is like checking your code beforehand to see if it makes sense
(ii) A program doesn't actually perform its task until it's executed
(iii) Technically, compiling also translates the code we write into low-level commands
the computer can execute

6. Try to identify kinds of errors to the given sentence. [U][CO1]


I wonder what color today is.
Ans:
Syntax error
7. aVar = 52
bVar = 3
bVar = 1
print(bVar)
What is the output of the above code? [Ap][CO1]
Ans:
1
8. myString1 = "Hello!” #string 1 declared
myString2 = "My name is David.” #string 2 declared
myString3 = "Welcome to CS1301!” #string 3 declared
print(myString1)
print(myString3)
print(myString2)
What is the output of the above code? [Ap][CO1]
Ans:
Hello!
Welcome to CS1301!
My name is David.
9. Write the output of the following? [Ap][CO1]
print('The sum of {0} and {1} is {2}'.format(2, 10, 12))
Ans:
The sum of 2 and 10 is 12
10. In python types is directly interpreted by the compiler, so consider the following
operation to be performed.[Hint: Choose operator(s)] [Ap][CO1]
>>>x = 13 ? 2
Objective is to make sure x has a integer value, select all that apply
a) x = 13 // 2
b) x = int(13 / 2)
c) x = 13 / 2
d) x = 13 % 2
Ans:
a) x = 13 // 2
b) x = int(13 / 2)
d) x = 13 % 2
Unit II

11. a = "A text message”


b =3
c = 7.4
d = False
What type of data that the variable d holds? [U][CO2]
a) decimal number b) string of characters c) Boolean d) An integer
Ans:
c) Boolean

12. #<class 'str'>


#<class 'int'>
#<class 'bool'>
#<class 'float'>
Rearrange the following code so that the output matches the above. [Ap][CO2]
print(type(5.1))
print(type(5))
print(type("Hello!"))
print(type(True))
Ans:
print(type("Hello!"))
print(type(5))
print(type(True))
print(type(5.1))
(iii)(ii)(iv)(i)
13. The line below attempts to print the value of my_int, but currently it does not work. Fix
this code so that it works and prints "The current value of my_int is:", followed by the
value. (Hint: There should not be space between message and value) [Ap][CO2]
import random
my_int = random.randint(0, 10)
print("”) #modify this print( ) statement
Ans:
my_int = random.randint(0, 10)
print("The current value of my_int is :”+str(my_int))
14. 1| a =5
2| b =3
3| c =4
4| d =4
5| e =5
6| print(a == b)
7| print(a == c)
8| print(a == d)
9| print(a == e)
What would be the output of the code above? If error, then write error line number(s)
[Ap][CO2]
Ans:
False
False
False
True
15. 1| a =5
2| b =5
3| c =3
4| print(a = b)
5| print(a = c)
6| print(b = c)
What would be the output of the code above? If error, then write error line number(s)
[Ap][CO2]
Ans:
Type error

16. a = "Hello, world"


b = "Hello, world"
c = "Hello, "
d = "world"
print(a == b)
print(a == c)
print(a == c + d)
Write the output of the above code? If error, then write error line number(s) [Ap][CO2]
Ans:
True
False
True
17. Write a python code for the method used to input a string as myString from the user.
[Ap][CO2]
Ans:
iv) myString=input(Enter string)
d) (iv)
18. Using dot notation, which of the following would represent the idea of a student's
address's street name? [U][CO2]
a) student.street.address b) student.address.street
c) address.student.street d) address.street.student
Ans:
b
19. Which of the following blocks of code will generate an error when run?
(select all that apply) [U][CO2]
a) Line1:pass = 5 Line2: print(pass) b) Line1:fail = 5 Line2:print(fail)
c) Line1:int = 5 Line2: print(int) d) Line1:float = 5.1 Line2: print(float)
Ans:
a) Line1:pass = 5 Line2: print(pass)

20. 1| letterOfTheDay = "F”


2| print("Letter of the day: " + letterOfTheDay)
What will be the output of the code above? [Ap][CO2]
Ans:
Letter of the day:F
Unit III
21. Based on the behavior described by the print statements, which of the following would
be the correct way to indent this code? (Assume the variables a and b are created
earlier.) [Ap][CO3]
1| if a > b:
2| print("This line should be controlled by line 1.")
3| print("This line should also be controlled by line 1.")
Ans
d)if a>b:
print(“this line should be controlled by line1”)
print(“this line should also be controlled by line 1”)
22. Write missing condition statement from the following code snippet? [Ap][CO3]
myNum1 = 1
myNum2 = 2
#Checks if myNum1 is less than myNum2
if myNum1 < myNum2:
#Prints this if so
print("myNum2 is greater than myNum1!")
#Prints this regardless
print("Execution complete!")

Ans:
c)if myNum1<myNum2:

23. Write the output of the following code snippet? [Ap][CO3]


myNum1 = 1
myNum2 = 2
myNum3 = 3
#Checks if myNum1 is less than myNum2
if myNum1 < myNum2:
#Prints this if so
print("myNum2 is greater than myNum1!")
#Checks if myNum1 is less than myNum3
if myNum1 < myNum3:
#Prints this if so
print("myNum3 is also greater than myNum1")
#Prints this regardless
print("Execution complete!")

Ans:
a)myNum2 is greater than myNum1
myNum3 also greater than myNum1
Exection completed

24. What is the scope of num1 from the following variables in the code snippet?
(Hint: Specify the line numbers) [Ap][CO3]
1| num1 = 5
2| num2 = 11
3| if num1 < num2:
4| num2 = 9
5| if num1 < num2:
6| num3 = 10
7| print("Done!")

Ans:
a)Line1 Global Scope
25. What is the scope of num2 from the following variables in the code snippet?
(Hint: Specify the line numbers) [Ap][CO3]
1| num1 = 5
2| num2 = 11
3| if num1 < num2:
4| num2 = 9
5| if num1 < num2:
6| num3 = 10
7| print("Done!")

Ans:
c)line 2 global scope, line 4 local scope
26. What is the scope of num3 from the following variables in the code snippet?
(Hint: Specify the line numbers) [Ap][CO3]
1| num1 = 5
2| num2 = 11
3| if num1 < num2:
4| num2 = 9
5| if num1 < num2:
6| num3 = 10
7| print("Done!")

Ans:
d)line 6 global scope
27. Find the errors from the following code snippet? [Ap][CO4]
myNum1 = 1
myNum2 = 3
if myNum1 < myNum2
result = "myNum1 is less than myNum2!"
print(result)
print("Done!")

Ans:
b)invalid Syntax
28. Find the errors from the following code snippet? [Ap][CO4]
myNum1 = 1
myNum2 = 3
if myNum2 < myNum1:
result = "myNum2 is greater than myNum1!"
print(result)
print("Done!")

Ans:
d)if condition error
29. Which line in the code above will cause an error? [Ap][CO4]
(Hint: Specify line number if error, other wise specify code is correct)
1| myAge = 17
2| if myAge>= 18:
3| print("I can vote now!")

Ans:
d)code is correct
30. Write reserved words from the following code snippet? [U][CO3]
#CreatestodaysWeather and sets it
#equal to "cold"
todaysWeather = "cold"
#Checks if todaysWeather equals "raining"
iftodaysWeather == "raining":
print("raincoat")
print("rainboots")
#IftodaysWeather didn't equal "raining",
#do the following
else:
print("t-shirt")
print("shorts")
print("Done!")
Ans:
a)if,else,print
Unit IV
31. What will be the output of the following code snippet? If it is an error then write as Error.
[Ap][CO5]
myString = ' "Hello, world!" '
print(myString)

Ans:
a)”Hello, world!”
32. What will be the output of the following code snippet? If it is an error then write as Error.
[Ap][CO5]
myString = " ' "Hello, world!" ' "
print(myString)

Ans:
d)Error

33. What will be the output of the following code snippet? If it is an error then write as Error.
[Ap][CO5]
myString = ' ' ' 'ello, "world"!' ' '
print(myString)

Ans:
a)“”ello,”world”!
34. Write output for the following: [Ap][CO5]
myStringWithNewline = "12345\n67890"
print(myStringWithNewline)

Ans:
a)12345
67890
35.Write output for the following: [Ap][CO5]
myString = "12345\n67890\tabcde\"fghijklm\\no"
print(myString)

Ans:
a)12345

67890 abcdefghijklm

36. Write output for the following: [Ap][CO5]


myString1 = "12345"
myString2 = "67890"
myString1 += myString2
print("Self-Assignment Concatenation: " + myString1)
Ans:
a)1234567890
37. Write output for the following: [Ap][CO5]
myString = "You-are-a-strange-loop"
print(myString[1])
Ans:
b)o
38. Write output for the following: [Ap][CO5]
myString = "You-are-a-strange-loop"
print(myString[21])
Ans:
b)string index out of range
39. Write python code for writing myInt1 to outputFile? [Ap][CO6]
myInt1 = 12
#Open OutputFile.txt in write mode
outputFile = open("OutputFile.txt", "w")
#Write myInt1 to outputFile
#Close outputFile
outputFile.close()
Ans:
d)outputfile.write(str(myInt1))
40. monthlySpending = {"food":150, "rent":750, "electric":100}
The line of code above creates a dictionary called monthlySpending with one key, food, and
one value, 150. If we want to add another item to this dictionary: "gas", with a value of 25,
How would we do that? [Ap][CO6]
Ans:
b)monthlySpending[“gas”]=25
Unit V
41. Which of the following is the name of the class we are creating? [Ap][CO7]
1| class Student:
2| def __init__(self):
3| self.studentName = ""
4| self.GPA = 0.0
5| self.creditHours = 0
6| self.enrolled = True
7| self.classes = []
Ans:
a)Student

42. Which of the following is a variable of the class whose initial value is an integer? [Ap][CO7]
1| class Student:
2| def __init__(self):
3| self.studentName = ""
4| self.GPA = 0.0
5| self.creditHours = 0
6| self.enrolled = True
7| self.classes = []
Ans:
b)creditHours
43.Which of the following is a variable of the class whose initial value is a float? [Ap][CO7]
1| class Student:
2| def __init__(self):
3| self.studentName = ""
4| self.GPA = 0.0
5| self.creditHours = 0
6| self.enrolled = True
7| self.classes = []
Ans:
c)GPA
44. What is the output of the following code? [Ap][CO7]
class test:
def __init__(self,a="Hello World"):
self.a=a
def display(self):
print(self.a)
obj=test()
obj.display()
Ans:
c) ”Hello World” is displayed
45. What is the output of the following code? [Ap][CO7]
class change:
def __init__(self, x, y, z):
self.a = x + y + z
x = change(1,2,3)
y = getattr(x, 'a')
setattr(x, 'a', y+1)
print(x.a)
Ans:
b)7
46.What is the output of the following code? [Ap][CO7]
class test:
def __init__(self,a):
self.a=a
def display(self):
print(self.a)
obj=test()
obj.display()
Ans:
c) Error as one argument is required while creating the object

47. Which of these is a private data field? [Ap][CO7]


def Demo:
def __init__(self):
__a = 1
self.__b = 1
self.__c__ = 1
__d__= 1
Ans:
b)__b
48. What is the output of the following code? [Ap][CO7]
class Demo:
def __init__(self):
self.a = 1
self.__b = 1
def get(self):
returnself.__b
obj = Demo()
print(obj.get())
Ans:
d)The program runs fine and 1 is printed
49.Which of the following is not a fundamental feature of OOP? [Ap][CO7]
(i)Encapsulation
(ii)Inheritance
(iii)Instantiation
(iv)Polymorphism
Ans:
c)instantiation
50. Refer given list as follows and answer the following question. [Ap][CO8]
253869147
After one iteration of selection sort, what is the order of items in the list?
[Hint: Write list elements inside [ ] after first iteration]
Ans:
b)[1 5 3 8 6 9 2 4 7]
Section B

UNIT I
1. Identify the type of error in the following code, Give reason? [Ap][CO1]
a = "Hello, world"
b=5
print(a.endswith("d"))
print(b.endswith("d"))
Ans:
True
Attribute Error: ’int’ object has no attribute ‘endswith’
2. myVar1 =5
myVar1 = 3
myVar2 = myVar1
myVar3 = "Hello!”
myVar1 = myVar3
myVar3 = 5.2
myVar2 = True
What will be the types of each of the above variables when the code above is to be
done running? [Ap][CO1]
Ans:
<class ‘str’>
<class ‘float’>
<class ‘bool’>
3. 1| string1 = "Hello!”
2| print(string1)
3| print(string2)
4| string2 = "Welcome to Python Programming!”
5| "My name is David." = string3”
6| print(string3)
7| print(string3)
In the above code, what is the first line that will generate an error? What will the first
error
be? [Ap][CO1]
Ans:
i)unterminated string literal(detected at line 5)
ii)name error: string2 is not defined
4. Name the operator in python that evaluates to true if it does not find a variable in the
specified sequence and false otherwise? Give an example. [U][CO1]
Ans:
Not in operator
5. What is Block comment? Apply block comment to the following code: [U][CO1]
def fib(n):
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while b < n:
print b
a, b = b, a+b
Ans:
Block comment ####### or “”” “””
6. Write a Python code to calculate the square root by accepting input from the user?
[Ap][CO1]
[Hint: Use input( ) method for getting input and convert that in to integer type]
Ans:
Import math
N=int(input(“Enter a number”))
Sqroot= math.pow(N,0.5)
Print(“The square root of a given number is :”+str(sqroot))

7. Write a Python Program that asks the user to enter their name and their age. Print out
a message addressed to them that tells the year that they will turn 100 years old?
[Ap][CO1]
Ans:
Name=input()
Current_age=int(input())
Hundred_year=2023+(100-current_age)
Print(f’{name}will become 100 years old in the year{Hundred_year}’.)
8. Create a variable savings with the value 100& create a variable factor, equal to 1.10.
Use savings and factor to calculate the amount of money end up with over 7 years.
[Hint: (SxF^7) Store the result in a new variable, result.] Print out the value of the
result? [Ap][CO1]
Ans:
Saving=100
Factor=1.10
Result=Saving*Factor^7
Print (Result)
9. Show how to concatenate a string variable with an integer? For example: "SCS-UG"
with number 2017. [Ap][CO1]
Ans:
String=”SCS-UG”
Integer=5
Print(String+Integer)
10. Show with python code that initialization can be done on more than one variable
"simultaneously" on the same line. Make the summation of those variables & print the
result? [Ap][CO1]
Unit II
11. Write code which Assign to each variable a value of the corresponding type (an integer
for my_integer, a string of characters for my_string, etc.). and display its type.
In the code below, created two dates earlier_date and later_date, and later_date is
guaranteed to be later than earlier_date. The day in each date is chosen randomly.
Complete this code so that it creates a variable called days_betweenthat stores the
number of days between the two dates?[Ap][CO2]
From datetime import date
import random
earlier_date = date(2017, 6, random.randint(1, 25))
later_date = date(2017, 6, random.randint(earlier_date.day + 1, 28))
Ans:
import random
earlier_date = date(2017, 6, random.randint(1, 25))
later_date = date(2017, 6, random.randint(earlier_date.day + 1, 28))
days_between=earlier_date – later_date
print(days_between.days)

12. Write the python code so that the output matches the following? [Ap][CO2]
<class 'str'>
<class 'int'>
<class 'bool'>
<class 'float'>
Ans:
Str=”Lalitha”
Int = 5
Bool = True
Float= 6.4
Print(type(Str))
Print(type(Int))
Print(type(Bool))
Print(type(Float))

13. myInteger =3
myFloat = 5.5
myString = "Python!”
myBoolean = False
a = myBoolean + myInteger
b = myInteger * myString
c = myFloat * myBoolean
d = myFloat * myInteger
What will be the values of each variable when this code is running? (Booleans take on
the value 0 for False, 1 for True.) [Ap][CO2]
Ans:
3
Python!Python!Python!
0.0
16.5
14. str = 'Python Programming'
print (str)
print (str[0])
print (str[1:5])
print (str[1:])
print (str * 2)
print (str + "TEST")
Write the output of above coding? [Ap][CO2]
Ans:
Python Programming
P
ython
ython Programming
Python Programming Python Programming
Python ProgrammingTEST
15. Accept divisor and dividend from the user. Write a Python program to print the quotient
and remainder as an integer? [Ap][CO2]
Ans:
Num=int(input(“Enter numerator:”))
Den=int(input(“Enter denominator:”))
Print(“Quotient is ”,str(num/den),”reminder is ”,str(num%den))
16. Create a variable mystery_string with the value "Hello, world!”. Write a Python
program that will print True if the string "world" appears within mystery_string, and
False if it does not? [Ap][CO2]
Ans:
mystery_string=”Hello,world!”
if “world” in mystery_string:
print(“True”)
else:
print(“Flase”)
17. 1| myString1 = "2”
2| myString2 = "-9.1”
3| myString3 = "Hello!”
4| ##
Pretend that each of the following lines was included as line 4 in the code above. What
would be the output of each? [Ap][CO2]
print(int(myString1)
print(bool(myString2))
print(float(myString3)
print(int(myString2)
print(float(myString1))
Ans:
Name error
18. 1| a =5
2| a **=2
3| b = a %5
4| a *=b
5| b +=5
6| a -=b
7| c = a ==b
8| d = a**2 == b**2
9| e = c or d
What is the value of each variable when this code has finished running? [Ap][CO2]
Ans:
-5(a)
5(b)
False(c)
True(d)
True (e)
19. For each of the following code segments, what will be the value of myVar at the end of
execution? [Ap][CO2]
myVar = 20
myVar +=4
myVar /=3
myVar **=3
myVar = -6
myVar +=6
myVar -=1
myVar **=3
myVar **=2
myVar = 600
Ans:
600
20. For each of the following code segments, what will be the value of myVar at the end of
execution? [Ap][CO2]
myVar /=2
myVar /=3
myVar /=4
myVar = 81
myVar %=6
myVar *=3
myVar +=9
myVar //=2
Ans:
300
UNIT III
21. Write python codes which produce the output from 0-5 as follows by using for, continue
statement? [Ap][CO3]
01245
Ans
For I in range(6):
If I == 3:
Continue
Print(I, end=’ ‘)

In this code, we use the range() function to loop through the numbers from 0 to 5. Inside
the loop, we use an if statement to check if the current number is equal to 3. If it is, we use
the continue statement to skip the rest of the loop body and move on to the next iteration.
If the current number is not equal to 3, we use the print() function to output it to the
console, separated by a space. The end=’ ‘ parameter is used to specify that a space
character should be printed after each number instead of a newline character.

The output of this code will be:


01245
.

22. Write python codes which accept input from the user, but the code should process the
input string only if it is at least 3 characters long. Otherwise, ask the user to give input
again? [Ap][CO3]
(Hint: Use len(), continue)
Ans
whileTrue:

user_input = input("Enter a string (at least 3 characters long): ")

iflen(user_input) <3:

print("Input string is too short. Please try again.")

continue

else:

# process the input string here

print("Processing input string:", user_input)

break
In this code, we use a while loop to keep asking the user for input until they provide a
string that is at least 3 characters long. We use the len() function to check the length of
the input string, and the continue keyword to skip to the next iteration of the loop if the
length is less than 3.

If the input string is at least 3 characters long, we can process it as needed. In this
example, we simply print the input string to the console. Finally, we use the break
keyword to exit the loop and end the program.

23. Answer the questions given below from the following code: [Ap][CO3]
1| x = 30
2| y = 10
3| if x >= y:
4| winner = "x”
5| else:
6| winner = "y”
7|if x % y == 0:
8| divisible = True
9| elif y % x == 0:
10| divisible = True
11| else:
12| divisible = False
13| if x >= 15 and y >= 15:
14| result = "x and y are big numbers”
15| elif x >= 15:
16| result = "x is a big number”
17| else:
18| result = "y is a big number
(i) What is the value of winner after the above code is executed?
(ii) What is the value of divisible after the above code is executed?
(iii) What is the value of result after the above code is executed?

Ans
a) The value of winner after the above code is executed depends on the values of x
and y. In this code, x is assigned the value 30 and y is assigned the value 10. Since
x is greater than or equal to y, the if statement on lines 3-6 will set winner to “x”.
Therefore, after the code is executed, the value of winner will be “x”.
b) The value of divisible after the above code is executed also depends on the values of
x and y. In this code, we check if x is divisible by y (line 7) or if y is divisible by x
(line 9). If either condition is true, divisible will be set to True. Otherwise, it will be
set to False. Since x is not divisible by y and y is not divisible by x, the else clause on
lines 11-12 will set divisible to False. Therefore, after the code is executed, the value
of divisible will be False.
c) The value of result after the above code is executed also depends on the values of x
and y. In this code, we check if both x and y are greater than or equal to 15 (line
13). If they are, result will be set to “x and y are big numbers”. If only x is greater
than or equal to 15 (line 15), result will be set to “x is a big number”. Otherwise,
result will be set to “y is a big number” (line 18). Since x is greater than or equal to
15 and y is less than 15, the elif clause on lines 15-16 will set result to “x is a big
number”. Therefore, after the code is executed, the value of result will be “x is a big
number
24. Get a number from user and assign to a variable named my_number. Write python code
that prints every third number from 1 to the my_number inclusive (meaning that if
my_number is 7, it prints 1, 4, and 7). Print each number on a separate line. [Ap][CO3]
[Hint: Use modulus operator]
Ans
My_number = int(input(“Enter a number: “))
For I in range(1, my_number + 1):
If I % 3 == 1:
Print(i)
In this code, we first get a number from the user using the input() function and store it in
the my_number variable after converting it to an integer using the int() function.

We then use a for loop to iterate through every number from 1 to my_number inclusive
(i.e., up to and including my_number). Inside the loop, we use the modulus operator (%) to
check if the current number is a multiple of 3 (i.e., if its remainder when divided by 3 is 1).
If it is, we print the number using the print() function, with each number printed on a
separate line.

Note that if the user enters a number less than 3, no numbers will be printed since there
are no multiples of 3 that are less than 3.

25. Initialize the variable named mystery_int = 50. Print the sum of alternate number from 1
to mystery_int. For example mystery_int is 50 then result will be 1, 3, 5 .. 49. [Ap][CO3]
[Hint: Use for loop and modulus operator ]
Ans
Mystery_int = 50 #test input value
# loop starts from 1 and extends uptomystery_int and step value is 3
for loopCounter in range(1,mystery_int+1,3):
print(loopCounter) # print each loopCounter value

26. The program is supposed to print the location of the 'o' in each word in the list given. Add
try/except blocks to print "Not found" when the word does not have an 'o'. [Ap][CO4]
words = ["cloud", "fog", "mat", "rainy"]
Ans
Words = [“cloud”, “fog”, “mat”, “rainy”]

For word in words:


Try:
O_index = word.index(‘o’)
Print(f”’o’ found in {word} at index {o_index}”)
Except ValueError:
Print(f”’o’ not found in {word}”)
In this code, we use a for loop to iterate through each word in the words list. For each word,
we use the try block to try to find the index of the letter ‘o’ using the index() method. If the ‘o’
is found, we print a message indicating the word and the index where ‘o’ was found. If the ‘o’ is
not found, a ValueError is raised and we handle it with the except block, printing a message
indicating that ‘o’ was not found in the word.

27. Give a segment of python code which shows the following output.
[Hint: Use any loop] [Ap][CO3]
111
222
333
Ans
def steps(value):
output=””
for loopCounter in range(1,value+1):#outer loop starts from here
output += (str(loopCounter)+str(loopCounter) + str(loopCounter)+”\n”)
while loopCounter>0:#inner loop starts from here
output += “\t”
loopCounter=loopCounter-1:#inner loop ends here
return output): #outer loop ends here
print(steps(3)) #calling function with a parameter 3
print(steps (6)))) #calling function with a parameter 6

28. Write a function called hide_and_seek. The function should have no parameters and
return no value; instead, when called, it should just print the numbers from 1 through 10,
followed by the text "Ready or not, here I come!" Write function definition and call
statement? [Ap][CO4]
Ans
Def hide_and_seek():
for loopCounter in range(1,11):
print(loopCounter)
print(“Ready or not, here I come!”)
hide_and_seek() #Invoking function

29. Provide a code segment with function and call statement. The function is supposed to
accept a number of minutes as parameter and print how many seconds are in that minutes?
[Ap][CO4]

Ans
Def minutes_to_seconds(minutes):
Seconds = minutes * 60
Print(f”There are {seconds} seconds in {minutes} minutes.”)
# Example function call
Minutes_to_seconds(5)

In this code, we define a function minutes_to_seconds that takes a single parameter


minutes. Inside the function, we calculate the number of seconds by multiplying the number
of minutes by 60 (since there are 60 seconds in a minute). We then use the print() function
to output a message that indicates how many seconds are in the input number of minutes.

In the example function call, we pass the value 5 as an argument to the


minutes_to_seconds function. This will output the following message:
There are 300 seconds in 5 minutes.
30. Provide python code that will show the output below when executed? [Ap][CO3]
123
4 5 6$
7!8!9!0
Ans
For I in range(1, 10):
If I == 4 or I == 7:
Print(‘ ‘, end=’!’)
Elif I == 6:
Print(I, end=’$\n’)
Else:
Print(I, end=’ ‘)
In this code, we use a for loop to iterate from 1 to 9 inclusive. For each iteration, we use a
series of conditional statements (if, elif, and else) to determine what to print.

If the current number is 4 or 7, we print a space followed by an exclamation mark (!) using the
end argument of the print() function to prevent the output from going to a new line.

If the current number is 6, we print the number followed by a dollar sign ($) and then use the
end argument to start a new line.

Otherwise, we simply print the current number followed by a space using the end argument to
prevent the output from going to a new line.

The output of this code will be:


123
4 5 6$
7!8!9!0

UNIT IV
31. Write a function called third character that accepts a string as an argument and returns the
third character of the string. If the user inputs a string with less than 3 characters, return
"Too short". Invoke the function with the following test cases? [Ap][CO5]
third_character("CS1301"))
third_character("Georgia Tech")
third_character("GT")
Ans
Def third_character(string):
If len(string) < 3:
Return “Too short”
Else:
Return string[2]
Print(third_character(“CS1301”)) # expected output: “1”
Print(third_character(“Georgia Tech”)) # expected output: “o”
Print(third_character(“GT”)) # expected output: “Too short”
The function checks whether the input string is less than 3 characters long. If it is, it returns
the string “Too short”. Otherwise, it returns the third character of the string, which is at
index 2 (since Python indices start at 0).
The test cases check whether the function correctly returns the third character for strings
with at least 3 characters, and returns “Too short” for shorter strings.

32. Write a function called "last_n" that accepts two arguments: a string search_string and
an integer n. The function should return the last n characters from search_string. If
search_string is shorter than n characters, then it should return the entire value of
search_string. Give example input and output. [Ap][CO5]
Ans
Def last_n(search_string, n):
If len(search_string) <= n:
Return search_string
Else:
Return search_string[-n:]
The function checks whether the length of search_string is less than or equal to n. If it is, it
returns the entire string. Otherwise, it returns the last n characters of the string, which can be
accessed using negative indexing ([-n:]).

Here are some examples of using the function:


Print(last_n(“hello world”, 5)) # expected output: “world”
Print(last_n(“Python”, 3)) # expected output: “hon”
Print(last_n(“apple”, 10)) # expected output: “apple”

In the first example, the last 5 characters of “hello world” are “world”, so the function returns
“world”.
In the second example, the last 3 characters of “Python” are “hon”, so the function returns
“hon”.

In the third example, “apple” is shorter than 10 characters, so the function returns the entire
string “apple”.

33. Provide python function which accepts 2 parameters(actual_string and search_string) and
ensure the presence of the search string is in a given string. Demonstrate with sample test
cases. [Ap][CO5]
Ans
Def check_presence(actual_string, search_string):
If search_string in actual_string:
Return True
Else:
Return False
The function uses the in operator to check whether search_string is a substring of
actual_string. If it is, the function returns True. Otherwise, it returns False.

Here are some examples of using the function:


Print(check_presence(“hello world”, “world”)) # expected output: True
Print(check_presence(“Python is a programming language”, “Java”)) # expected output:
False
Print(check_presence(“apple”, “app”)) # expected output: True

34. Give a segment of python code which illustrates kinds of string concatenation. [Ap][CO5]
Ans
# Using the + operator to concatenate two strings
Str1 = “Hello”
Str2 = “world”
Result1 = str1 + “ “ + str2
Print(result1) # Output: “Hello world”

# Using the join() method to concatenate a list of strings


Str_list = [“My”, “name”, “is”, “John”]
Result2 = “ “.join(str_list)
Print(result2) # Output: “My name is John”

# Using f-strings (formatted strings) to interpolate variables into a string


Name = “Alice”
Age = 30
Result3 = f”My name is {name} and I am {age} years old.”
Print(result3) # Output: “My name is Alice and I am 30 years old.”
In the first example, we use the + operator to concatenate the two string variables str1 and
str2, and also add a space in between them.
In the second example, we use the join() method to concatenate a list of strings str_list, with a
space as the separator.
In the third example, we use f-strings (formatted strings) to interpolate variables name and age
into a string. The variables are enclosed in curly braces {} within the string, and the f before
the string indicates that it is a formatted string.

35. Write a function named find_occurance () which accept the sentence “Where there is a will
there is a way” as an argument and find, print the location of the second occurrence of
“there”. [Ap][CO5]
Ans
Def find_occurrence(sentence, word):
# First occurrence of the word
First_occurrence = sentence.find(word)

# If the word is not found in the sentence, return -1


If first_occurrence == -1:
Return -1

# Second occurrence of the word


Second_occurrence = sentence.find(word, first_occurrence + 1)

# If the second occurrence is not found, return -1


If second_occurrence == -1:
Return -1

Return second_occurrence

# Example usage
Sentence = “Where there is a will there is a way”
Word = “there”
Second_occurrence = find_occurrence(sentence, word)

If second_occurrence == -1:
Print(f”’{word}’ not found or only found once in the sentence.”)
Else:
Print(f”The location of the second occurrence of ‘{word}’ is at index {second_occurrence}.”)
In this example implementation, the find_occurrence() function takes two arguments: sentence
(the input sentence as a string), and word (the word to search for).
The function first finds the index of the first occurrence of the given word in the sentence using
the find() method of the string. If the word is not found, the function returns -1.
If the word is found, the function then looks for the second occurrence of the word by calling
find() again, starting the search from the index immediately after the first occurrence. If the
second occurrence is not found, the function returns -1.
Finally, the function returns the index of the second occurrence of the word. The calling code
then checks if the returned index is -1 (indicating that the word was not found or only found
once), and prints a message accordingly. If the index is not -1, it prints the location of the
second occurrence of the word in the sentence.
36. Create a function average() which accepts list as an argument and return the average of
numbers in the list. [Ap][CO5]
Ans
Def average(numbers):
# Check if the list is empty
If len(numbers) == 0:
Return None

# Calculate the sum of the numbers


Total = sum(numbers)

# Calculate the average by dividing the total by the number of items in the list
Avg = total / len(numbers)

Return avg

# Example usage
My_list = [1, 2, 3, 4, 5]
Result = average(my_list)
Print(result) # Output: 3.0

In this implementation, the average() function takes a list of numbers as an argument and first
checks if the list is empty. If the list is empty, the function returns None to indicate that there is
no average.
If the list is not empty, the function calculates the total sum of the numbers in the list using the
sum() function, and then divides the total by the number of items in the list to get the average.
Finally, the function returns the calculated average.
In the example usage, we create a list my_list with some numbers, call the average() function
with my_list as an argument, and print the returned average value.

37. Provide a Python code to multiply all the items in a list named oneToFiveNumbers by 2.
Finally, print the new list named listMultipliedByTwo. [Ap][CO5]
Ans
oneToFiveNumbers = [1, 2, 3, 4, 5]

listMultipliedByTwo = []
for num in oneToFiveNumbers:
listMultipliedByTwo.append(num * 2)

print(listMultipliedByTwo) # Output: [2, 4, 6, 8, 10]


In this example code, we start with a list of numbers oneToFiveNumbers containing the
numbers from 1 to 5.

We then create an empty list listMultipliedByTwo to store the results of multiplying each
number in the original list by 2.

We use a for loop to iterate over each number in the oneToFiveNumbers list. Inside the
loop, we multiply the current number by 2 and append the result to the listMultipliedByTwo
list.

Finally, we print the contents of the listMultipliedByTwo list, which contains all the items
from the oneToFiveNumbers list multiplied by 2.

38. Create a list with a set of elements [1,2,3,4,5]. Develop a python function named
writeFunction to write the members of list in the file named “Output.txt”. [Ap][CO5]
Ans
Def writeFunction(lst):
# Open the file for writing
With open(“Output.txt”, “w”) as f:
# Write each item in the list to a new line in the file
For item in lst:
f.write(str(item) + “\n”)

# Example usage
My_list = [1, 2, 3, 4, 5]
writeFunction(my_list)

In this example implementation, the writeFunction() function takes a list as an argument lst.

The function opens a file named “Output.txt” in write mode using the open() function with the
mode “w”. This will create a new file if it doesn’t exist, or truncate the file if it does exist

The function then uses a for loop to iterate over each item in the list and writes it to a new line
in the file using the write() function. We convert each item to a string using str() to ensure that
we can write it to the file as text, and we add a newline character “\n” at the end of each line
to ensure that each item is written to a new line in the file.

Finally, we call the writeFunction() function with an example list my_list containing the numbers
1 to 5, which will write the contents of the list to the “Output.txt” file in the current working
directory.

39. Write missing lines from following code segment? [Ap][CO6]

myInt1 = 12
myInt2 = 23
myInt3 = 34
#Open OutputFile.txt in write mode
outputFile = open("OutputFile.txt", "w")
#Write myInt1 to outputFile
# missing line1
#Write myInt2 to outputFile
# missing line2
#Write myInt3 to outputFile
# missing line3
#Close outputFile
outputFile.close()
Ans
myInt1 = 12
myInt2 = 23
myInt3 = 34

# Open OutputFile.txt in write mode


outputFile = open(“OutputFile.txt”, “w”)

# Write myInt1 to outputFile


outputFile.write(str(myInt1))

# Write myInt2 to outputFile


outputFile.write(str(myInt2))

# Write myInt3 to outputFile


outputFile.write(str(myInt3))

# Close outputFile
outputFile.close()
In this code segment, we have three integer variables myInt1, myInt2, and myInt3.
We then open a file named “OutputFile.txt” in write mode using the open() function, and
store the file object in the outputFile variable.

To write the values of myInt1, myInt2, and myInt3 to the file, we use the write() function
of the outputFile object. We convert each integer value to a string using the str() function
before writing it to the file.
Finally, we close the file using the close() method of the outputFile object to ensure that
any changes made to the file are saved and the file is properly closed.
40. 1| string1 = "Hi!"

2| string2 = "Hey!"

3| string3 = "Hello!"

4|

5| outputFile = open("MyOutput.txt", "w")

6| outputFile.write(string1 + "\n")

7| outputFile.write(string2 + "\n")

8| outputFile.write(string3)

9| outputFile.close()
Which is the best way to rewrite the above code with the print() function instead of the write()
method? [Ap][CO6]

[Hint: only lines 6 through 8 differ between the segments below.]

Ans

String1 = “Hi!”

String2 = “Hey!”

String3 = “Hello!”

outputFile = open(“MyOutput.txt”, “w”)

print(string1, file=outputFile)
print(string2, file=outputFile)

print(string3, end=””, file=outputFile)

outputFile.close()

In this example, we replace lines 6 through 8 from the original code with three print()
statements. The print() function has an optional file argument that we can use to specify the
file object we want to write to.

We pass the outputFile object as the file argument for each print() call. The print() function
automatically adds a newline character at the end of each line by default, so we don’t need to
add “\n” to the first two print() calls.

For the third print() call, we add the end argument and set it to an empty string to ensure that
there is no newline character added to the end of the line. This is because the third line of text
in the file is “Hello!”, and we don’t want it to be followed by a newline character.

Finally, we close the file using the close() method of the outputFile object.

UNIT- V

41. Which of the following is the name of the class we are creating? And change the class name
into Student Enrollment, then write new class with all members. [Ap][CO7]

1| class Student:

2| def __init__(self):

3| self.studentName = ""

4| self.GPA = 0.0

5| self.creditHours = 0

6| self.enrolled = True

7| self.classes = []

Ans
Class StudentEnrollment:

Def __init__(self):

Self.studentName = “”

Self.GPA = 0.0

Self.creditHours = 0

Self.enrolled = True

Self.classes = []

In this updated class definition, we've changed the name of the class to "StudentEnrollment" to
reflect its purpose.

The rest of the class remains the same, with the __init__() method initializing the class
attributes studentName, GPA, creditHours, enrolled, and classes.

We can now use this updated class definition to create objects of the StudentEnrollment class
and work with their attributes and methods.

42. Which of the following is a variable of the class whose initial value is an integer? And
change that value into 5 and write an update class with all members. [Ap][CO7]

1| class Student:

2| def __init__(self):

3| self.studentName = ""

4| self.GPA = 0.0

5| self.creditHours = 0

6| self.enrolled = True

7| self.classes = []

Ans
Class Student:

Def __init__(self):

Self.studentName = “”

Self.GPA = 0.0

Self.creditHours = 0

Self.enrolled = True

Self.classes = []

# Create an object of the Student class

myStudent = Student()

# Update the creditHours attribute to 5

myStudent.creditHours = 5

In this updated class definition, we’ve left the class attributes and __init__() method
unchanged. Instead, we’ve created an object of the Student class on line 11 and assigned it to
the variable myStudent.

On the next line, we update the creditHours attribute of myStudent to 5. We can now use
myStudent to access the updated value of creditHours and perform other operations on the
object’s attributes and methods.

43.Which of the following is a variable of the class whose initial value is a float? And change
that value into 83.75 and write an update class with all members. [Ap][CO7]

1| class Student:

2| def __init__(self):

3| self.studentName = ""

4| self.GPA = 0.0

5| self.creditHours = 0
6| self.enrolled = True

7| self.classes = []

Ans

To change its value to 83.75, we can simply assign the new value to the GPA attribute after
creating an object of the Student class. Here’s an updated class definition with the modified
GPA attribute:

Class Student:

Def __init__(self):

Self.studentName = “”

Self.GPA = 0.0

Self.creditHours = 0

Self.enrolled = True

Self.classes = []

# Create an object of the Student class


myStudent = Student()

# Update the GPA attribute to 83.75

myStudent.GPA = 83.75

In this updated class definition, we’ve left the class attributes and __init__() method
unchanged. Instead, we’ve created an object of the Student class on line 11 and assigned it to
the variable myStudent.

On the next line, we update the GPA attribute of myStudent to 83.75. We can now use
myStudent to access the updated value of GPA and perform other operations on the object’s
attributes and methods.

44. What is the output of the following code? [Ap][CO7]

class test:

def __init__(self,a="Hello World"):

self.a=a

def display(self):

print(self.a)

obj=test()

obj.display()

Ans

The output is:

Hello World

Explanation:
The code defines a class called test, which has an __init__() method that initializes an instance
variable a with the value of “Hello World” by default. It also has a display() method that prints
the value of self.a.

On line 6, an object of the test class is created and assigned to the variable obj.

On the next line, the display() method of the obj object is called, which prints the value of
obj.a, which is “Hello World”.

45. What is the output of the following code?

class change:

def __init__(self, x, y, z):

self.a = x + y + z

x = change(1,2,3)

y = getattr(x, 'a')

setattr(x, 'a', y+1)

print(x.a)

Ans

The output of the code is:

Explanation:

The code defines a class called change, which has an __init__() method that initializes an
instance variable a with the sum of three arguments x, y, and z.

On line 4, an object of the change class is created and assigned to the variable x, with
arguments 1, 2, and 3.
On the next line, the getattr() function is used to get the value of a attribute of the x object and
assign it to variable y. Therefore, y is assigned the value of 6.

On line 6, the setattr() function is used to set the value of a attribute of the x object to y+1.
Therefore, x.a is updated to the value of 7.

On the last line, x.a is printed, which is 7.

46.What is the output of the following code?

class test:

def __init__(self,a):

self.a=a

def display(self):

print(self.a)

obj=test()

obj.display()

Ans

The code will raise a TypeError with the following error message:

TypeError: __init__() missing 1 required positional argument: ‘a’

Explanation:

The test class is defined with an __init__() method that takes one parameter a and initializes an
instance variable self.a with its value.

On line 6, an object of the test class is created and assigned to the variable obj, but the
constructor is called without any arguments, which raises a TypeError because the __init__()
method requires one argument.

47. Which of these is a private data field? [Ap][CO7]

def Demo:
def __init__(self):

__a = 1

self.__b = 1

self.__c__ = 1

__d__= 1

Ans

The private data field in the Demo class is self.__b.

In Python, a data field is considered private if its name starts with two underscores (__) but
does not end with two underscores. Private data fields are not directly accessible from outside
the class and can only be accessed through getter and setter methods.

In the provided code, __a and __d__ are not considered private data fields because they
either do not meet the naming convention or end with two underscores, which makes them
name-mangled but still accessible from outside the class. __c__ is not a private data field
because it ends with two underscores and is considered a special variable used for name
mangling, but can still be accessed from outside the class.

48. What is the output of the following code?

class Demo:

def __init__(self):

self.a = 1

self.__b = 1

def get(self):

returnself.__b

obj = Demo()

print(obj.get())

Ans

The output of the code will be 1.


In the Demo class, there are two instance variables a and __b. The variable a is a public
variable and can be accessed directly using the object of the class. The variable __b is a private
variable, and it can only be accessed within the class, and not from outside.

However, the get method in the Demo class returns the value of the private variable __b, which
can be accessed using the object of the class.

In the given code, the object obj of the Demo class is created, and then the get method is
called using the object obj. The get method returns the value of the private variable __b, which
is then printed using the print statement. Therefore, the output of the code will be 1.

49.

1| class Dog:

2| def __init__(self, name = "", owner = None):

3| self.name = name

4| self.owner = owner

5| def speak(self):

6| print("WOOF!")

7|

8| class Owner:

9| def __init__(self, name):

10| self.name = name

11| def speak(self):

12| print("My name is:", name)

Write valid python code to create a new instance of Dog from the above code? [Ap][CO7]

[Hint: __init__ behaves like a function and remember what you learned about keyword
parameters!]

Ans

To create a new instance of the Dog class, we can simply call the class and pass the required
arguments (name and owner) as parameters:
Dog1 = Dog(name=”Buddy”, owner=Owner(name=”John”))

This creates a new instance of the Dog class with the name “Buddy” and an Owner object with
the name “John” as its owner.

50.

1| class Dog:

2| def __init__(self, name = "", owner = None):

3| self.name = name

4| self.owner = owner

5| def speak(self):

6| print("WOOF!")

7|

8| class Owner:

9| def __init__(self, name):

10| self.name = name

11| def speak(self):

12| print("My name is:", name)

Which of the following would be valid ways to create a new instance of Dog from the above
code that includes an owner? [Ap][CO7]

[Hint:__init__ behaves like a function and remember what you learned about keyword
parameters!]

Ans

To create a new instance of Dog from the above code that includes an owner, we need to
provide a value for the owner parameter in the __init__ method. Here are some valid ways to
do that:

My_owner = Owner(“John”)

My_dog = Dog(“Fido”, my_owner)

My_dog = Dog(“Fido”, Owner(“John”))


Both of these create a new instance of Owner with the name “John”, and then use that instance
to create a new instance of Dog. The first way creates the Owner instance separately and then
passes it to the Dog constructor as an argument, while the second way creates the Owner
instance inline as an argument to the Dog constructor.

Section C
Unit I
1. Apply Print Debugging for the following Python code. [Ap][CO1]
i = 10
count = 1
while count < i:
count = count + 1
while count > 0:
count = count + 1
print(count)

Ans
I = 10
Count = 1

While count < i:


Print(f”count: {count}”) # debugging print statement
Count = count + 1
While count > 0:
Print(f”inner count: {count}”) # debugging print statement
Count = count + 1

Print(count)

When we run this code, we will see the values of count and inner count printed out at
each iteration of the loops. This will help us understand what’s happening and
potentially identify any issues.

Note that there was also an indentation error in the original code, which I’ve corrected
here.

2. 1|userInput = input("Enter a number: ")


2| print("Your original input: " + userInput)
3| userInputAsFloat = float(userInput)
4| print("Your input as a float:", userInputAsFloat)
5| userInputAsInt = int(userInput)
6| print("Your input as an integer:", userInputAsInt)
The code above prompts the user to input a number. Where will an error arise if...
[Ap][CO1]
a) The user input is 5
b) The user input is 8.1
c) The user input is Ok!
d) The user input is blank (that is, the user just presses enter)
Ans:

a)Enter a number:5
Your original input:5
Your input as a float:5.0
Your input as an integer:5
b) Enter a number:8.1
Your original input:8.1
Your input as a float:8.1
Value error
c)Enter a number:Ok!
Your original input:Ok!
Value error
d)Enter a number:
Your original input:
Value error
3. What is inline comment? Apply inline comment for the given python function again()
which accept user input and invoke respective functions[Ap][CO1]
defagain():
calc_again = input('Do you want to calculate again? type Y for YES or N for NO.')
ifcalc_again == 'Y':
calculate()
elifcalc_again == 'N':
print('See you later.')
else:
again()
Ans
An inline comment is a comment that is written on the same line as the code it is referring to. It
is used to provide additional information about the code or to explain its purpose.
Here’s an example of adding an inline comment to the given again() function:
Def again():
Calc_again = input(‘Do you want to calculate again? Type Y for YES or N for NO.’) # get user
input
If calc_again == ‘Y’: # check if user wants to calculate again
Calculate() # invoke calculate() function
Elifcalc_again == ‘N’: # check if user wants to quit
Print(‘See you later.’)
Else: # if user input is invalid, prompt again
Again() # invoke again() function recursively
In this example, the inline comments provide additional information about what each line of
code does, making it easier for other programmers (and even your future self) to understand
the function.

4. Write a python program which accept 2 numbers in the type of float from the user and
display the sum and its average in a neat format ? [Ap][CO1]
Ans:
Float1=5.1
Float2=4.9
Result1=Float1+Float2
Result2=Float1+Float2/2
Print(“The sum of given float numbers is :”+str(Result1))
Print(“The average of the given float numbers is:”+str(Result2))
5. Write a Python program to find the largest number among the three input
numbers[Ap][CO1]
Ans:
N1=int(input(“Enter the first number:”))
N2=int(input(“Enter the second number:”))
N3=int(input(“Enter the third number:”))
if N1>N2 and N1>N3:
print(“the largest number is:”+str(N1))
elif N2>N3:
print(“The largest number is:”+str(N2))
else:
print(“The largest number is:”+str(N3))
6. Write a Python program to find the factors of a number. Display the result as The factors of
50 are: 1, 2, 5, 10, 25, and 50 if the given number is 50[Ap][CO1]
Ans:
n=int(input(“Enter the number:”))
i=1
print(“the factors for given number are:”)
while i<:
if n%i==0:
print(i)
i=i+1
7. Write a Python program to accept the year from the user and ensure whether the given
year is a leap year or not? [Ap][CO1]
Ans:
year=int(input(“Enter the year to be checked:”))
If(year%4==0 and year%100!=0 or year%400==0):
Print(“the year is a leap year!”)
Else:
Print(“the year isn’t a leap year!”)

8. Write a Python program to generate a random number between 1 and 100 (including 1 and
100). Ask the user to guess the number, and then tell them whether they guessed too
low, too high, or exactly right. [Ap][CO1]
Ans:
Import random
Num=random.randint(1,100)
While True:
Guess=int(input(“Guess a number between 1 and 100:”))
If guess==num:
Print(“You won!!!”)
Break
elifi<num:
print(“Try higher”)
elifi>num:
print(“Try lower”)
print(“if guess less than 6 times you won”)
9. Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays using input),
compare them, print out a message of congratulations to the winner) [Ap][CO1]
The rules:
Rock beats scissors
Scissors beats paper
Paper beats rock
Ans:
import sys
U1=input(“what is your name?”)
U2=input(“what is your name?”)
U1_ans=input(“%s, do you want to choose rock ,paper or scissors?”%U1)
U2_ans=input(“%s, do you want to choose rock ,paper or scissors?”%U2)
def compare(user1,user2):
if user1==user2:
return(“It’s a tie!”)
elif user1==’rock’:
if user2==’scissors’:
return(“Rock wins”)
else:
return(“Paper wins”)
elif user1==’scissors’:
if user2==’paper’:
return(“scissors wins”)
else:
return(“Rock wins”)
elif user1==’paper’:
if user2==’rock’:
return(“Paper wins”)
else:
return(“scissors wins”)
else:
return(“Invalid input! You have not entered rock, paper or scissors, try again”)
sys.exit
print(compare(U1_ans, U2_ans))
10. Write a Python program to calculate the number of words and characters present in a
given sentence? [Ap][CO1]
Ans:
String=”Computer science”
Count=0
for i in range(0,len(String)):
count=count+1
print(“Total number of characters in a string:”+str(count))
Unit II
11. Accept mealcost from the user & calculate tax_rate as 8 %, tip_rate as 20%. Write a
Python program that will print the "receipt" for a meal purchase. The receipt should look
like this: [Ap][CO2]
Subtotal: 10.00
Tax: 0.8
Tip: 2.0
Total: 12.8
Ans:
1/meal_cost = 10.00

2|tax_rate=0.08

3|tip_rate=0.20

4 taxAmount = tax rate meal_cost #calculate taxAmount


5 tipAmount = tip_ratemeal_cost #calculate tipAmount

6 totalAmount = meal_cost + taxAmount + tipAmount #calculate totalAmount

7 print(“Subtotal:”+str(meal_cost)) # print subtotal

8]print(“Tax:”+str(taxAmount)) # print tax amount

9 print(“Tip:”+str(tipAmount)) # print tip amount

10 print(“Total:”+str(totalAmount)) # print total

12. 1| onList = True


2| inStock = True
3| onSale = False
4| rotten = False
Write Four conditions that use Boolean operators and, or and not. Then write all conditions
that includes the above variables (at least 3). Finally all conditions should return value True.
[Ap][CO2]
Ans
Here are four conditions that use Boolean operators and, or, and not with the given
variables:

 onList and inStock and not rotten


 onList and inStock and onSale
 not onList or (inStock and not rotten)
 not onSale or inStock or rotten
And here are at least three conditions that include the above variables and return True:
 onList and inStock # True because both are True
 not rotten or onSale # True because onSale is False
 not inStock or rotten or not onSale # True because not inStock is False
Note that there are many possible conditions that could use these variables and return True,
depending on what you’re trying to check for.

13. The given variables specify the start time for a run as well as the length of the run
in minutes.[Ap][CO2]
start_hour = 3
start_minute = 48
length = 172
print the time at which the run will end, using normal formatting (e.g. 6:40 for the
#original data above)
Ans
To print the time at which the run will end, we need to add the length of the run (in
minutes) to the start time, taking care to handle cases where the resulting hour or minute
value exceeds 24 or 60, respectively.

Here’s one way to do it:


Start_hour = 3
Start_minute = 48
Length = 172

# Calculate the total number of minutes for the run


Total_minutes = start_minute + length

# Calculate the number of hours and minutes that have passed


Elapsed_hours = total_minutes // 60
Elapsed_minutes = total_minutes % 60

# Calculate the final hour value, taking into account the starting hour and elapsed hours
Final_hour = (start_hour + elapsed_hours) % 24

# Format the output string with leading zeros, if necessary


Output_time = f”{final_hour:02d}:{elapsed_minutes:02d}”

Print(output_time)

When we run this code with the given values,


it will output:
10:40
This means the run will end at 10:40 AM.

14. Create four variables: [Ap][CO2]


#Create four variables named my_integer, my_decimal,my_string, and my_boolean.
#Assign to each variable a valueof the corresponding type (an integer for my_integer, a
#string of characters for my_string, etc.). You can choosewhatever values you want -- just
#make sure the variablenames and types are correct!
#Note that your code should *not* print anything. The onlyprinting should come from the
last for lines of thisstarter code.

#Write missing code!

#Don't modify these next lines! They're used for grading


print(type(my_integer))
print(type(my_decimal))
print(type(my_string))
print(type(my_boolean))
Ans
1 my_integer = 10 # set value 10 to variable my_integer 2❘my_decimal = 99.9 # set value
99.9 to variable my_decimal

3 my_string = “Python” # set value Python to variable my_string

4| my_boolean = True # set value True to variable my_boolean 5 print(type(my_integer))

6 print(type(my_decimal))

7 print(type(my_string))

8 print(type(my_boolean))

15. PrintFourVariables: [Ap][CO2]


#In the code below, four variables are created.Add to this code to make it find and print the
#types of each of these four variables, in the order in which they're declared (a, then b, then
#c, then d).

fromdatetime import date


import random
a = "Hello, world!"
b = date.today()
c = random.randint(0,100)
d = random
e=34.56

#Don't modify anything above this line!


#Write missing code!

Ans

1 from datetime import date

2 import random

3| a = “Hello, world!”
4| b = date.today()

5 c=random.randint(0,100)

6| d = random

7 print(type(a)) #finding & printing data type of a variable named a

8 print(type(b)) #finding & printing data type of a variable named b

9 print(type©) #finding & printing data type of a variable named c

10 print(type(d)) #finding & printing data type of a variable named d

16.CovertingtoStrings: [Ap][CO2]
#In the code below, four variables are created:an integer, a float, a date, and a boolean.
#Create four new variables: integerAsString,floatAsString, dateAsString, and booleanAsString.
#Convert the corresponding variables to strings.

fromdatetime import date


newInteger = 8
newFloat = 8.2
newDate = date.today()
newBoolean = False
#Write missing code!

#Don't edit the lines of code below!


print(integerAsString, type(integerAsString))
print(floatAsString, type(floatAsString))
print(dateAsString, type(dateAsString))
print(booleanAsString, type(booleanAsString))
Ans
1 from datetime import date

2| new_integer = 8

3| new_float = 8.2

4| new_date = date.today()

5 new_boolean = False

6] integer_as_string = str(new_integer) # converting integer to string 7| float_as_string =


str(new_float) # converting float to string

8|date_as_string = str(new_date) # converting date to string

9| boolean_as_string = str(new_boolean) # converting boolean to string

10 print(integer_as_string, type(integer_as_string)) 11 print(float_as_string,


type(float_as_string))

12 print(date_as_string, type(date_as_string))

13 print(boolean_as_string, type(boolean_as_string))

17. CovertingFromStrings: [Ap][CO2]

#In the code below, three strings are created. Only one can be converted to all three data
#types we're covering here (integers,floats, and booleans). Create three new variables called
#asInteger, asFloat, and asBoolean, select the only variable thatcan be converted to all three,
#and convert it.
a = "5.1"
b = "Hello!"
c = "5"
#Write missing code!

#Don't change the code below!


print(asInteger, type(asInteger))
print(asFloat, type(asFloat))
print(asBoolean, type(asBoolean))

Ans
1 a=”5.1”
2| b = “Hello!”

3|c=”5”

4 as integer = int© #convert string to integer

5 as float = float(b) #convert string to float

6 as boolean = bool(a) #convert string to boolean

7 print(as_integer, type(as_integer))

8 print(as float, type(as_float))

9 print(as_boolean, type(as_boolean))

18. SixVariableComparisons: [Ap][CO2]


#In the code below, we've created six variables: two strings,two dates, and two times.
#Complete the code to check to see if each pair of strings, dates, and times are considered
#Equalby Python.

fromdatetime import time


fromdatetime import date
string1 = "Hello, world"
string2 = "Hello, world"
date1 = date(2017, 1, 15)
date2 = date(2017, 1, 15)
time1 = time(12, 45)
time2 = time(12, 45)

#Don't modify the code above!

#Write code that Check if the values of string1 and string2 are equal and print the
results

# Write code that Check if the values of date1 and date2 are equal and print the
results

# Write code that Check if the values of time1 and time2 are equal and print the
results
Ans
1 from datetime import time

2 from datetime import date

3 mystery_string_1 = “Hello, world”

4| mystery_string_2 = “Hello, world”

5 mystery_date_1 = date(2019, 1, 15)

6| mystery_date_2 = date(2019, 1, 15)

7| mystery_time_1 = time(12,45)

8 mystery_time_2 = time(12,45)

9 print(mystery_string_1 == mystery_string_2) #compare two strings and print result

10 print(mystery_date_1 == mystery_date_2)) #compare two dates and print result

11 print(mystery_time_1 == mystery_time_2)) #compare two times and print result

19. GoOutToLunch: [Ap][CO2]


#In the code below, we've created a function called goOutToLunch().Just know that on the
#line you're writing,you'll have access to three boolean variables: hungry, broughtLunch,
#andhaveMoney.Complete the commented line such that the variable 'result' is:
# - True if hungry is true and if either broughtLunch is false orhaveMoney is true.
# - False otherwise.# The only line you should have to edit is the line starting with
#'result'. Edit this line so that 'result' receives a valuecorresponding to the reasoning above.
#You can add additional linesof code before it if you'd like, of course, but you don't have to
#in order to complete this exercise. Note that if you do add additionallines, they should be
#indented with the same number of spaces as thecurrent line.

#Function goOutToLunch(hungry, broughtLunch, haveMoney)


#Takes as input three booleans: hungry, broughtLunch, and haveMoney.
#Returns as output True if the person should go out to lunch, false
#otherwise.
defgoOutToLunch(hungry, broughtLunch, haveMoney):
#In any code you write here, you'll have access to three variables:
#hungry, broughtLunch, and haveMoney, just as if they had been
#created the way you've seen before.
#Write your code according to the directions above

return result

#You may modify the values of the variables below to test out your answer
testHungry = True
testBroughtLunch = False
testHaveMoney = True
print("Result:", goOutToLunch(testHungry, testBroughtLunch, testHaveMoney))
Ans
1| hungry = True

2 coworkers going = False

3 brought lunch = False

# checking hungry with other condition

4 print(hungry and (coworkers going or not brought_lunch))

20. FiveMathFunctions: [Ap][CO2]


#Below are the function definitions for five functions: addTwo,subtractTwo, multiplyByTwo,
#divideTwo, and modulusTwo. You don'tneed to worry about how these functions work.
#Complete thedesignated line according to the directions for what the lineshould accomplish.
#You should only need to edit those lines that ask you to completethem, but you can modify
#the code at the bottom to test out yourcode a bit.

defaddTwo(myVar):
#write your code so that myVar equals two more than myVar

returnmyVar

defsubtractTwo(myVar):
# write your code so that myVar equals two less than myVar

returnmyVar

defmultiplyByTwo(myVar):
# write your code so that myVar equals two times myVar

returnmyVar
defdivideByTwo(myVar):
# write your code so that myVar equals myVar divided by two

returnmyVar

defmodulusTwo(myVar):
# write your code so that result equals the remainder when myVar is divided by
# two

returnmyVar

#You may change this variable to test out your code


myTestVar = 5
print("Add two:", addTwo(myTestVar))
print("Subtract two:", subtractTwo(myTestVar))
print("Multiply by two:", multiplyByTwo(myTestVar))
print("Divide by two:", divideByTwo(myTestVar))
print("Modulus two:", modulusTwo(myTestVar))

Ans

1 mystery value_1-6

2 mystery_value_2=2

3) print(mystery value 1+ mystery value_2) # calculate addition and print result

4) print(mystery value 1-mystery value_2) # calculate subtraction and print result

51 print(mystery value_1 mystery value 2) # calculate multiplication and print result

61 print(mystery value 1/ mystery_value_2) # calculate divide and print result

7) print(mystery value_1 % mystery value_2) # calculate modulus and print result


Unit III

21. a) Which line in the code below will cause an error? [Ap][CO3]

1| myAge = 17
2| if myAge>= 18:
3| print("I can vote now!")
Ans
For the given code:
1| myAge = 17
2| if myAge>= 18:
3| print(“I can vote now!”)
Line 3 will not cause an error, but it will not print anything because the condition in line 2 is
False. Since myAge is assigned a value of 17 in line 1, the condition myAge>= 18 in line 2
is False, so the code inside the if block (line 3) will not be executed.

b) Finish the code in lines 6 and 7 so the code prints a restaurant suggestion if you're
craving pizza!
1| craving = "pizza"
2| if craving == "tacos":
3| print("Go to Takorea!")
4| elif craving == "sushi":
5| print("Go to Satto!")
6| #Complete this line below!
7| #Complete this line below!
Ans
To finish the code in lines 6 and 7 so it prints a restaurant suggestion if you’re craving
pizza, you can do the following:
Craving = “pizza”
If craving == “tacos”:
Print(“Go to Takorea!”)
Elif craving == “sushi”:
Print(“Go to Satto!”)
Elif craving == “pizza”: # add this line to check if craving is pizza
Print(“Go to Pizza Hut!”) # add your restaurant suggestion for pizza
Else:
Print(“Sorry, I don’t know where to go for that.”)
In this example, we add an additional elif statement in line 5 to check if craving is equal to
“pizza”. If it is, we print our restaurant suggestion for pizza in line 6. If craving is not equal
to any of the other options, we print a generic message in the else block.

22. Write output of the following code? [Ap][CO3]


1| myFood = "chocolate cupcakes"
2| yourFood = "hawaiian pizza"
3|
4| if myFood == yourFood:
5| print("We like the same food.")
6| else:
7| print("We have different tastes.")
8|
9| if len(myFood) > 8:
10| print("My food has a long name.")
11| eliflen(yourFood) > 8:
12| print("Your food has a long name.")
13| else:
14| print("We like foods with short names.")
15|
16| if len(myFood) >len(yourFood):
17| print("My food has a longer name than yours.")
18| else:
19| print("Your food has a longer name than mine.")
20|
21| if yourFood == "pasta":
22| print("Mamma mia!")
23| else:
24| print(yourFood)
[Hint: The len() function returns the length of the string inside parentheses. So, len("hello")
would be 5 because there are 5 letters in "hello". len(myFood) would be 18 because
myFood is "chocolate cupcakes", and there are 18 letters in "chocolate cupcakes".]

Ans

The output of the given code will be:

We have different tastes.

My food has a long name.

Your food has a longer name than mine.

Hawaiian pizza

Explanation:

 In line 1 and 2, two variables myFood and yourFood are assigned string values.
 In line 4-6, an if statement checks if myFood is equal to yourFood. Since the two
strings are different, the code in the else block will be executed, and it will print
“We have different tastes.”

 In line 9-14, another if statement checks the length of the two strings. Since
len(myFood) is greater than 8 (it is 18), the code in line 10 will be executed, and it
will print “My food has a long name.”
 In line 16-19, another if statement compares the length of the two strings. Since
len(myFood) (18) is not greater than len(yourFood) (13), the code in the else block
will be executed, and it will print “Your food has a longer name than mine.”

 In line 21-24, another if statement checks if yourFood is equal to “pasta”. Since it is


not, the code in the else block will be executed, and it will print “hawaiian pizza”.

23. What is the output of the code below? [Ap][CO3]

a) 1| myGPA = 3.0
2| requirement = 3.0
3| if myGPA> requirement:
4| print("Welcome to the club!")
5| else:
6| print("Sorry, you don't have the GPA required to join.")
b)
1| clubMembers = ["John", "Jenny", "Jason", "Jane"]
2| bannedMembers = ["Jack", "Jasmine", "Jared"]
3| myName = "Jenny"
4| if myName in clubMembers:
5| print("Welcome back!")
6| elifmyName in bannedMembers:
7| print("You've been banned!")
8| else:
9| print("Sorry, you're not on the list.")
Ans
a) The output will be “Welcome to the club!” since the condition in line 3 is true, since
myGPA is equal to requirement.
b) The output will be “Welcome back!” since myName is “Jenny” and it is present in the
clubMembers list.

24. What is the output of the code below? [Ap][CO3]


1| time = 2359
2| tirednessLevel = 90
3| homeworkDone = True
4| earlyClass = False
5|
6| if time >= 2300:
7| if tirednessLevel>= 85:
8| if homeworkDone == True:
9| if earlyClass == True:
10| print("Go to sleep!")
11| else:
12| print("Go to sleep soon...")
13| else:
14| print("Finish your work, then sleep!")
15| else:
16| print("Stay up a little longer!")
17| else:
18| print("It's still pretty early.")
Ans
If we assume that all variables are not changed, the output of the code will be “Finish your
work, then sleep!” because the conditions in lines 6-8 are true, but the condition in line 9 is
false, so the code executes the else statement in line 14.

25. What is the output of the below code? If no output then write "No Output".[Ap][CO3]
a)
1| fahrenheit = 80
2| suggestion = "pants"
3| if fahrenheit>= 70:
4| suggestion = "shorts"
5| print(suggestion)
b)
1| myAge = 17
2| if myAge>= 18:
3| voteStatus = True
4| print(vvoteStatus
Ans
a) The output will be “shorts” because the condition on line 3 is True, so the value
of “suggestion” is changed to “shorts” on line 4, and then printed on line 5.

b) There will be an error because “voteStatus” is not defined if the condition on line
2 is False. To fix this, you could define “voteStatus” before the if statement, like
this:
1| myAge = 17

2| voteStatus = False

3| if myAge>= 18:

4| voteStatus = True

5| print(voteStatus)

This code will print “False” because the condition on line 3 is False, so “voteStatus” remains
False.

26. Freezing: [Ap][CO3]

Given temperature = -3.7, celsius = True

#You may modify the lines of code above, but don't move them!When you Submit your code,
#we'll change these lines toassign different values to the variables.Above are given two
#variables. temperature is a float that holds a temperature. celsius is a boolean that represents

#whether the temperature is in Celsius; if it's False, then the given temperature is actually in
#Fahrenheit.

#Add some code below that prints "Freezing" if the valuesabove represent a freezing
temperature, and "Not freezing"if they don't.

#In Celsius, freezing is less than or equal to 0 degrees.In Fahrenheit, freezing is less than or
equal to 32 degrees.

#Write missing code!


Ans
1 temperature = -3.7 #test input value

2) celsius = True #test input value

# checking with two conditions

3] if(temperature <= 0 and celsius) or (temperature < 32 and celsius == False); 4)


print(“Freezing”) #print if condition is true

5) else:
6) print(“Not freezing”) #print if condition is not true

27. Mystery Loop: [Ap][CO3]

mystery_int = 5

#You may modify the lines of code above, but don't move them!When you Submit your code,
#we'll change these lines toassign different values to the variables.

#In math, factorial is a mathematical operation where aninteger is multipled by every number
between itself and 1.For example, 5 factorial is 5 * 4 * 3 * 2 * 1, or 120.

#Factorial is represented by an exclamation point: 5!

#Use a for loop to calculate the factorial of the numbergiven by mystery_int above. Then, print
#the result.#Hint: Running a loop from 1 to mystery_int will give youall the integers you need
#to multiply together. You'll needto track the total product using a variable declared before

#starting the loop, though!

#Write missing code!


Ans
Here’s the code to calculate the factorial of mystery_int using a for loop:
Mystery_int = 5
Factorial = 1
For I in range(1, mystery_int + 1):
Factorial *= i
Print(factorial)

This code initializes the variable factorial to 1 and then uses a for loop to iterate from 1 to
mystery_int. Inside the loop, it multiplies factorial by the loop variable i. Finally, it prints the
value of factorial after the loop has finished executing.

When mystery_int is 5, this code will output the value 120, which is the factorial of 5.

28. EveryThird: [Ap][CO3]

mystery_int = 50

#You may modify the lines of code above, but don't move them!When you Submit your code,
#we'll change these lines toassign different values to the variables.

#Write a for loop that prints every third number from 1 tomystery_int inclusive (meaning that
#if mystery_int is 7, itprints 1, 4, and 7). Print each number on a separate line.
#Hint: There are multiple ways to do this! You might use themodulus operators, or you could
#use the third argument forrange().

#Write missing code!


Ans
1| mystery_int = 50 #test input value

# loop starts from 1 and extends uptomystery_int and step value is 3

2 for loopCounter in range(1,mystery_int+1,3):

3 print(loopCounter) # print each loopCounter value

29.ReturnDate: [Ap][CO3]

#Write a function called get_todays_date that returnstoday's date as a string, in the form
year/month/day.

#For example, if today is January 15th, 2017, then itwould return 2017/1/15.

# Now, you're converting it to a function that returns the string.

#Note that the line below will let you access today's dateusingdate.today() anywhere in your
code.

fromdatetime import date

#Write missing code!

#If you want to test your code, you can do so by callingyour function below. However, this is
no longer requiredfor grading.

print(get_todays_date())

Ans
1 from datetime import date

21 def get_todays_date(): # function starts

3) todays date date.today()

# assign date value as given format year/month/day


4] datestring = str(todays_date.year)+”/”+ str(todays_date.month)+”/”+str(todays_date.day)
51 return datestring #function returns

6) print(get todays_date()) invoking a function

30. HideandSeek: [Ap][CO3]

#Write a function called hide_and_seek. The function shouldhave no parameters and return no
value; instead, whencalled, it should just print the numbers from 1 through 10,follow by the
text "Ready or not, here I come!". Eachnumber and the message at the end should be on its
ownline.

#Then, call the function.There should be no print statements outside the function.

#Write your function code!

#And write code for Calling your function!

Ans

1 def hide_and_seek():

2 for loopCounter in range(1,11):

3 print(loopCounter)

4 print(“Ready or not, here I come!”)

5 hide_and_seek() #Invoking function

Unit IV

31. Steps: [Ap][CO5]


#Write a function called "steps" that should return a string that, if printed, looks like this:
#111
#222
#333
#
#Note that the characters at the beginning of the second and third lines must be tabs, not
spaces. There should be onetab on the second line and two on the third line.
#You may only declare ONE string in your function.
#Hint: Don't overthink this! We're literally just asking youto return one single string that just
holds the above text.You don't have to build the string dynamically or anything.

#Write missing code!


#The line below will test your function.
print(steps())

Ans
1❘ def steps(value):

2 output=””

31 for loopCounter in range(1,value+1):#outer loop starts from here

4 output += (str(loopCounter)+str(loopCounter) + str(loopCounter)+”\n”)

5 while loopCounter>0:#inner loop starts from here

6| output += “\t”

7 loopCounter=loopCounter-1:#inner loop ends here

8 return output): #outer loop ends here

9 print(steps(3)) #calling function with a parameter 3

10 print(steps (6)))) #calling function with a parameter 6

32. What is the value of myString immediately after each of the following lines has run?
[Ap][CO5]
Do not include quotation marks in your responses. Write your answer as follows:
After Line Number 1: #write your answer
After Line Number 2: #write your answer
After Line Number 3: #write your answer
After Line Number 4: #write your answer
After Line Number 5: #write your answer
1| myString = "Hello"
2| myString += "!"
3| myString = "!" + myString
4| myString = "?" + myString + "?"
5| myString += myString
Ans
After Line Number 1: Hello
After Line Number 2: Hello!
After Line Number 3: !Hello!
After Line Number 4: ?!Hello!?
After Line Number 5: ?!Hello!?
Hello!?

33. 1| for i in range(1, 6):


2| #Insert your answer from below
Imagine we were writing a for loop, and on every iteration of the for loop, we wanted to print
out the following message:
Loop iteration #1 beginning now
Note: The number after the pound sign would change with each iteration of the loop.
[Ap][CO5]
Ans
Here’s an example code block that should print the desired message on each iteration of the
loop:
For I in range(1, 6):
Print(“Loop iteration #” + str(i) + “ beginning now”)
The range(1, 6) function call generates the numbers 1 through 5, which the loop variable I
takes on successively with each iteration of the loop. The str(i) call converts the integer I to a
string so that it can be concatenated with the rest of the message using the + operator. Finally,
the print() function outputs the complete message to the console.

34.What will be the output of each of the following code segments? [Ap][CO5]
(Note: this exercise is case-sensitive.)
a) 1| myString1 = "CS1301"
2| myString2 = myString1.replace("CS", "Computer Science")
3| myString3 = myString2.replace(" ", "")
4| myString4 = myString3.upper()
5| print(myString4)
b)1| myString = "CS1301"
2| myString = myString.replace("CS", "computer science")
3| myString = myString.replace("1301", "101")
4| myString = myString.replace("e1", "e 1")
5| myString = myString.title()
6| print(myString)

Ans
a) The output of this code segment will be:
COMPUTERSCIENCE1301
This code segment uses the replace() method to replace the substring “CS” in myString1
with the string “Computer Science”. This produces the string “Computer Science1301”.
Then, the replace() method is called again to remove all spaces in the string. This produces
the string “ComputerScience1301”. Finally, the upper() method is called to convert the
string to all uppercase letters.
b) The output of this code segment will be:
Computer Science 101
This code segment also uses the replace() method to replace the substring “CS” with the
string “computer science”. This produces the string “computer science1301”. Then, the
replace() method is called again to replace the substring “1301” with the string “101”. This
produces the string “computer science101”. Next, the replace() method is called again to
replace the substring “e1” with the string “e 1”. This produces the string “computerscienc e
101”. Finally, the title() method is called to capitalize the first letter of each word in the
string.
35. a) What will be the output of the following code? [Ap][CO5]
1| a = 6
2| b = 2
3| c = 9
4| myTuple = (a, b, c)
5| print(myTuple)
b)
1| aString = "What's up?"
2| aFloat = 26.2
3| aInt1 = 9
4| aCharacter = "J"
5| aInt2 = -10
6|
7| aTuple = (aString, aFloat, aInt1, aCharacter, aInt2)
8| #Line of code here
What will be the value of mySlice if the following line is placed on line 8?
mySlice = aTuple[:3]

Ans
a) The output of this code will be:
(6, 2, 9)
This code creates a tuple named myTuple containing the values of variables a, b, and c. The
print() function is then called to output the entire tuple to the console
b) If the following line is placed on line 8:
mySlice = aTuple[:3]
Then mySlice will be a tuple containing the first three elements of aTuple, which are aString,
aFloat, and aInt1.
So the value of mySlice will be:
(“What’s up?”, 26.2, 9)

36. Consider the following:


1| def circleInfo(radius):
2| peri = 2 * 3.14 * radius
3| area = 3.14 * (radius ** 2)
4| return (peri, area)
5| aRadius = 3
6| aTuple = circleInfo(aRadius)
7| #Line of code here
The function above takes as input a radius and returns as output a tuple with two values: the
perimeter of the corresponding circle, and the area of the corresponding circle. For reference, a
circle with radius 3 will have a perimeter of ~18.84 and an area of ~28.26.
What will be the output of the above code when the following lines are placed on line 7?
[Ap][CO5]
a) print(aTuple[0]) b) print(aTuple[1])

Ans
If the following lines are placed on line 7:

a) Print(aTuple[0])

The output will be:


18.84
This is because aTuple is assigned the result of calling circleInfo() with aRadius as an argument.
circleInfo() returns a tuple containing two values, where the first value is the perimeter of the
circle with the given radius. In this case, aRadius is 3, so the perimeter is 2 * 3.14 * 3 = 18.84.
The [0] index is used to access the first element (i.e. the perimeter) of the tuple.
b) Print(aTuple[1])

The output will be:


28.26
This is because aTuple is a tuple containing two values, where the second value is the area of
the circle with the given radius. In this case, aRadius is 3, so the area is 3.14 * (3 ** 2) =
28.26. The [1] index is used to access the second element (i.e. the area) of the tuple.

37. Consider the following:


1| myList1 = [1, 2, 3, -2, 0]
2| myList2 = [-4, -7, -6]
3| #Line of code here
Enter the value of myList1 after the following lines of code are run. Assume that for each line, it
is placed directly on line 3; in other words, when answering the second prompt
(myList1.append(-22)), assume that the first prompt (myList1.sort()) did not run. [Ap][CO5]
a) myList1.sort()
b) myList1.append(-22)
c) myList1.extend(myList2)
d) myList1.insert(0,99)
Ans
Assuming each line is placed directly on line 3, the resulting value of myList1 will be:

a) After running myList1.sort(), the value of myList1 will be:


[-2, 0, 1, 2, 3]
b) After running myList1.append(-22), the value of myList1 will be:
[1, 2, 3, -2, 0, -22]
b) After running myList1.extend(myList2), the value of myList1 will be:
[1, 2, 3, -2, 0, -4, -7, -6]
c) After running myList1.insert(0, 99), the value of myList1 will be:
[99, 1, 2, 3, -2, 0]
Note that the insert() method inserts the specified element (99) at the specified position (index
0) and shifts all other elements to the right.

38. Consider the following:


1| GeorgiaAreaCodes = [404, 770, 678, 706, 762, 229, 423, 912, 478]
2| #Lines below go here
3| #Lines below go here
4| #Lines below go here
Write your code segments, if placed starting on line 2 above, will print each of the Georgia area
codes given in the list on their own line, then close without error? [Ap][CO5]

Ans
Here are three possible ways to print each Georgia area code on its own line:

1)Using a for loop:


1| GeorgiaAreaCodes = [404, 770, 678, 706, 762, 229, 423, 912, 478]
2| for code in GeorgiaAreaCodes:
3| print(code)
2)Using a while loop:
1| GeorgiaAreaCodes = [404, 770, 678, 706, 762, 229, 423, 912, 478]
2| I = 0
3| while I <len(GeorgiaAreaCodes):
4| print(GeorgiaAreaCodes[i])
5| I += 1
3)Using a list comprehension:
1| GeorgiaAreaCodes = [404, 770, 678, 706, 762, 229, 423, 912, 478]
2| [print(code) for code in GeorgiaAreaCodes]

39. Imagine you had a list of integers called myAccountList which you want to write to a file
Accounts.txt, with each number on a separate line. Every item in myAccountList is an
integer. Write your code segments would accomplish this? [Ap][CO6]
Ans
Here’s how you could write the contents of myAccountList to a file named “Accounts.txt”, with
each number on a separate line:
myAccountList = [1, 2, 3, 4, 5]

with open(“Accounts.txt”, “w”) as file:


for num in myAccountList:
file.write(str(num) + “\n”)
In the code above, we open the file “Accounts.txt” in write mode (“w”), which creates the file if
it does not already exist and truncates it (empties it) if it does. We then iterate over
myAccountList, converting each number to a string using str(num), and writing it to the file
using file.write(). We add “\n” after each number to write it to a new line in the file. Finally, we
close the file using the with statement, which automatically handles closing the file for us.

40. Refer the code below and answer the following question? [Ap][CO6]
#CreatesmyDictionary with David=4045551234, Lucy=4045555678,
#Vrushali=4045559101
myDictionary = {"David" : "4045551234", "Lucy" : "4045555678",
"Vrushali" : "4045559101"}
print(myDictionary)

#Checks if "David" is a key in the dictionary


# if it is true then print "David is already in myDictionary!" and add
# David2= 4045551121
#otherwise print "David is already in myDictionary!" and print
# David=4045551234
Ans
Here’s the code with the requested comments:
# Creates a dictionary called myDictionary with three key-value pairs
myDictionary = {“David” : “4045551234”, “Lucy” : “4045555678”, “Vrushali” : “4045559101”}

# Checks if “David” is a key in the dictionary


If “David” in myDictionary:
# If “David” is in the dictionary, print a message and add a new key-value pair
Print(“David is already in myDictionary!”)
myDictionary[“David2”] = “4045551121”
else:
# If “David” is not in the dictionary, print a message and print the existing value
Print(“David is not in myDictionary!”)
Print(“David=4045551234”)
The output of this code will always be:
David is already in myDictionary!
This is because “David” is already a key in the dictionary, so the first branch of the if statement
will always be executed. The code will add a new key-value pair “David2” : “4045551121” to the
dictionary, but this pair will not be printed or otherwise displayed.

Unit V
41. Phone: [Ap][CO7]
#Write a class named "Phone". The Phone class should have an attribute called "storage" which
defaults to128, and an attribute called "color" which defaultsto "red".
#Hint: 'attribute' is another common word for'instance variable'.

#Write missing code!

#Below are some lines of code that will test your function.You can change the value of the
#variable(s) to test yourfunction with different inputs.

#If your function works correctly, this will originally print 128 and red, each on a separate line.
new_phone = Phone()
print(new_phone.storage)
print(new_phone.color)

Ans
Here’s the code for the Phone class:
Class Phone:
Def __init__(self, storage=128, color=”red”):
Self.storage = storage
Self.color = color
The Phone class has two attributes: storage and color, which default to 128 and “red”,
respectively. The __init__ method is a special method that is called when a new instance of the
class is created. It takes two arguments (storage and color) with default values, and sets the
instance variables self.storage and self.color to these values.

The lines of code at the bottom create a new instance of the Phone class (new_phone) and
print the values of its storage and color attributes.
If you run the code, it will output:
128
Red
These are the default values of the storage and color attributes for the new_phone instance,
respectively.
42. Use the given code and answer the following questions? [Ap][CO7]
1| class Student:
2| def __init__(self):
3| self.studentName = ""
4| self.GPA = 0.0
5| self.creditHours = 0
6| self.enrolled = True
7| self.classes = []
Using the same Student class from before, let's imagine we want to create a new student with
the following values:
Student's Name: "George P. Burdell"
Enrolled: True
GPA: 3.9
a) enter the line of code that will create a variable called newStudent of type Student. Note that
all parts of this exercise are case-sensitive, and you should avoid using duplicate spaces or
switching between quotes and apostrophes for creating strings.
b) enter the line of code that will set the value of enrolled fornewStudent to the boolean True
andNext, enter the line of code that will set the value of GPA for newStudent to the float
3.9

Ans
a) To create a variable called newStudent of type Student with the specified attributes, we
can use the following code:
newStudent = Student()
newStudent.studentName = “George P. Burdell”
newStudent.enrolled = True
newStudent.GPA = 3.9
The first line creates a new instance of the Student class and assigns it to the variable
newStudent. The next three lines set the attributes studentName, enrolled, and GPA for
the newStudent instance, respectively.
b) To set the value of enrolled for newStudent to the boolean True, we can use the
following code:
newStudent.enrolled = True
This line sets the enrolled attribute of the newStudent instance to True.
c) To set the value of GPA for newStudent to the float 3.9, we can use the following code:
newStudent.GPA = 3.9
This line sets the GPA attribute of the newStudent instance to 3.9.
43. Use the given code and answer the following questions? [Ap][CO7]
1| class Student:
2| def __init__(self):
3| self.studentName = ""
4| self.GPA = 0.0
5| self.creditHours = 0
6| self.enrolled = True
7| self.classes = []
Using the same Student class from before, let's imagine we want to create a new student with
the following values:
Credit Hours: 1334
Classes: ["CS1301", "PHYS3001", "ISYE3029"]
a) enter the line of code that will set the value of creditHoursfornewStudent to the integer 1334
b) enter the line of code that will set the value of classes for newStudent to the list ["CS1301",
"PHYS3001", "ISYE3029"]
Ans
a) To set the value of creditHours for newStudent to the integer 1334, we can use the
following line of code
newStudent.creditHours = 1334
b) To set the value of classes for newStudent to the list [“CS1301”, “PHYS3001”,
“ISYE3029”], we can use the following line of code
newStudent.classes = [“CS1301
44. Number: [Ap][CO7]
#Write a class named "Number" with one attribute called "value" which defaults to 0
and#another attribute called "even" which defaults to True.Next, create an instance of this
class #and assign it toa variable called "number_instance".Then, set the value attribute to 101
and #the evenattribute to False.
#Write missing code!

#Note that this exercise does not print anything bydefault. You're welcome to add print
#statements to debugyour code when running it. Note that the autograderwill check both your
#value for number_instance and yourdefinition of the class Number.

Ans
Here’s the code that satisfies the requirements of the problem statement
Class Number:
Def __init__(self):
Self.value = 0
Self.even = True

Number_instance = Number()
Number_instance.value = 101
Number_instance.even = False
This code defines the Number class with value and even attributes, creates an instance of this
class named number_instance, and then sets the value attribute to 101 and the even attribute
to False.

45. Consider given code before writing your answer? [Ap][CO7]


create one instance named myNewPerson, assign new value for firstname=”Ragul”,
lastname=”Dravid”, eyecolor=”browny” and age = 56 and print all values
#Define the class Person
class Person:
#Create a new instance of Person
def __init__(self):
#Person's default values
self.firstname = "[no first name]"
self.lastname = "[no last name]"
self.eyecolor = "[no eye color]"
self.age = -1

#Create two new Persons and assign them to myPerson1


myPerson1 = Person()
myPerson1.firstname = "David"
print("myPerson1: " + myPerson1.firstname)
Ans
To create an instance named myNewPerson with the values firstname=”Ragul”,
lastname=”Dravid”, eyecolor=”browny”, and age=56, and then print all the values, you would
modify the code as follows:
# Define the class Person
Class Person:
# Create a new instance of Person
Def __init__(self):
# Person’s default values
Self.firstname = “[no first name]”
Self.lastname = “[no last name]”
Self.eyecolor = “[no eye color]”
Self.age = -1

# Create a new instance of Person and set its attributes


myNewPerson = Person()
myNewPerson.firstname = “Ragul”
myNewPerson.lastname = “Dravid”
myNewPerson.eyecolor = “browny”
myNewPerson.age = 56

# Print the values of myNewPerson’s attributes


Print(“First Name:”, myNewPerson.firstname)
Print(“Last Name:”, myNewPerson.lastname)
Print(“Eye Color:”, myNewPerson.eyecolor)
Print(“Age:”, myNewPerson.age)

46. Consider given code before writing your answer? [Ap][CO7]


create one constructor with two parameters firstname and lastname, assign values “Ragul”
and “Dravid”
#Define the class Person
class Person:
#Create a new instance of Person
def __init__(self):
#Person's default values
self.firstname = "[no first name]"
self.lastname = "[no last name]"
self.eyecolor = "[no eye color]"
self.age = -1

#Create two new Persons and assign them to myPerson1


myPerson1 = Person()
myPerson1.firstname = "David"
print("myPerson1: " + myPerson1.firstname)
Ans
To create a constructor with two parameters firstname and lastname, you can modify the
__init__ method of the Person class as follows:
Class Person:
# Create a new instance of Person with firstname and lastname
Def __init__(self, firstname, lastname):
# Initialize Person’s attributes
Self.firstname = firstname
Self.lastname = lastname
Self.eyecolor = “[no eye color]”
Self.age = -1

# Create a new Person instance with firstname “Ragul” and lastname “Dravid”
myNewPerson = Person(“Ragul”, “Dravid”)

# Print the values of myNewPerson’s attributes


Print(“First Name:”, myNewPerson.firstname)
Print(“Last Name:”, myNewPerson.lastname)
Print(“Eye Color:”, myNewPerson.eyecolor)
Print(“Age:”, myNewPerson.age)
This will create a new instance of Person with the given firstname and lastname attributes and
print out all the attribute values.

47. Consider the following:


1| class Student:
2| def __init__(self, studentName, enrolled):
3| self.studentName = studentName
4| self.GPA = 0.0
5| self.creditHours = 0
6| self.enrolled = enrolled
7| self.classes = []
Imagine we wanted to build a getter for a student's GPA. We want to do that because we want
to log every time the GPA is read by printing the text, "GPA read". Write your code for getter
would accomplish this? [Ap][CO7]
Ans
To create a getter for a student’s GPA that logs every time the GPA is read by printing “GPA
read”, we can define a method called get_GPA in the Student class. Here’s how we can modify
the given code to accomplish this:
Class Student:
Def __init__(self, studentName, enrolled):
Self.studentName = studentName
Self._GPA = 0.0
Self.creditHours = 0
Self.enrolled = enrolled
Self.classes = []

Def get_GPA(self):
Print(“GPA read”)
Return self._GPA

@property
Def GPA(self):
Return self.get_GPA()
Note that we’ve added a new method called get_GPA, which logs that the GPA is being read
and then returns the actual value of _GPA. We’ve also defined a @property called GPA that calls
the get_GPA method. By doing so, whenever the GPA attribute is accessed, it will log that the
GPA is being read and then return the actual value of _GPA.

Additionally, we’ve changed the name of the _GPA attribute to make it private. This is a good
practice to follow in Python to indicate that this attribute should not be modified directly by
external code. Instead, it should be accessed and modified through the public methods and
properties of the class.

48. Consider the class:


1| class Student:
2| def __init__(self, studentName, enrolled):
3| self.studentName = studentName
4| self.GPA = 0.0
5| self.creditHours = 0
6| self.enrolled = enrolled
7| self.classes = []
Imagine we wanted to build a setter for a student's GPA. We want to do that because we want
to log every time the GPA is changed by printing the text, "GPA changed from [old] to [new]",
where [old] and [new] are replaced with the previous and new value.Write your code for setter
would accomplish this?
Ans
Here’s an example code for a setter method in the Student class that logs every time the GPA is
changed
Class Student:
Def __init__(self, studentName, enrolled):
Self.studentName = studentName
Self._GPA = 0.0
Self.creditHours = 0
Self.enrolled = enrolled
Self.classes = []

@property
Def GPA(self):
Return self._GPA

@GPA.setter
Def GPA(self, value):
Old_GPA = self._GPA
Self._GPA = value
Print(f”GPA changed from {old_GPA} to {value}”)
In this code, we define a getter method for the GPA attribute using the @property decorator.
We then define a setter method for the GPA attribute using the @GPA.setter decorator.

Inside the setter method, we first store the old value of GPA in a variable called old_GPA. Then
we update the _GPA attribute with the new value passed to the setter method. Finally, we log
the change by printing the message with the old and new values interpolated into the string
using f-strings.
Note that we use a leading underscore in the attribute name _GPA to indicate that it is intended
to be a “private” attribute that should not be accessed directly from outside the class. Instead,
it should be accessed through the GPA property.

49. Consider the class:


1| class Student:
2| def __init__(self, studentName, enrolled):
3| self.studentName = studentName
4| self.GPA = 0.0
5| self.creditHours = 0
6| self.enrolled = enrolled
7| self.classes = []
Instead of just changing the value of GPA directly, we probably want to instead calculate a new
GPA based on the old value and a new grade.
Below is the beginning of a function to do this, but it has some gaps. Select the code that
should fill in each gap.
8| def updateGPA([1]):
9| newTotal = (newGrade * newHours) + (self.GPA * self.creditHours)
10| [2]
11| [3]
write your code for [1], [2] and [3]? [Ap][CO7]

Ans
[1]: You need to pass in self and the new grade and credit hours as parameters, so the correct
code for this line would be:
Def updateGPA(self, newGrade, newHours):
[2]: You need to calculate the new total number of grade points (i.e., the total number of grade
points from the new grade and credit hours, plus the total number of grade points from the
student’s previous grades). The code for this line should be:
Self.GPA = (newTotal) / (self.creditHours + newHours)
[3]: You need to print a message indicating that the GPA has been updated. The code for this
line should be:
Print(f”GPA changed from {self.GPA – (newGrade * newHours) / self.creditHours} to
{self.GPA}”)

50. Write Python code for generatingfibonacci series. In fibonacci series the first two numbers
in the Fibonacci sequence are 0 and 1 and each subsequent number is the sum of the previous
two. For examplefibonacci series is 0, 1, 1, 2, 3, 5, 8,13, 21… [Ap][CO8]
[Hint: create function named fibSeries with one parameter named userInput]

Ans

Here is an example Python code for generating a Fibonacci series up to a user-defined limit

Def fibSeries(userInput):

Fib = [0, 1]
While fib[-1] <userInput:

Fib.append(fib[-1] + fib[-2])

Return fib[:-1]

userInput = int(input(“Enter the limit for the Fibonacci series: “))

print(fibSeries(userInput))

In this code, we first define a function named fibSeries that takes one parameter named
userInput (which represents the limit of the Fibonacci series).

Inside the function, we first create a list fib with the first two numbers of the Fibonacci
sequence (0 and 1). We then use a while loop to add new numbers to the fib list until the last
number in the list is greater than or equal to the userInput.

Finally, we return the fib list without the last element (which is greater than the userInput).

Outside the function, we ask the user to enter the limit for the Fibonacci series, and then call
the fibSeries function with the user input as the argument. The function returns the Fibonacci
series up to the user input, which we then print to the console.

You might also like