CMPSC8 practice quizzes!
.pdf
keyboard_arrow_up
School
University of California, Santa Barbara *
*We aren’t endorsed by this school
Course
8
Subject
Computer Science
Date
Dec 6, 2023
Type
Pages
43
Uploaded by JudgeDinosaur3878
What is the correct syntax to make a global variable (ex_global_var) available inside a function
definition?
a.
global ex_global_var
b.
ex_global_var
c.
global(ex_global_var) X
d.
public ex_global_var
How should the following code be modified to also multiply by c the value provided by: return a
+ b
a.
a + b * c
b.
return (a + b) * c
c.
(return a + b) * c X
d.
return a + b * c
What is returned by the following?
result = '5' * 3
print (result)
a.
error X
b.
15
c.
535353
d.
555
What is the output of the following code?
def math(x,y):
z = x + y
return z
math(3,5)
print(z)
a.
5
b.
8 X
c.
3
d.
error
What is the output of the following code?
def print_red():
print("red", end = ", ")
def print_orange():
print("orange")
def print_yellow():
print("yellow", end = ", ")
print_orange()
def print_green():
print_red()
print("green", end = ", ")
print_yellow()
print_green()
a.
red, green, yellow, orange
b.
red, green, yellow
c.
red, green
d.
Red, green, orange, yellow
Practice Short Answer Quiz:
Given a variable age, write the code that correctly outputs the following. If the age is less zero or
greater than 150 output "invalid age", if the age is less than four or greater than eighty output
"free", if the age is between four and twelve (inclusive) output "child discount", otherwise output
"regular pricing".
if age < 0 or age > 150:
print(“invalid age”)
elif age < 4 or age > 80:
print(“free”)
elif 4 <= age <= 12:
print(“child discount”)
else:
print(“regular pricing”)
Given this grading scheme (80-100] A , (60-80] B, [0-60] C, and less than 0 and greater than 100
is invalid. Given the variable numerical_grade, output the corresponding letter grade. (Note:
(80-100] means 100 is an A but 80 is a B so ( means exclusive and ] means inclusive. Ex: if
numerical_grade is 80 the output should be B if the numerical_grade is -1 the output should be
invalid)
def letter_grade(grade):
“““ this function takes a numerical grade as an input and outputs the letter grade ”””
if 0 <= grade <= 60:
letter = ‘C’
elif 60 < grade <= 80:
letter = ‘B’
elif 80 < grade <= 100:
letter = ‘A’
else:
letter = ‘invalid’
return letter
Define a function called triangle_area with parameters base and height that returns the area of a
triangle.
Relevant geometry equations:
area = 1/2 x base x height
def triange_area(base, height(:
area = ½ * base * height
Return area
Define a function add_three_to_me that takes in an integer as a parameter. The function first
checks if the type of the parameter is an integer and if it is not it prints "incorrect type",
otherwise it returns 3 plus the value of the input.
Define three functions hours_to_seconds, hours_to_minutes, and minutes_to_seconds with
appropriate parameters. hours_to_minutes will convert hours to minutes, minutes_to_seconds
will convert minutes to seconds, and hours_to_seconds will just call the other two functions.
def hours_to_minutes(hours):
“ “ “ This function takes hours as input and outputs minutes ” ” ”
minutes = hours * 60
return minutes
def minutes_to_seconds(minutes):
“ “ “ This function takes minutes as input and outputs seconds ” ” ”
seconds = minutes * 60
return seconds
def hours_to_seconds(hours):
“ “ “ This function takes hours as input and outputs seconds ” ” ”
se
What code replaces XXX to make the program output the number 10?
multiplier = 1
def do_multiplication(x):
return x * multiplier
def set_multiplier(x):
XXX
multiplier = x
user_value = 5
set_multiplier(2)
print(do_multiplication(user_value))
a.
set_multiplier(2)
b.
global multiplier
c.
do_multiplication(x)
d.
global x
What is the output?
def print_message1():
print('Message #1')
def print_message2():
print('Message #2')
print_message1 = print_message2
print_message2 = print_message1
print_message1()
print_message2()
a.
Message #1
Message #2
b.
Message #1
Message #1
c.
Message #2
Message #1
d.
Message #2
Message #2
Which of the following is true?
a.
A function can have any number of return statements, or no return statement at all.
b.
A function must have exactly one return statement, or no return statement at all.
c.
A function can only return strings and numbers, not lists or dictionaries.
d.
A function must always have at least one return statement.
Which of the following types of constructs should be called when the programmer wants to stop
program execution?
a.
Print a "FIXME" message and return -1
b.
return None
c.
Use a pass statement
d
.
Raise NotImplementedError
What is the result when the program is executed?
def add(x, y):
return x + y
print('Begin test')
s = add('hello', 5)
print(s)
print('End test')
●
2/7 :
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
Related Questions
please code in python
A local variable in a function is either a parameter or a variable which appears on the left hand side (LHS) of an assignment statement in the function. A variable in a function is global if it is not local, but if you want to assign something to a global variable, g, in a function, then you will need the statement global g. Without the global g statement, assignment, like, g = 5, would make g local. You shouldn't use global variables very often when writing functions, since global variables reduce readability. Occasionally they are useful, such as when you would like to count how often a function is called. Define a global variable, countcalls, and increment it inside the power(x, n) function that you wrote for Q4, so that it counts the number of times the power function is called. Show that it produces the expected number of calls for power(2, 10) and power(5, 10) and power(5, 0), each separately
arrow_forward
If a parameter in a function header is preceded by
of arguments could be sent in the call and they wil
[Select]
However, if the s
an assignment operator
a single star
, then any number of arguments could be sent in the call along with
[Select]
[Select]
[Select]
two stars
their values and they will be treated inside the function as a [Select]
, then any number
as a
arrow_forward
True or False
1-int fx(char x) is a function with int return
value
2-int fx(char &x) is a function with parameter
passed by value
3-void fx(char ch) is a function with no return
value
4-char fx( int x) is a function with int return
value
arrow_forward
c++ computer language
given the function header: void sum(int x=2, float y=3, int z =100) then which of the following is a valid function call? (choose all possible)
a.sum(9);
b.sum(a,b,5);
c.sum(a,b);
d.sum();
arrow_forward
To accomplish pass-by-reference when passing a nonarray variable to a function, it’snecessary to pass the__________________ of the variable to the function.
arrow_forward
complete the function definition withouth local variables so that the function will convert any fuel effeciency measured in mpg to the equivalent metric fuel consumption. thank you!
arrow_forward
1-int fx(char &x) is a function with parameter passed by value(False/True)
2-int fx(char x) is a function with int return value(False/True)
3-void fx(char ch) is a function with no return value(False/True)
4-char fx( int x) is a function with int return value(False/True)
arrow_forward
1-int fx(char &x) is a function with parameter passed by value(False/True)
2-int fx(char x) is a function with int return value(False/True)
3-void fx(char ch) is a function with no return value(False/True)
4-char fx( int x) is a function with int return value(False/True)
arrow_forward
coding in c
arrow_forward
Write a function called area_circumference_generator that takes a radius of a circle as a function parameter and calculates its circumference and area. Then
returns these two results as a tuple and prints the results using tuple unpacking in the function call accorrding to the given format. [Must use tuple packing &
unpacking]
!!
Example1:
Function Call:
area_circumference_generator(1)
Output:
(3.141592653589793, 6.283185307179586)
Area of the circle is 3.141592653589793 and circumference is 6.283185307179586
arrow_forward
Define a function named change_values that takes four integers as parameters and swaps or changes them based on a set of rules. Your Change Function should follow the following rules in the following order:
1. If the second value is an odd number, then it should be swapped with the first number.
2. If the third value is a power of two, then it should be swapped with the fourth value.
3. If the summation of the current values 1 to 3rd (after the above two rules are applied) is equal to the fourth value, then the fourth value should be set to the first value.
Then write a Main program that reads four integers from standard input, calls function change_values() to swap the values, and prints the swapped values on a single line separated with spaces.
Example Input:
1
3
4
0
Example Output:
3 1 0 3
arrow_forward
help@ritaj.ps : E-mail Call us : +97 (0/2)-2-2982000
COMI UTEK ANDTRO OKAMUVIIINGFLECTOTE-1
MidTerm Exam / 7 / COMPUTER AND PROGRAMMING-Lecture-1201 -1/ ,
If the following statement is a correct call to the function SUM, then SUM must be a void function. int num =
SUM(x, y)
Select one
a. Syntax error O
b. We cannot know if it's void or not void function O
c. True O
d. False O
arrow_forward
17.
A function should determine the average of x and y.
What should be the function's parameters and return value(s)?
A.Parameters: none
Return values: X,y
B.Parameters: ×, y, average
Return value: none
C.Parameters: average
Return values; X, y
D.Parameters: X, y
Return value: average
arrow_forward
In C++ please
arrow_forward
Write a function which calculates the number of tweets that were posted per day.
Function Specifications:
It should take a pandas dataframe as input.
It should return a new dataframe, grouped by day, with the number of tweets for that day.
The index of the new dataframe should be named Date, and the column of the new dataframe should be 'Tweets', corresponding to the date and number of tweets, respectively.
The date should be formated as yyyy-mm-dd, and should be a datetime object. Hint: look up pd.to_datetime to see how to do this.
arrow_forward
in C++ program please:
According to Wikipedia: “The International Collegiate Programming Contest, known as the ICPC, is an annual multi-tiered competitive programming competition among the universities of the world.” Moreover, the participants of the contest should be no older than 24.
Complete the following function which takes as input two parameters: the current year and the birth year of a student. The function should return the age of the person given the parameters.
int calculateAge(int current_year, int birth_year) {
arrow_forward
Redesign this solution using functions. For this lab:
You will define a function names main().
You will get input in the main function and pass it to the following functions:
milesToKm()
FahToCel()
GalToLit()
PoundsToKg()
InchesToCm().
Each function will require that you have a local variable to store the result of the calculation. This result will then be displayed using the print statement from within the function.
For this portion of the lab, you will reuse the program you wrote in Lab 5 Part1 A. Redesign this solution in the following manner:
All of the functions used must now be value returning functions.
Put the functions in an external module and let the main program import the module.
arrow_forward
In C++ programming lanuage:
Normally a function does not have access to a variable defined in another function. However, by using a ________________variable as a parameter, a function may change a variable that is defined in another function.
arrow_forward
Ibra Bakery wants you to create a simple python program for calculating cashback offers on cakes for the customers on the occasion of their second anniversary. The program should start by reading customer_name, Number_of_cakes. Then you need to do the following
Create a void function and a parameter that will display “Welcome to Ibra bakery <customer name>”.
example: Welcome to Ibra bakery Mohammed
Create a function with return value and with a parameter Number_of_cakes. then input cake_price of each cake. Then calculate Total_price as sum of all the cakes’ prices.
Create a function that will accept Total_price as parameter then compute cashback based on a criterion that if Total_price is more than 10.0 omr, cashback will be 20% of Total_price otherwise no cashback.
Display all the details as output.
User-defined function(python)
arrow_forward
Ibra Bakery wants you to create a simple python program for calculating cashback offers on cakes for the customers on the occasion of their second anniversary. The program should start by reading customer_name, Number_of_cakes. Then you need to do the following
Create a void function and a parameter that will display “Welcome to Ibra bakery <customer name>”.
example: Welcome to Ibra bakery Mohammed
Create a function with return value and with a parameter Number_of_cakes. then input cake_price of each cake. Then calculate Total_price as sum of all the cakes’ prices.
Create a function that will accept Total_price as parameter then compute cashback based on a criterion that if Total_price is more than 10.0 omr, cashback will be 20% of Total_price otherwise no cashback.
Display all the details as output.
User-defined function (python)
arrow_forward
please code in python.
Each problem will be placed in its own function. You will have a main function that calls the function for each problem. For these problems, you will need to use the following string functions: lower, upper, isupper, islower, isdigit, and replace, along with using [ ] to access individual characters. You may use other string functions if you find them useful.
You will write a function named computeGCPercentage that accepts a string (representing a piece of DNA) as an input and returns a float representing the Guanine-Cytosine (GC) content percentage.
For example, assume that the DNA string GTAACTAGCTTACGTAAC is entered. Because there are a total of 7 characters that are either G or C, and there are 18 characters altogether, the function should return a floating point value equivalent to 7/18 .
Requirements Your function:1. Must check to see that there are no other characters in the string other than those specified. If there is, it should print an error message…
arrow_forward
Which of the following are benefits of specifying a function's parameters' data type(s)? Choose
all that apply.
it constructs data of the correct type in the parameter
O it conveys the valid types of argument expressions required in a call to the function
O it conveys valid operations on parameters within the function's body
O it ensures a default value for the parameter when an argument is missing
it makes it possible to identify invalid function calls without running the program
there are no benefits in specifying a function's parameters' data types
arrow_forward
Write a function days_in_month() that returns the number of days in a month. The
function has the following prototype:
int days_in_month(int month, int is_leap);
Month should be an integer value between 1 and 12. The function should return (-1) if
an invalid month is input. The variable ‘is_leap’ is 1 for leap years, 0 otherwise.
arrow_forward
In C Language and not C++ PLEASE
C Language not C++
arrow_forward
SEE MORE QUESTIONS
Recommended textbooks for you
C++ for Engineers and Scientists
Computer Science
ISBN:9781133187844
Author:Bronson, Gary J.
Publisher:Course Technology Ptr
C++ Programming: From Problem Analysis to Program...
Computer Science
ISBN:9781337102087
Author:D. S. Malik
Publisher:Cengage Learning
Related Questions
- please code in python A local variable in a function is either a parameter or a variable which appears on the left hand side (LHS) of an assignment statement in the function. A variable in a function is global if it is not local, but if you want to assign something to a global variable, g, in a function, then you will need the statement global g. Without the global g statement, assignment, like, g = 5, would make g local. You shouldn't use global variables very often when writing functions, since global variables reduce readability. Occasionally they are useful, such as when you would like to count how often a function is called. Define a global variable, countcalls, and increment it inside the power(x, n) function that you wrote for Q4, so that it counts the number of times the power function is called. Show that it produces the expected number of calls for power(2, 10) and power(5, 10) and power(5, 0), each separatelyarrow_forwardIf a parameter in a function header is preceded by of arguments could be sent in the call and they wil [Select] However, if the s an assignment operator a single star , then any number of arguments could be sent in the call along with [Select] [Select] [Select] two stars their values and they will be treated inside the function as a [Select] , then any number as aarrow_forwardTrue or False 1-int fx(char x) is a function with int return value 2-int fx(char &x) is a function with parameter passed by value 3-void fx(char ch) is a function with no return value 4-char fx( int x) is a function with int return valuearrow_forward
- c++ computer language given the function header: void sum(int x=2, float y=3, int z =100) then which of the following is a valid function call? (choose all possible) a.sum(9); b.sum(a,b,5); c.sum(a,b); d.sum();arrow_forwardTo accomplish pass-by-reference when passing a nonarray variable to a function, it’snecessary to pass the__________________ of the variable to the function.arrow_forwardcomplete the function definition withouth local variables so that the function will convert any fuel effeciency measured in mpg to the equivalent metric fuel consumption. thank you!arrow_forward
- 1-int fx(char &x) is a function with parameter passed by value(False/True) 2-int fx(char x) is a function with int return value(False/True) 3-void fx(char ch) is a function with no return value(False/True) 4-char fx( int x) is a function with int return value(False/True)arrow_forward1-int fx(char &x) is a function with parameter passed by value(False/True) 2-int fx(char x) is a function with int return value(False/True) 3-void fx(char ch) is a function with no return value(False/True) 4-char fx( int x) is a function with int return value(False/True)arrow_forwardcoding in carrow_forward
- Write a function called area_circumference_generator that takes a radius of a circle as a function parameter and calculates its circumference and area. Then returns these two results as a tuple and prints the results using tuple unpacking in the function call accorrding to the given format. [Must use tuple packing & unpacking] !! Example1: Function Call: area_circumference_generator(1) Output: (3.141592653589793, 6.283185307179586) Area of the circle is 3.141592653589793 and circumference is 6.283185307179586arrow_forwardDefine a function named change_values that takes four integers as parameters and swaps or changes them based on a set of rules. Your Change Function should follow the following rules in the following order: 1. If the second value is an odd number, then it should be swapped with the first number. 2. If the third value is a power of two, then it should be swapped with the fourth value. 3. If the summation of the current values 1 to 3rd (after the above two rules are applied) is equal to the fourth value, then the fourth value should be set to the first value. Then write a Main program that reads four integers from standard input, calls function change_values() to swap the values, and prints the swapped values on a single line separated with spaces. Example Input: 1 3 4 0 Example Output: 3 1 0 3arrow_forwardhelp@ritaj.ps : E-mail Call us : +97 (0/2)-2-2982000 COMI UTEK ANDTRO OKAMUVIIINGFLECTOTE-1 MidTerm Exam / 7 / COMPUTER AND PROGRAMMING-Lecture-1201 -1/ , If the following statement is a correct call to the function SUM, then SUM must be a void function. int num = SUM(x, y) Select one a. Syntax error O b. We cannot know if it's void or not void function O c. True O d. False Oarrow_forward
arrow_back_ios
SEE MORE QUESTIONS
arrow_forward_ios
Recommended textbooks for you
- C++ for Engineers and ScientistsComputer ScienceISBN:9781133187844Author:Bronson, Gary J.Publisher:Course Technology PtrC++ Programming: From Problem Analysis to Program...Computer ScienceISBN:9781337102087Author:D. S. MalikPublisher:Cengage Learning
C++ for Engineers and Scientists
Computer Science
ISBN:9781133187844
Author:Bronson, Gary J.
Publisher:Course Technology Ptr
C++ Programming: From Problem Analysis to Program...
Computer Science
ISBN:9781337102087
Author:D. S. Malik
Publisher:Cengage Learning