Lab_06-AnswerSheet (1)
pdf
keyboard_arrow_up
School
Drexel University *
*We aren’t endorsed by this school
Course
171
Subject
Computer Science
Date
Dec 6, 2023
Type
Pages
13
Uploaded by ElderDiscovery12934
CS 171 - Lab 6
Professor Mark W. Boady and Professor Adelaida Medlock
Content by Professor Lisa Olivieri of Chestnut Hill College
Detailed instructions to the lab assignment are found in the following pages.
●
Complete all the exercises and type your answers in the space provided.
What to submit:
●
Lab sheet in PDF.
Submission must be done via Gradescope
●
Please make sure you have marked the questions on the correct pages of the PDF and added any
teammates to the submission
●
We only accept submissions via Gradescope.
Student Name: Shaun Mangan
User ID (abc123): sam677
Possible Points: 88
Your score out of 88
:
Lab Grade on 100% scale:
Graded By (TA Signature):
CS 171
Lab 6
Week 6
Question 1: 1 point
FYI: Predefined/built-in functions
: segments of code already included in Python.
print()
,
round()
,
abs()
,
pow()
,
int()
are examples.
Arguments
: The information that a function needs to work. Arguments are sent to the function between the
parentheses
()
.
To use a function, call the function.
input(
"
Enter your name
"
)
is a call to the
input
function sending
the string
"
Enter your name
"
as an argument.
Closely examine the Python program below.
#Get Input
name =
input
("Enter your name: ")
#Print Results
print
("Name:", name)
(a)
(1 point) Circle / highlight calls to predefined functions in the program above.
Question 2: 8 points
Enter and execute the following Python program.
(a) (1 point) What is printed by Line 2?
4.67
(b) (1point) What is printed by Line 3?
125
(c) (1 point) What is printed by Line 4?
7.0
(d) (1 point) What is printed by Line 5?
34
(e) (1 point) What is printed by Line 6?
7
(f) (1 point) What is printed by Line 9?
98
(g) (2 points) What is the difference between the
round
()
function and the
int
()
function?
2
1
#Sample functions
2
print
(
abs
(−4.67) )
3
print
(
pow
(5, 3) )
4
print
(
pow
(49, 0.5) )
5
print
(
int
(34.8) )
6
print
(
round
(6.9) )
7
8
import
random
9
print
(random.randint(1 ,100) )
CS 171
Lab 6
Week 6
The int function only prints the whole number, while the round function rounds the decimal to the
nearest whole number then prints it.
Question 3: 5 points
What value is returned by each of the following function calls?
(a) (1 point)
abs
(4.5)
4.5
(b) (1 point)
int
("678")
678
(c) (1 point)
round
(−5.6)
-6
(d) (1 point)
random.randint(4, 10)
5
(e) (1 point) Is
import
random
required to run
random.randint(4, 10)
?
Yes
No
Question 4: 1 point
Circle / highlight the
argument
in the call to the built-in function:
Question 5: 1 point
answer =
pow
(4, 3)
. What is/are the argument(s) in this code?
4 and 3
Question 6: 2 points
If a function contains more than one argument, do you think the order of the arguments makes a difference?
Explain your answer with an example.
The order does make a difference because if I use 2^3 it would be 8 but if I used 3^2 it would be 9.
Question 7: 6 points
Execute the following lines of code:
import
math
3
number = 45.78
answer =
round
(number)
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
CS 171
Lab 6
Week 6
x = 4.7
y = 5.3
z = −4.8
a = −3.2
print
(math.ceil(x))
print
(math.ceil(y))
print
(math.ceil(z))
print
(math.ceil(a))
print
(math.floor(x))
print
(math.floor(y))
print
(math.floor(z))
print
(math.floor(a))
(a) (2 points) Explain the purpose of the
ceil()
function
This rounds the number up to the nearest integer.
(b) (2 points) Explain the purpose of the
floor()
function.
This rounds the number down to the nearest integer.
(c) (2 points) Why are the calls to the
floor()
and
ceil()
functions preceded by “
math
.”?
Because they need the math function to be imported in order for the functions to run.
FYI:
A
function
is a segment of code that performs a single task.
A
function definition
is the segment of code that tells the program what to do when the function is
executed. The first line of a function definition is known as the
function header
Question 8: 6 points
Review the following Code.
#Description: This program uses a function to print a message
#Function Definition
def
printMessage ():
print
("Welcome to Python.")
print
("Learn the power of functions!")
#Function Definition
def
main() :
print
("Hello Programmer!")
#Function Call
printMessage ()
#Function Call
main()
(a) (1 point) What Python keyword is used to indicate that a code segment is a function definition?
def
4
CS 171
Lab 6
Week 6
(b) (1 point) What are the two function headers in the Python code?
def printMessage():, and def main():
(c) (1 point) The name of the function is in the function header. What are the names of the two functions?
printMessage and main
(d) (1 point) Enter and execute the Python program. What is the output?
Hello Programmer!
Welcome to Python.
Learn the power of functions!
(e) (2 points) What line of code would you add to the program to print the last two lines twice? Where
would you add the code?
I would add printMessage() under calling the main function.
Question 9: 14 points
Examine the following code.
#Description: This programuses functions to calculate
# the area of a circle, given the radius
import
math
def
calculateArea (radius): - function def
area = math.pi
∗
radius
∗∗
2
print
("A circle of Radius %d has area %.2f"
%(radius, area))
def
main() :
radius =
int
(
input
("Enter the radius: "))
calculateArea(radius) - function call
#### Call to main ####
main()
(a) (2 points) Label the
function definitions
and the
function calls
in the above code.
(b) (2 points) The function call and the function definition for
calculateArea
each include a variable
within the parentheses. The variable in the function call is known as an
argument
. The variable in the
function definition is called a
parameter
. What is the parameter in the function definition? What is its
purpose?
The parameter is the radius, its purpose is to take the radius that the person entered in, and calculate
the area with it.
5
CS 171
Lab 6
Week 6
(c) (2 points) In this example the parameter in the
function definition
and the argument in the
function call
have the same name. Is this required?
Yes because, if you put a different name when you call it, you will get an error message.
(d) (2 points) Enter and execute the program. Verify your answer to question (c) by changing the variable
name in the main function from
radius
to
number
. Do not change the parameter variable name in the
function definition. Does the program still work?
No, because the radius is still not defined.
(e) (2 points) Write a line of code that calls the
calculateArea
function and sends the value
6
as the
argument. Add the line of code to the main program and execute it to be sure it works properly.
calculateArea(6)
A circle of Radius 6 has area 113.10
(f)
(2 points) Add another function to the program that calculates and prints the
diameter
of a circle, given
the
radius
as the parameter. Place the function definition above call to the main function of the program.
Write the function below.
def calculateDiameter (radius):
diameter = 2 * radius
print("A circle of Radius %d has diameter %.2f" %(radius, diameter))
(g) (2 points) Add another line of code to the main function of the program to call the function that was
created in part (f). Send the radius entered by the user as the argument to the function.
def main() :
radius = int(input("Enter the radius: "))
calculateArea(radius)
calculateDiameter(radius)
Question 10: 5 points
Write a function that draws a frog. Call the function to be sure it works. Put your Python code for this
answer.
6
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
CS 171
Lab 6
Week 6
def drawFrog():
print(" @..@")
print("(----)")
print("(>--<)")
print("^^--^^")
drawFrog()
print()
Question 11: 5 points
Add a
for
loop to call the function multiple times and print the following. Put your Python code for this
answer.
Frog 1
Frog 2
Frog 3
Frog 4
7
CS 171
Lab 6
Week 6
def drawFrog():
print(" @..@")
print("(----)")
print("(>--<)")
print("^^--^^")
for i in range(4):
drawFrog()
print()
FYI:
So far, the functions you have created print the results within the function. They do not send back any
information to the original calling code. Functions that do not send back information are known as
void
functions
. Functions often send back or return a result and are known as
value returning functions
.
Question 12: 10 points
Review the following code.
# This program prompts the user for two numbers,
# calls a function to determine the smaller number
# and prints the smaller number that is returned from the function
def
getSmaller (num1, num2):
if
num1 < num2:
smaller = num1
else
:
smaller = num2
return
smaller
def
main() :
userInput1 =
int
(
input
("Enter a number: ") )
userInput2 =
int
(
input
("Enter a second number: ") )
smallerNumber = getSmaller ( userInput1, userInput2 )
print
("The smaller of the two numbers is", smallerNumber)
##Call Main
main()
(a) (2 points) What is the new
keyword
used in the function definition?
return
(b) (2 points) What do you think the keyword tells the program to do?
returns the smaller variable, pretty much telling the function what to print out.
8
CS 171
Lab 6
Week 6
(c) (2 points) Circle/highlight the line of code from the program with the
function call
to
getSmaller
.
(d) (2 points) In a
void function
, the
function call
is on a line by itself. Why is this
function call
placed on
the right-hand-side of an
assignment statement
?
It has to be on the right side of the function in order for it to get accepted.
(e) (2 points) What are the arguments used for the function call?
userInput1, and userInput2
Question 13: 8 points
Examine the following code.
import
math
def
getQuadratic (a, b):
square = a
∗∗
2 + b
∗∗
2
squareRoot = math.sqrt ( square )
return
squareRoot
def
main() :
print
(“The
square
root
of
the
sum
of
the
squares
of
3
and
4
is:”,
getQuadratic(3,
4))
##Call Main
main()
(a) (2 points) What does the program do?
Gets the square root of the sum of the squares 3 and 4.
(b) (2 points) Circle/highlight the function call.
(c) (2 points) Is the function a void function or a value returning function?
value returning function
(d) (2 points) Why is the
import
statement needed in this program?
To import the math function, so the square root can be calculated.
9
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
CS 171
Lab 6
Week 6
Question 14: 6 points
Develop and test the following code in Python.
Carefully examine and then complete the following Python program.
• The program prompts the user to enter a number between 1 and 5
• It also generates a random number between 1 and 5.
• The program prints the number the user enters and prints the random number.
• The program then compares the two numbers.
–
If the numbers are the same, it prints the message “You picked the same number as the
computer!”.
–
If the number the user entered is higher than the random number, the program should print “Your
number is higher than the computer’s number.”
–
Otherwise, it should print: “Your number is smaller than the computer’s number”.
Complete the code for the
getMessage()
function so that it returns the appropriate message,
depending on the values stored in the two parameters. See Sample Output for the correct messages to
be returned.
import
random
def
getMessage (userNum, randNum):
#Rewrite this function
return
""
def
main() :
userNum =
int
(
input
("Enter a number between 1 and 5: ") )
while
userNum > 5
or
userNum < 1:
userNum =
int
(
input
("Invalid number. Enter a number between 1 and 5: ") )
randNum = random.randint (1, 5)
print
("Computer number:", randNum)
print
("User number:", userNum)
print
( getMessage (userNum, randNum) )
##Call Main
main()
Rewrite the
getMessage
function so that it prints the below responses.
• You picked the same number as the computer!
• Your number is smaller than the computer’s number.
• Your number is higher than the computer’s number.
Write your new function definition below.
def getMessage (userNum, randNum):
#Rewrite this function
if(userNum==randNum):
return("You picked the same number as the computer!")
if(userNum>randNum):
return("Your number is higher than the computer's number.")
if(userNum<randNum):
10
CS 171
Lab 6
Week 6
return("Your number is lower than the computer's number.")
Question 15: 10 points
Complete the following program.
The program should:
• Display five addition facts, one at a time, and allow the user to answer them.
• Provide the correct answer if user enters incorrect answer.
• Print a congratulatory answer, if the answer is correct.
• Keep track of the number of problems the user answers correctly.
• Prints a special message, if the user gets all five problems correct.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Include the required import statement
# Fill-in 1
def
printRocket ():
# Include a FOR loop that prints the numbers from 10 to 0
# Fill-in 2
# Fill-in 3
print
("Blast-off!!")
print
(" *")
print
("***")
print
("*****")
print
("*****")
print
("*****")
print
("*****")
def
main ():
numCorrect = 0
for
x
in range
(5):
# Assign a random number between 1 and 10
# to num1 and num2
num1 = #Fill-in 4
num2 =
#Fill-in 5
answer =
int
(
input
(
str
(num1) + "+" +
str
(num2)+ "=" ) )
# Write the test condition to determine if the user’s
# answer is equal to the sum of the two numbers
if
# Fill-in 6
print
("Congratulations! Your answer is correct!\n")
# Write the line of code to increment the variable
# that keeps track of the number of correct answers
# Fill-in 7
else
:
print
("Sorry, your answer is incorrect.", end = " ")
11
CS 171
Lab 6
Week 6
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# Print the correct answer
# Fill-in 8
print
()
# Write the test condition to determine if the user answers
# all the questions correctly
if
# Fill-in 9
print
("\nGreat Job! You answered the problems correctly!")
# Write the code call the function that prints the rocket
# Fill-in 10
else:
print
("You answered:", numCorrect, "questions correctly.")
print
("Type again for a perfect score!")
### Call Main
main()
(a) (1 point) What should go on Line 2
import random
(b) (1 point) What should go on Line 6
for x in range(10, 1, -1):
(c) (1 point) What should go on Line 7
print(x)
(d) (1 point) What should go on Line 21
random.randint(1,10)
(e) (1 point) What should go on Line 22
random.randint(1,10)
(f)
(1 point) What should go on Line 27
if answer == (num1 + num2):
(g) (1 point) What should go on Line 31
numCorrect +=1
(h) (1 point) What should go on Line 35
print(“correct answer”, str(num1 + num2))
(i) (1 point) What should go on Line 40
12
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
CS 171
Lab 6
Week 6
numCorrect ==25:
(j) (1 point) What should go on Line 43
printRocket()
13
Recommended textbooks for you
COMPREHENSIVE MICROSOFT OFFICE 365 EXCE
Computer Science
ISBN:9780357392676
Author:FREUND, Steven
Publisher:CENGAGE L
Np Ms Office 365/Excel 2016 I Ntermed
Computer Science
ISBN:9781337508841
Author:Carey
Publisher:Cengage

New Perspectives on HTML5, CSS3, and JavaScript
Computer Science
ISBN:9781305503922
Author:Patrick M. Carey
Publisher:Cengage Learning
Recommended textbooks for you
- COMPREHENSIVE MICROSOFT OFFICE 365 EXCEComputer ScienceISBN:9780357392676Author:FREUND, StevenPublisher:CENGAGE LNp Ms Office 365/Excel 2016 I NtermedComputer ScienceISBN:9781337508841Author:CareyPublisher:CengageNew Perspectives on HTML5, CSS3, and JavaScriptComputer ScienceISBN:9781305503922Author:Patrick M. CareyPublisher:Cengage Learning
COMPREHENSIVE MICROSOFT OFFICE 365 EXCE
Computer Science
ISBN:9780357392676
Author:FREUND, Steven
Publisher:CENGAGE L
Np Ms Office 365/Excel 2016 I Ntermed
Computer Science
ISBN:9781337508841
Author:Carey
Publisher:Cengage

New Perspectives on HTML5, CSS3, and JavaScript
Computer Science
ISBN:9781305503922
Author:Patrick M. Carey
Publisher:Cengage Learning