Introduction to Programming with Python & Java: Part 1

¡Supera tus tareas y exámenes ahora con Quizwiz!

Which of the following statements are true? Select all that apply. A. A variable is a symbolic name for (or reference to) a value. B. A variable can be used to store all kinds of stuff including user input. C. Variable names are case-sensitive D. You can assign a variable a value and then reassign the same variable a different value later on in your code.

All of the above

Which is the correct way to select some columns of data in DataFrame df? A. df["id", "name", "gender"] B. df[["id", "name", "gender"]] C. df("id", "name", "gender") D. df (["id", "name", "gender"])

B. df[["id", "name", "gender"]]

What is used to take input from the user in Python? A. get() B. input() C. scanf() D. <>

B. input()

Which of the following can be used to open a file "MOOC.csv" in append-mode only? A. my_file = open('MOOC.csv', 'w+') B. my_file = open('MOOC.csv', 'a') C. my_file = open('MOOC.csv', 'rw') D. my_file = open('MOOC.csv', 'r+')

B. my_file = open('MOOC.csv', 'a')

Which method do we use for joining two tables? A. pd.join() B. pd.merge(left=df, right=df_cities, how='inner', left_on='city_id', right_on='id') C. df.describe() D. df.head()

B. pd.merge(left=df, right=df_cities, how='inner', left_on='city_id', right_on='id')

Which of the following will return an error? A. print(round(15387-128) + int(412//23)) B. print('23 % 11 = ' + 23 % 11) C. print('Today\'s a good day') D. print(4>4)

B. print('23 % 11 = ' + 23 % 11)

Which method do we use to give an x-axis a label? A. xtitle() B. xlabel() C. xlegend()

B. xlabel()

Which one is correct if we want to get the average rating for action movies? A. df["rating"].mean() B. df[df["genre"] == "Action"]["rating"].sum() C. df[df["genre"] == "Action"]["rating"].mean()

C. df[df["genre"] == "Action"]["rating"].mean()

If you wanted to open a file "metrics.csv" in write mode using the following method, f = my_file.open('metrics.csv','w'), how would you then close the file? A. file.end() B. exit() C. f.close() D. metrics.close()

C. f.close()

Which one is correct if we want to create a pivot table for DataFrame df indexing on column "author" and "title", and display the summation of the "res" column? A. import pandas as pd, df_res = pd.pivot_table(df, index=["author", "title"], columns=["res"], aggfunc=[sum]) B. import pandas as pd, df_res = pd.pivot_table(df, index=["author", "title"], values=["res"], aggfunc=[pd.sum]) C. import pandas as pd, import numpy as np, df_res = pd.pivot_table(df, index=["author", "title"], values=["res"], aggfunc=[np.sum]) D. import pandas as pd, import numpy as np, df_res = pd.pivot_table(df, index1=["author"], index2=["title"], values=["res"], aggfunc=[np.mean])

C. import pandas as pd, import numpy as np, df_res = pd.pivot_table(df, index=["author", "title"], values=["res"], aggfunc=[np.sum])

What is the type of age: 1, age = input("How old are you?")? A. type B. int C. str D. float

C. str

What does the following code output: for num in range(1, -5, -1): print(num, end=", ")? A. 1, 0, -1, -2, -3, -4, -5 B. -5, -4, 3, 2, 1, 0 C. -4, -3, -2, -1, 0, 2, 3, 4, 5 D. 1, 0, -1, -2, -3, -4,

D. 1, 0, -1, -2, -3, -4,

Which of the following is a comparison operator? A. / B. and C. ** D. >

D. >

Which marks can be used to give comments? A. # B. """...""" C. '''...''' D. All of the above

D. All of the above

Which of the following statements about Docstrings is correct? A. A docstring describes the operation of the function (or class). B. To create a docstring, include a string as the first statement in function. C. The docstring is accessible by calling the function: help(func_name). D. All of the above

D. All of the above

Which of the following can be used to add a new key:value pair to a dictionary? A. dictionary[key] = value B. dictionary.update([(key, value)]) C. dictionary.update({key:value}) D. All the above

D. All the above

Which of the following can be used to get a value from a dictionary? A. variable = dictionary[key] B. variable = dictionary.get(key) C. variable = dictionary.get(key, value) D. All of the above

D. All the above

What will be the result of the following code: s = 'all', print(set(s))? A. {'a', 'l'} B. {'a', 'l', 'l'} C. {'l', 'a'} D. Both {'a', 'l'} and {'l', 'a'} are possible

D. Both {'a', 'l'} and {'l', 'a'} are possible

What does the following code output: l = ['foo', 'bar', 'baz'], while len(l) > 3: print(d.pop()), print('Done.')? A. The snippet does not generate any output. B. 'baz', 'bar', 'foo', Done. C. foo, bar, baz D. Done

D. Done

What is the result of the following code: course = {'1': 'CIT590', '2': 'CIT591', '3': 'CIT593'}, print(course['4'])? A. CIT590 B. CIT593 C. None D. KeyError

D. KeyError

What does the following code do: df[len(df) - 1 : ]? A. Returns rows from 0 to the last one B. Returns the first row C. Returns the last two rows D. Returns the last row

D. Returns the last row

What is the limit to the number of elif statements that can be implemented after an if statement? A. 5 B. 10 C. 100 D. There is no limit

D. There is no limit

Which of the following statements is false? A. When you open a file for writing, if the file does not exist, a new file is created. B. When you open a file for writing, if the file exists, the existing file is overwritten with the new file. C. When you open a file for reading, if the file does not exist, an error occurs. D. When you open a file for writing, if the file does not exist, an error occurs.

D. When you open a file for writing, if the file does not exist, an error occurs.

What will be the result of the following script: lst = [], for i in range(2): for j in range(1, 3): lst.append(i * j), print(lst) A. [0, 1, 2] B. [0, 1, 2, 3] C. [0, 0, 0, 1, 2, 3, 2, 4, 6] D. [0, 0, 1, 2]

D. [0, 0, 1, 2]

You want to find all the flights that departed from Philadelphia and arrived in Los Angeles, for a price that is less than $1200. You already have the following script: import csv, flights = [], with open('flights.csv', 'r') as csvfile: reader = csv.DictReader(csvfile), for row in reader: flights.append(row). Which of the scripts below is true for getting the information mentioned above? A. filtered_flights = [row in flights if row["Departure"] == Philadelphia and row["Destination"] == Los Angeles and row["Price"] < 1200)] B. filtered_flights = [row for row in flights if row["Departure"] == Philadelphia and row["Destination"] == Los Angeles and row["Price"] < 1200)] C. filtered_flights = [row in flights if row["Departure"] == 'Philadelphia' and row["Destination"] == 'Los Angeles' and int(row["Price"]) < 1200)] D. filtered_flights = [row for row in flights if row["Departure"] == 'Philadelphia' and row["Destination"] == 'Los Angeles' and int(row["Price"]) < 1200)]

D. filtered_flights = [row for row in flights if row["Departure"] == 'Philadelphia' and row["Destination"] == 'Los Angeles' and int(row["Price"]) < 1200)]

Which of the following is the correct syntax to check if the variable x is equal to 5? A. if (x != 5) B. if (x = 5) C. if (x <= 5) D. if (x == 5)

D. if (x == 5)

What data type could be used to store the phone number 123-456-7890? A. int B. float C. bool D. str

D. str

We have the following information about students: student_info = [{'first name':'Caroline', 'last name':'Harrison', 'birthdate':'1997-03-02'}, {'first name':'Rachel', 'last name':'Reynolds', 'birthdate':'1996-01-07'}, {'first name':'Olivia', 'last name':'James', 'birthdate':'1998-05-09'}] Which of the following code snippets is correct to get the information for the youngest student? A. youngest_student_info = max(key=lambda student_info: student_info['birthdate']) B. youngest_student_info = max(student_info.sort(student_info['birthdate'])) C. youngest_student_info = max(student_info['birthdate']) D. youngest_student_info = max(student_info, key=lambda x: x['birthdate'])

D. youngest_student_info = max(student_info, key=lambda x: x['birthdate'])

Which of the following are the common features of PyCharm? A. Code Assistance and analysis B. Code Completion C. Syntax and error highlighting D. Quick fixes E. All of the above

E. All of the above

What does the following code output: x = 5, y = "John", z = "UIO", print(x + x + z)? A. 10John B. 5 UIO C. TypeError D. 10UIO

C. TypeError

We have the following information about students: student_info = [{'first name':'Caroline', 'last name':'Harrison', 'birthdate':'1997-03-02'}, {'first name':'Rachel', 'last name':'Reynolds', 'birthdate':'1996-01-07'}, {'first name':'Olivia', 'last name':'James', 'birthdate':'1998-05-09'}] Which of the following code snippets is correct to sort the given student_info based on last name? A. student_info.sort() B. student_info.sort(student_info['last name']) C. student_info.sort(key=lambda x: x['last name']) D. None of the above

C. student_info.sort(key=lambda x: x['last name'])

What will list(d.keys()) return; d = {'A': 1, 'B': 2, 'C': 3}? A. [1,2,3] B. 'A', 'B', 'C' C. [A, B, C] D. ['A', 'B', 'C']

D. ['A', 'B', 'C']

Assume you have imported the package pyplot as plt and created a histogram in the program. Now you want to display the histogram. What is the code you will write to show the plot?

plt.show()

What is the result of the following code: s = df["some_attribute"] == "some_value", type(s)? A. Series B. DataFrame C. Boolean D. List

A. Series

Which of the following is used to represent a List in Python? A. [] B. {} C. () D. All of the above

A. []

What is the correct way to select the third element in a list called 'my_list'? A. my_list[2] B. my_list[3] C. my_list.get(2)

A. my_list[2]

Which of the following are data structures? Select all that apply. A. Lists B. Tuples C. Sets D. Loops

A, B and C

A statement using the or operator results in True if _______. Select all that apply. A. Both operands are true B. Both operands are false C. First operand is true D. Either of the operands is true

A, C, and D

What will be the result of the following code: a = [1, 2, 3, None, (), []], print(len(a))? A. 6 B. 3 C. 4 D. None

A. 6

A statement using the and operator results in True if _______. A. Both operands are true B. Both operands are false C. First operand is true D. Either of the operands is true

A. Both operands are true

When creating a pivot table, what would happen if we do not specify any aggregation function? A. By default, the pivot table calculates the average for every column in the result. B. By default, the pivot table calculates the summation for every column in the result. C. An error will occur. D. It will do nothing.

A. By default, the pivot table calculates the average for every column in the result.

What is the result of the following code: course = {'1': 'CIT590', '2': 'CIT591', '3': 'CIT593'}, print(course['1'])? A. CIT590 B. CIT591 C. None D. KeyError

A. CIT590

What will be the result of the following code: x = (1, 2, 3, 4), print(x[4])? A. Error B. 4 C. x D. None

A. Error

Which of the following is NOT a kind of server-side programming language? A. HTML B. Python C. Java D. PHP

A. HTML

What is used to define a block of code (body of loop, function, etc.) in Python? A. Indentation B. Parenthesis C. Quotation D. Curly braces

A. Indentation

What does IDLE stand for? A. Integrated Development and Learning Environment B. Integrated Development and Language Environment C. Integrated Development and Light Environment

A. Integrated Development and Learning Environment

What does IDE stand for? A. Integrated development environment B. Intermediate development environment C. Integrated drive environment

A. Integrated development environment

What does df.groupby(['genre']) do? A. It splits the data into different groups by 'genre'. B. It splits the data into different groups by default. C. It sorts the data based on 'genre'

A. It splits the data into different groups by 'genre'.

What does the following script print: for i in range(5): print(i)? A. Numbers from 0 - 4 B. Numbers from 1 - 5 C. Numbers from 0 - 5 D. Number 5 only

A. Numbers from 0 - 4

What does the following code do: f = open("test.txt", "r+")? A. Opens test.txt file for both reading and writing B. Opens test.txt file for reading only C. Opens test.txt file for writing only D. Opens test.txt file in god mode

A. Opens test.txt file for both reading and writing

What does the following code do if "df" is a DataFrame that stores the movie information: genre = df["genre"].isin(["Comedy", "Action"]), year = df["release_year"] == 2000, rating = df["rating"] > 4, df[genre & (year | rating)]? A. Select the comedy movies and action movies that are released in 2000 or have ratings above 4. B. Select the comedy movies and action movies that are released in 2000 and have ratings above 4. C. Select comedy movies and action movies that are not released in 2000 or have ratings equal to 4.

A. Select the comedy movies and action movies that are released in 2000 or have ratings above 4.

Which of the statements below is true for the following script: def calculate(str1, str2): calculated_number = 0, num1 = float(str1), num2 = float(str2), try: calculated_number = num1 / num2, except ValueError: print ('Error!'), return calculated_number, print(calculate('one', 'zero'))? A. The script will cause a ValueError because the code that tries to catch the error is incorrect. B. The script will print 'Error!' C. The script will print 'zero' D. The script will print '0.0'

A. The script will cause a ValueError because the code that tries to catch the error is incorrect.

We can pass a dict object as an argument to aggfunc. A. True B. False

A. True

What will be the result of the following code: myList = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], print(myList[6:8]) A. ['g', 'h'] B. ['g', 'h', 'a'] C. ['g'] D. Error

A. ['g', 'h']

What will be the result of the following code: lst = [1, 2, 3], lst.append(3), lst.pop() , print(lst)? A. [1, 2, 3] B. [1, 2, 3, 3] C. [2, 3, 3] D. Error

A. [1, 2, 3]

Which of the following is used to represent a list in Python? A. [] B. {} C. () D. All of above

A. []

How can you quickly examine the first 5 rows of a DataFrame? A. df.head() B. df.head(4) C. df.describe(5) D. df.drop_duplicates()

A. df.head()

Which of the following commands can be used to read all of the content in a file object f as a string? A. f.read() B. f.readline() C. f.readlines() D. f.read(n)

A. f.read()

Assume we want to add a legend in a histogram. Which parameter should we specify if we want to place the legend at the center of the figure? A. loc B. center C. xy

A. loc

Which of the following can be used to open a file "MOOC.csv" in read-mode only? A. my_file = open('MOOC.csv', 'r') B. my_file = open('MOOC.csv', 'r+') C. my_file = open(my_file = 'MOOC.csv', 'r') D. my_file = open(my_file = 'MOOC.csv', 'r+')

A. my_file = open('MOOC.csv', 'r')

What is the result of the following code: lst = [], with open("text.txt", "r") as f: lines = f.readlines(), for i in range(2): lst.append(lines[i].rstrip()), print(lst)? A. ['The world is hard and cruel.', 'We are here none knows why,'] B. ['The world is hard and cruel.\n', 'We are here none knows why,\n'] C. 'The world is hard and cruel. We are here none knows why,' D. 'The world is hard and cruel.\n We are here none knows why,'

A. ['The world is hard and cruel.', 'We are here none knows why,']

What is the output of the following code: print(3 >= 3)? A. 3>=3 B. True C. False D. None

B. True

What will be the result of the following code: my_list = ['cat', 'dog', 'fish'], print('cat' in my_list) A. 'cat' B. True C. 1 D. None

B. True

What will be the result of the following script: my_list = ['cat', 'dog', 'fish'], print('cat' in my_list)? A. cat B. True C. 1 D. 'cat' in my_list

B. True

What will be the result of the following script: my_list = [1, 2, 3, 4], my_list.append(5), my_list.pop(), my_list.pop(1), print(my_list)? A. [2, 4, 5] B. [1, 3, 4] C. [3, 4, 5] D. [2, 3, 4]

B. [1, 3, 4]

Which of the following can be used to open a file named "my_file.txt" in read mode and assign it to a variable named "f"? Select all that apply. A. f = open("my_file.txt") B. with open("my_file.txt", 'r') as f C. with open("my_file.txt", 'a') as f D. f = my_file.open('r')

A and B

What will be the result of the following script: string = 'pasta', result = '', for i in range(len(string) - 1, -1, -1): result += string[i], print(result) A. asp B. atsap C. psa D. An error message

B. atsap

Choose the correct function definition of calc() so that we can execute the following function call successfully: calc(25, 75, 55), calc(10.2, 20.3, 4), calc('output', 10.2, 20.3). A. def calc(a, b, c): print(a * b * c) B. def calc(a, b, c): print(a, b / c) C. No, it is not possible in Python D. def calc(a, b, c): print(a + b + c)

B. def calc(a, b, c): print(a, b / c)

Which of the following is a comment in Python? Select all that apply. A. //This is a single line comment B. #This is a single line comment C. """ This is a multi-line comment """ D. /* This is a multi line comment */

B and C

Which of the following can be used for exponentiation? A. // B. ** C. % D. *

B. **

How many rows will there be after calling df.drop_duplicates("AUTHOR", inplace = True)? A. 0 B. 1 C. 4 D. 5

B. 1

What will be the result of the following script: def add_two(x): x = x + 2, print(x), add_two(5)? A. 5 B. 7 C. 2 D. An error message

B. 7

What is the result of the following script: f = lambda x: x * 4, print(f(2))? A. 2222 B. 8 C. 16 D. Error

B. 8

What will be the result of the following script: def square(x): print(x ** 2), square(3)? A. 2 B. 9 C. 3 D. 6

B. 9

What is the result of the following code: course = {'1': 'CIT590', '2': 'CIT591', '3': 'CIT593'}, print(course.get('4', 'CIT594'))? A. CIT590 B. CIT594 C. None D. KeyError

B. CIT594

What will happen if you run the following code, f = open("test.txt", "a"), but "test.txt" does not exist? A. Creates "test.txt" and opens in read mode B. Creates "test.txt" and opens in append mode C. Does not create "test.txt" and no error message D. Error message

B. Creates "test.txt" and opens in append mode

What is the result of the following code: import pandas as pd, xls = pd.ExcelFile('yelp.xlsx'), df = xls.parse('yelp_data'), print(type(df))? A. .xlsx B. DataFrame C. Data D. .docs

B. DataFrame

We can pivot a DataFrame without an index column. A. True B. False

B. False

What will the following script print: x = 0, while x <= 5: if x == 4: break, print(x), x += 1 A. Numbers 0 - 4 B. Numbers 0 - 3 C. Numbers 1 - 4 D. Numbers 1 - 3

B. Numbers 0 - 3

What does the following code do: f = open("test.txt")? A. Opens test.txt file for both reading and writing B. Opens test.txt file for reading only C. Opens test.txt file for writing only D. Opens test.txt file in god mode

B. Opens test.txt file for reading only

What will be the result of the following code: for i in range(5): print(i)? A. Print numbers from 0 - 5 B. Print numbers from 0 - 4 C. Print numbers from 1 - 5 D. Print numbers from 2 - 5

B. Print numbers from 0 - 4

Which of the following is NOT a kind of client-side programming (computing) language? A. HTML B. Python C. CSS D. JavaScript

B. Python

Which of the following statements is NOT correct? A. Python is an open-source programming language B. Python needs to be compiled C. Python is an object-oriented programming (OOP) language D. Python is interpreted by a Python interpreter

B. Python needs to be compiled

Which of the following statements about the execution order of the script provided is true: def study(): print("Have fun coding!"), def work(): print("Have fun working!"), print("Do you know correct execution order?"), work(), study()? A. The functions study() and work() are executed in the order in which they occur, from top to bottom. I.e., study() comes first, then work(). B. The functions study() and work() are executed in the order in which they are called. I.e. work() comes first, then study().

B. The functions study() and work() are executed in the order in which they are called. I.e. work() comes first, then study().

When defining a variable, which of the following is allowed? A. The variable name can start with a digit. B. The variable name can start with an underscore. C. The variable name can contain a space. D. The variable name can have symbols like @, #, $, etc.

B. The variable name can start with an underscore.

What is the result of the following code: with open("text.txt", "w") as f_write: f_write.write("That is the wisdom of life.") , with open("text.txt", "r") as f_read: line = f_read.readline(), print(line)? A. 'The world is hard and cruel.' B. ['That is the wisdom of life.'] C. 'That is the wisdom of life.' D. ['We must be very humble.']

C. 'That is the wisdom of life.'

What will the following script print: x = 0, for x in range(5): if x == 3: continue, print(x) A. 0, 1, 2, 3, 4 B. 1, 2, 3, 4 C. 0, 1, 2, 4 D. 1, 2, 4, 5

C. 0, 1, 2, 4

What is the result of the following code: d = {}, d[1] = 1, d['1'] = 2, d[1] = 3, sum = 0, for i in d: sum += d[i], print(sum)? A. 2 B. 3 C. 5 D. 6

C. 5

Which operator is used to compare two numbers for equality? A. = B. += C. == D. !=

C. ==

Which of the following statements about functions are true? A. Functions are used to create objects in Python. B. Functions make your program run faster. C. A function is a piece of code that performs a specific task. D. All of the above

C. A function is a piece of code that performs a specific task.

What will be the result of the following script: x = [1, 2, 3, 4], print(x[4])? A. x B. 4 C. An error message D. None of the above

C. An error message

What is the output of the following function call: def fun1(num): return num + 25, fun1(5), print(num)? A. 25 B. 5 C. NameError D. 30

C. NameError

What is the result of the following code: course = {'1': 'CIT590', '2': 'CIT591', '3': 'CIT593'}, print(course.get('4'))? A. CIT590 B. CIT591 C. None D. KeyError

C. None

What does the following code output: num = 10, i = 9, if num % i == 1: print(num), break A. 10 B. 9 C. SyntaxError D. 1

C. SyntaxError

Which of the statements below is true for the following script: import csv, students = [], with open('MOOC.csv', 'r') as csvfile: reader = csv.DictReader(csvfile), for row in reader: students.append(row), filtered_students = [row for row in students if (int(row["age"]) < 30 and float(row["weight"]) < 190)], for student in filtered_students: print(student["name"], student["age"], student["weight"])? A. The script cannot be run as there is an error with the code that filters the data (filtered_students). B. The script cannot be run as there is an error with the code that iterates over the filtered data (filtered_students). C. The script can be run; the list of students who are younger than 30 and weigh less than 190 can be found. D. The script can be run; the name, age, and weight of the students who are at least 30 and weigh 190 can be found.

C. The script can be run; the list of students who are younger than 30 and weigh less than 190 can be found.

Which of the statements below is true for the following script: import csv, youngest_student = None, min_age = None, with open('MOOC.csv', 'r') as csvfile: reader = csv.DictReader(csvfile), for row in reader: age = int(row["age"]), if min_age == None or min_age > age: youngest_student = row["name"], min_age = age? A. The script cannot be run as there is an error with the usage of DictReader. B. The script cannot be run as there is an error with iterating over the reader. C. The script can be run; the youngest student and their age can be found. D. The script can be run; the oldest student and their age can be found.

C. The script can be run; the youngest student and their age can be found.

Which of the statements below is false for the following script: import csv, with open('MOOC.csv', 'r') as csvfile: reader = csv.DictReader(csvfile)? A. It can run without any error B. The type of 'reader' is DictReader C. You can iterate over 'reader' more than once D. 'MOOC.csv' is opened for reading only

C. You can iterate over 'reader' more than once

What will be the result of the following code: lst = [1, 2, 3], lst.append(3), lst.pop(0), print(lst)? A. [1, 2, 3] B. [1, 2, 3, 3] C. [2, 3, 3]

C. [2, 3, 3]

How would one delete the entry with key 'A'; d = {'A': 1, 'B': 2, 'C': 3}? A. d.delete('A': 1) B. d.delete('A') C. del d['A'] D. del d['A':1]

C. del d['A']

How can you get the type of data stored in each column of a DataFrame df? A. type(df) B. df.columns C. df.dtypes D. df.count()

C. df.dtypes


Conjuntos de estudio relacionados

SOCW 3306 Chapter 9: Social Insurance

View Set

CCNA 1121 Modules 1-3 Basic Network Connectivity and Communications

View Set

CHAPTER 13. Marketing: Helping Buyers Buy

View Set

Math 5.12 Classify and Measure Angles

View Set

1.2 structural organisation of the human body

View Set