Python Answer
Python Answer
(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
Ans:
c)if myNum1<myNum2:
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
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
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.
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:
iflen(user_input) <3:
continue
else:
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”]
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)
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.
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:]).
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.
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”
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)
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 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)
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.
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
# 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|
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]
Ans
String1 = “Hi!”
String2 = “Hey!”
String3 = “Hello!”
print(string1, file=outputFile)
print(string2, 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 = []
myStudent = Student()
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 = []
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.
class test:
self.a=a
def display(self):
print(self.a)
obj=test()
obj.display()
Ans
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”.
class change:
self.a = x + y + z
x = change(1,2,3)
y = getattr(x, 'a')
print(x.a)
Ans
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.
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:
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.
def Demo:
def __init__(self):
__a = 1
self.__b = 1
self.__c__ = 1
__d__= 1
Ans
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.
class Demo:
def __init__(self):
self.a = 1
self.__b = 1
def get(self):
returnself.__b
obj = Demo()
print(obj.get())
Ans
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:
3| self.name = name
4| self.owner = owner
5| def speak(self):
6| print("WOOF!")
7|
8| class Owner:
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:
3| self.name = name
4| self.owner = owner
5| def speak(self):
6| print("WOOF!")
7|
8| class Owner:
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”)
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
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.
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
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.
# Calculate the final hour value, taking into account the starting hour and elapsed hours
Final_hour = (start_hour + elapsed_hours) % 24
Print(output_time)
6 print(type(my_decimal))
7 print(type(my_string))
8 print(type(my_boolean))
Ans
2 import random
3| a = “Hello, world!”
4| b = date.today()
5 c=random.randint(0,100)
6| d = random
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.
2| new_integer = 8
3| new_float = 8.2
4| new_date = date.today()
5 new_boolean = False
12 print(date_as_string, type(date_as_string))
13 print(boolean_as_string, type(boolean_as_string))
#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!
Ans
1 a=”5.1”
2| b = “Hello!”
3|c=”5”
7 print(as_integer, type(as_integer))
9 print(as_boolean, type(as_boolean))
#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
7| mystery_time_1 = time(12,45)
8 mystery_time_2 = time(12,45)
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
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
Ans
1 mystery value_1-6
2 mystery_value_2=2
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.
Ans
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.”
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.
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.
#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.
5) else:
6) print(“Not freezing”) #print if condition is not true
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.
#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
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.
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().
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.
#Note that the line below will let you access today's dateusingdate.today() anywhere in your
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
#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.
Ans
1 def hide_and_seek():
3 print(loopCounter)
Unit IV
Ans
1❘ def steps(value):
2 output=””
6| output += “\t”
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!?
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)
Ans
If the following lines are placed on line 7:
a) Print(aTuple[0])
Ans
Here are three possible ways to print each Georgia area code on its own line:
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]
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)
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'.
#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.
# Create a new Person instance with firstname “Ragul” and lastname “Dravid”
myNewPerson = Person(“Ragul”, “Dravid”)
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.
@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.
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]
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.