Introduction To Python Midterm Exam Review: Practice questions

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Which of the following is (are) a Python Logical Operator? _____. A.) or B.) All of the above C.) and D.) not

B.) All of the above

What is the output of the following code block? class sample: x = 23 def increment(self): self.__class__.x = self.__class__.x + 1 a = sample() b = sample()b.increment() print(a.__class__.x)

24

Read the following code snippet which is designed to count the frequency of the names in the name list: Name_list = ['csev', 'cwen', 'csev', 'zqian', 'cwen'] counts = dict() for name in Name_list : counts[name] = counts.get(name, ____) + 1 print counts Select the best answer to complete the blank in the code snippet. A.) 0 B.) -1 C.) " D.) 1

A.) 0

What is the output of the following Python statement? >>> len("X\nY") A.) 3 B.) 2 C.) 5 D.) 4

A.) 3 ****"X\nY" is a string containing two characters: "X" and "\n" (which represents a newline character), followed by "Y". When we call len() on this string, it counts the number of characters in the string. The newline character "\n" is treated as a single character, even though it's represented by two characters in the source code. Therefore, the length of the string "X\nY" is 3. The output of len("X\nY") is indeed 3, which matches option 3.

Compare the following two strings in Python: 'aa' _______ 'aaz' A.) < B.) > C.) =

A.) < ***Certainly! Here's a brief explanation: When comparing strings in Python using the comparison operators, Python compares the strings based on their lexicographical order, which is essentially their alphabetical order. The symbol '<' indicates "less than", and it means that the first string comes before the second string in the lexicographical order. In this case, 'aa' comes before 'aaz' in the alphabetical order, so the correct symbol to complete the comparison is '<'. Therefore, the correct answer is option A: '<'.

Compare the following two strings in Python: 'a' _______ '0' A.) > B.) = C.) <

A.) >

Which of the following statements are correct about tuples and lists? A.) All of them B.) Lists slower but more powerful than tuples. Lists can be modified and they have many handy operations and methods C.) Tuples are immutable and have fewer features. D.) We can convert tuples and lists using list() and tuple()

A.) All of them

Regarding "break" and "continue" in Python, which of the following statements is wrong? _____. A.) If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the outermost loop. B.) The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration. C.) In Python, break and continue statements can alter the flow of a normal loop. D.) The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop.

A.) If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the outermost loop.

Regarding classes, objects, and instances in Python, which of the following is wrong? A.) None of them B.) Instances are objects that are created which follow the definition given inside of the class. Objects belong to classes. Classes reflect concepts, objects reflect instances that embody those concepts. C.) The core tasks for object oriented programming are to build different classes and thus construct different objects based on the classes to achieve aims. D.) Everything in Python is really an object

A.) None of them

Regarding methods in classes, which of the following statements is wrong? A.) None of them B.) There's no "destructor" method for classes in Python C.) We define a method in a class by including function definitions within the scope of the class block D.) There must be a special first argument self in all of method definitions which gets bound to the calling instance

A.) None of them

Which of the following statements about "self" and data attributes in Python classes is wrong? A.) None of them B.) The first argument of every method is a reference to the current instance of the class C.) In __init__, self refers to the object currently being created; so, in other class methods, it refers to the instance whose method was called D.) Although you must specify self explicitly when defining the method, you don't include it when calling the method.

A.) None of them

The output of the following codes is _______________. x = "awesome"def myfunc(): global xx = "fantastic"myfunc()print("Python is " + x) A.) Python is fantastic B.) Python is C.) Python is awesome D.) Non of them

A.) Python is fantastic ***The code provided defines a global variable x with the value "awesome". Then, it defines a function myfunc that tries to create a global variable xx with the value "fantastic". However, there is a syntax error in this line: global xx = "fantastic". The global keyword should be followed by just the variable name, not an assignment. Due to this error, the code will raise a syntax error and won't execute successfully. Therefore, none of the provided options match the output. The correct answer should be python is fantastic

Is the following statement true or false? "From a function's perspective, a parameter is the variable listed inside the parentheses in the function definition, and an argument is the value that is sent to the function when it is called." A.) True B.) False

A.) True

Is the following statement true or false? Using for loop, each execution of the loop will read a line from the file into a string. A.) True B.) False

A.) True

Length_Of_Rope and length_of_rope are two different variables in Python. This statement is _____. A.) True B.) False

A.) True

^ Matches beginning of a line and beginning of string. What is the output of the following codes? import re ms= '''Tom 90\nMike 80\nHuang 96''' name= re.findall("^\w+",ms, re.MULTILINE) print(name) A.) ['Tom','Mike','Huang'] B.) ['Tom 90\nMike 80\nHuang 96'] C.) [] D.) ['Tom']

A.) ['Tom','Mike','Huang'] ***^\w+: This pattern matches a sequence of one or more word characters (letters, digits, or underscores) at the beginning of a line. re.MULTILINE: This flag allows the "^" metacharacter to match the beginning of each line in a multi-line string rather than just the beginning of the entire string. In the given multi-line string ms, the pattern "^" matches the beginning of each line, and "\w+" matches the first word on each line. Therefore, the output of re.findall("^\w+", ms, re.MULTILINE) will be ['Tom', 'Mike', 'Huang'], as it correctly identifies the first word on each line in the string ms. Option A, ['Tom', 'Mike', 'Huang'], is the correct answer.

"\w" matches any alphanumeric character; "\W" any non-alphanumeric character. "\b" matches a word boundary; "\B" matches a character that is not a word boundary. What is the output of the following code? s= "He is the man's father and he is also a teacher! " word=re.findall("\\bhe\\b",s) print(word) A.) ['he'] B.) ['\\bhe\\b'] C.) ['he', 'he', 'he', 'he'] D.) ['he', 'he']

A.) ['he'] *****\bhe\b: This pattern matches the word "he" surrounded by word boundaries. In the given string s, the word "he" is found as a standalone word, not as part of another word like "the" or "teacher". Therefore, the output of re.findall("\\bhe\\b", s) will be ['he'], as it correctly identifies the standalone occurrence of the word "he" in the string s. Option A, ['he'], is the correct answer.

Note: '\d' matches any digit; '\D' matches any non-digit. A student's username is composed of his/her first name, last name, a dash and order number, please fill in blanks to extract them. username="Knappen_Michell_01" order_number=re.findall('_____', username) # return ['01'] Name_with_dash=re.findall('_____',username) # ['Knappen_Michell_'] name=re.findall('_____',name_with_dash) # ['Knappen', 'Michell'] print(order_number[0],name[0],name[1]) # 01 Knappen Michell A.) \d+, \D+, [A-Z][a-z]+ B.) \D+, \d+, [A-Z][a-z]+ C.) \D+, \d+, [A-Z]+ D.) \w+, \D+, [A-Z][a-z]+

A.) \d+, \D+, [A-Z][a-z]+ *****\d+: This pattern matches one or more digits. In the given username "Knappen_Michell_01", it captures the order number "01". \D+: This pattern matches one or more non-digits. In the given username "Knappen_Michell_01", it captures the part before the order number, which is "Knappen_Michell_" (excluding the trailing underscore). [A-Z][a-z]+: This pattern matches an uppercase letter followed by one or more lowercase letters, representing a capitalized name. In the given username "Knappen_Michell_01", it captures the first name "Knappen" and the last name "Michell". Therefore, option A, which includes \d+, \D+, [A-Z][a-z]+, correctly extracts the order number and the first and last names from the given username, fulfilling the requirements of the scenario.

'\s' matches any whitespace character; '\S' any non-whitespace character. Notes: A space, a tab(\t), a carriage return(\r), a new line(\n) are all white spaces. Fill in the blank to extract ['3\t\n68', '78 6'] s="This thing happen 45 years ago or 6 years ago. I don't know. He told me it is 1000 years ago! 3\t\n68 year later, he will know 78 6 and he will come! " txt_d=re.findall('_____',s) print(txt_d) A.) \d+\s+\d+ B.) \s+\d+\s+ C.) \s+\d+\d+ D.) \d+\d+\s+

A.) \d+\s+\d+ ****\d+: This pattern matches one or more digits. In the given string s, it captures the sequences of digits. \s+: This pattern matches one or more whitespace characters. In the given string s, it captures the whitespace characters between the digits and between the sequences. Putting these together: \d+\s+\d+: This pattern matches one or more digits followed by one or more whitespace characters followed by one or more digits. In the given string s, it correctly captures the sequences '3\t\n68' and '78 6', which are separated by whitespace characters. Therefore, option A, which includes \d+\s+\d+, is the correct answer for extracting the specified sequences from the given string.

The method "display" in the following code block is an empty method. Please select an appropriate key word to fill in the blank. # define a class class person: Name ="" Age =0 def set(self,name,age): self.Name=name self.Age =age def display(self): ________ # create a object Tom =person() Tom.set("Tom Ray", 55) Tom.display() # nothing done A.) pass B.) break C.) continue D.) empty

A.) pass ****In Python, the pass statement is a placeholder that does nothing when executed. It's often used when a statement is syntactically required but no action is needed. In this context, since the display method is empty and does not perform any action, we need to include a placeholder statement. So, when we select pass to fill in the blank, it means that when the display method is called, it will do nothing but continue the execution without raising any errors. Therefore, the correct answer is A.) pass.

Select the select functions/ modules for the following code block: # Launch windows application. import _______ _______("notepad.exe") A.) subprocess, subprocess.run B.) subprocess, subprocess.execute C.) os, os.execute D.) os, os.run

A.) subprocess, subprocess.run ****The code block aims to launch a Windows application, specifically "notepad.exe". In Python, the subprocess module provides a way to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. The subprocess.run() function specifically runs the command passed to it as an argument, waits for it to complete, then returns a Completed Process instance with information about the process. Therefore, the correct module to import is subprocess, and the correct function to use is subprocess.run. With subprocess.run("notepad.exe"), the "notepad.exe" application will be launched. Thus, the correct answer is option A: subprocess, subprocess.run.

Compare the following two strings in Python: 'a' _______ 'A' A.) < B.) > C.) =

B.) > ***When comparing strings in Python using the comparison operators, Python compares the strings based on their lexicographical order, which is essentially their alphabetical order. The symbol '<' indicates "less than", and it means that the first string comes before the second string in the lexicographical order. In this case, 'a' comes before 'A' in the alphabetical order, so the correct symbol to complete the comparison is '>. Therefore, the correct answer is option B: '>'.

The purpose of the following codes is to add num1 and num2 and then show the results. Select the correct answers to fill in the blanks. ---------------------------------- num1=3 num2= 7 s= "{_______} *{________}={________}".format(num1+num2, num1,num2) print(s) --------------------------------- A.) 0,1,2 B.) 1,2,0 C.) 0,2,1 D.) 1,0,2

B.) 1,2,0 ***num1=3 and num2=7 are defined as variables. The string s is formatted using .format() method with three placeholders {} inside it. Inside .format(), the first placeholder is filled with the sum of num1 and num2 (num1+num2). The second placeholder is filled with the value of num1. The third placeholder is filled with the value of num2. So, after the formatting, the string s becomes: "10 *3=7" Now, let's see which answer fits the blanks: num1+num2 is 3+7=10, so it fits the first blank. num1 is 3, so it fits the second blank. num2 is 7, so it fits the third blank. The correct sequence is 1,2,0, which corresponds to option B: 1,2,0.

Which of the following is not a Python Comparison Operator? _____. A.) == B.) = C.) < D.) <= E.) ! =

B.) =

What can Python do? _____ is correct. A.) Python can be used for rapid prototyping, or for production-ready software development. B.) All statements are correct. C.) Python can connect to database systems. It can also read and modify files D.) Python can be used on a server to create web applications. It can also be used alongside software to create workflows E.) Python can be used to handle big data, artificial intelligence (machine learning), and perform complex mathematics.

B.) All statements are correct.

In order to include the python files already existed, which keyword should be used? _____. A.) Include B.) Import C.) Have D.) Search

B.) Import

The output of the following codes is _______________. total = 0; # This is global variable. def sum( arg1, arg2 ): total = arg1 + arg2; # This is local variable print("Inside the function local total : ", total) return total; # Now you can call sum function sum( 10, 20 ); print("Outside the function global total : ", total) A.) Inside the function local total : 0 Outside the function global total : 0 B.) Inside the function local total : 30 Outside the function global total : 0 C.) Inside the function local total : 30 Outside the function global total : 30 D.) Inside the function local total : 0 Outside the function global total : 30

B.) Inside the function local total : 30 Outside the function global total : 0 ***This code defines a function sum that calculates the sum of two arguments arg1 and arg2 and prints the result inside the function. However, it also defines a global variable total initialized to 0 outside of the function. Inside the function sum, a local variable total is defined and assigned the sum of arg1 and arg2. This local variable total shadows the global variable total within the function's scope. When the function sum is called with arguments 10 and 20 (sum(10, 20)), it prints the local total, which is 30. After calling the function, when print("Outside the function global total : ", total) is executed, it prints the global variable total, which remains 0 because the global variable wasn't modified within the function. So, the correct output is: Inside the function local total : 30 Outside the function global total : 0 This matches option B: "Inside the function local total : 30 Outside the function global total : 0".

Regarding local variables, which of the following statements is correct? A.) Different functions cannot have local variables with the same name B.) The scope of a local variable is the function in which the local variable is created C.) Local variable can be accessed by statements inside its function which precede its creation D.) None of them

B.) The scope of a local variable is the function in which the local variable is created

If we define a set: myset = {'Apples', 'Bananas', 'Oranges'}, what will appear if we enter: myset[0] A.) 'Apples' B.) TypeError: 'set' object does not support indexing

B.) TypeError: 'set' object does not support indexing

In the following function, _____ is applied to function arguments. def add_many_number(num1,*num_tuple): sum=0 sum=sum+num1 for num in num_tuple: sum=sum+num return(sum) A.) Required arguments B.) Variable-length arguments C.) Default arguments D.) Keyword arguments E.) Arbitrary keyword arguments

B.) Variable-length arguments ***This function utilizes variable-length arguments denoted by *num_tuple. Variable-length arguments allow the function to accept an arbitrary number of arguments, which are then collected into a tuple named num_tuple. Inside the function, it iterates over this tuple and adds each element to the sum, starting with the initial value of num1. So, the correct answer is B.) Variable-length arguments, as they allow the function to accept multiple arguments in a tuple format.

_____ matches any one of a list of characters x;_____ matches any single character; ______ matches zero or more x; ______ matches one or more x. A.) dot ., [x], x+, x* B.) [x], dot ., x*, x+ C.) [x], dot ., x+, x* D.) dot ., [x], x*, x+

B.) [x], dot ., x*, x+ ****Sure, let's break down the explanation for why option B is the correct answer based on the given descriptions: [x]: This matches any one of a list of characters x. This matches with option B as it contains a character class enclosed within square brackets, which is [x]. dot .: This matches any single character. This matches with option B as it contains a dot, which represents any single character. x*: This matches zero or more occurrences of x. This matches with option B as it contains the asterisk (*) following the character x, indicating zero or more occurrences. x+: This matches one or more occurrences of x. This matches with option B as it contains the plus sign (+) following the character x, indicating one or more occurrences. Therefore, option B, which includes [x], dot ., x*, x+, matches all the given descriptions and is the correct answer.

Regarding the "try...except..." suite, which of the following statements is wrong? A.) if no special handler exists, Python handles it, meaning the program halts and with an error message as we have seen so many times B.) none of the above C.) the try suite contains code that we want to monitor for errors during its execution. D.) if an error occurs anywhere in that try suite, Python looks for a handler that can deal with the error.

B.) none of the above

In the Python re module, the function _____ returns a list where the string has been split at each match A.) findall B.) split C.) sub D.) search

B.) split

According to Python name conventions, which of the following cannot be a variable's name in Python? _____. A.) this_is_a_variable B.) abc_123 C.) 123_abc D.) _abc_123

C.) 123_abc

In Python, t = (23, 'abc', 4.56, (2,3), 'def'). The output of t[-3] is A.) 23 B.) (2,3) C.) 4.56 D.) 'def'

C.) 4.56 ***In Python, tuples are ordered collections of items, and they are indexed starting from 0. So, when accessing elements of a tuple t, -1 refers to the last element, -2 refers to the second to last element, and so on. Given the tuple t = (23, 'abc', 4.56, (2, 3), 'def'), t[-3] refers to the third to last element of the tuple, which is 4.56. Therefore, the correct answer is 4.56

For the image tag in a HTML page, fill in the blank to extract image sources and names with a regular expression. str=""" <img src="Michigan%20Tech%20Pictures_files/IMG_5867g3.jpg" alt="1" width="700" height="231">""" pattern="______" img_list=re.findall(pattern,str) A.) <img\s+src=\"(\S\.-/+/(\S+jpg))\"\s B.) <img\s+src=\"[\S\.-/]+/\S+jpg\"\s C.) <img\s+src=\([\S\.-/]+/(\S+jpg))\"\s D.) <img\w+src=([\S\.-/]+/(\S+jpg))\"\w

C.) <img\s+src=/([\S\.-/]+/(\S+jpg))\"\s *****<img\s+src=: This part matches the opening of the image tag, including any whitespace characters (\s+), the literal characters "src=", and any additional spaces. ([\S\.-/]+/: This part captures the image source, enclosed within parentheses (). Here: [\S\.-/]+: Matches one or more non-whitespace characters, periods, dashes, or slashes, representing the path to the image file. /: Matches the slash character that separates directories in the path. (\S+jpg)): This part captures the image name, also enclosed within parentheses (). Here: \S+jpg: Matches one or more non-whitespace characters followed by "jpg", representing the image file name. \"\s: This part matches the closing quotation mark of the src attribute and any additional spaces. Therefore, the correct pattern to extract image sources and names is <img\s+src=([\S\.-/]+/(\S+jpg))\"\s. And the answer is C.) <img\s+src=([\S\.-/]+/(\S+jpg))\"\s.

Which of the following statements is wrong? A.) String is an immutable ordered sequence of chars B.) Tuple is an immutable ordered sequence of items C.) Items in a tuple should have the same data type. D.) List is a mutable ordered sequence of items

C.) Items in a tuple should have the same data type.

Regarding the method "__init__()" in Python classes, which of the following statements is wrong? A.) The arguments passed to the class name are given to its __init__() method B.) __init__ serves as a constructor for the class. Usually does some initialization work C.) None of them D.) An __init__ method can take any number of arguments. Like other functions or methods, the arguments can be defined with default values, making them optional to the caller.

C.) None of them

Regarding the "try/except group", which of the following statements is wrong? A.) if there is an error but no exception handling is found, give the error to Python B.) if no exception in the try suite, skip all the try/except to the next line of code C.) Only a single except suite can be associated with a try suite D.) if an error occurs in a try suite, look for the right exception; if found, run that except suite and then skip past the try/except group to the next line of code

C.) Only a single except suite can be associated with a try suite

About the features of Python, which statement is wrong? _____. A.) Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick. B.) The most recent major version of Python is Python 3 C.) Python works on only Microsoft Windows Operating Systems. D.) Python can be treated in a procedural way, an object-oriented way or a functional way. E.) Python has syntax that allows developers to write programs with fewer lines than some other programming languages.

C.) Python works on only Microsoft Windows Operating Systems.

Regarding defining and calling a function, which statement is wrong? A.) When a function is called, interpreter jumps to the function and executes statements in the block, and then jumps back to part of program that called the function B.) A main function is called when the program starts C.) The first character of a function name can be a number. D.) Any input parameters in a function should be placed within the parentheses.

C.) The first character of a function name can be a number.

Regarding sets in Python, which statement is false? A.) A set is an unordered collection of items B.) Every element in a set is unique, iterable and immutable C.) The set as a whole is immutable D.) A set can only contain unique elements

C.) The set as a whole is immutable

Read the following Python codes: l1=[1,2,3] l2=l1 l2[0]=10 print(l1) What is the output? A.) Traceback error B.) [1,2,3] C.) [10,2,3]

C.) [10,2,3] ***First, we create a list called l1 with the values [1, 2, 3]. Then, we create a new variable called l2 and set it equal to l1. This means l2 now refers to the same list as l1. Next, we change the first element of l2 to 10. Since l2 and l1 refer to the same list, this change also affects l1. Finally, we print l1. So, when we print l1, the output is [10, 2, 3]. This is because both l1 and l2 are referring to the same list, and the change made to l2 also affects l1. Therefore, the correct answer is [10, 2, 3].

Python is sensitive to end of line stuff. To make a line continue, which symbol should be used? _____. A.) ! B.) . C.) \ D.) # E.) -

C.) \

Read the Python codes: t=('a','b','c') type(t) type() above is a _____ A.) method B.) neither of the answers C.) function

C.) function ****We have a tuple t with the values ('a', 'b', 'c'). Then, we use the type() function to find out the type of t. The type() function takes an object (in this case, t) as input and returns the type of that object. So, when we use type(t), it returns the type of t, which is <class 'tuple'>. Therefore, type() is a function because it takes an input and returns a value based on that input. So, the correct answer is "function" because type() is a built-in Python function that returns the type of an object

Select the select functions/ modules for the following code block: #Print out all directories, sub-directories and files with os.walk() import _____ for root, dirs, files in ______('c:\\MyPythonDir'): print(root) print(dirs) print(files) A.) subprocess, subprocess.mkdir B.) subprocess, subprocess.walk C.) os, os.walk D.) os, os.mkdir

C.) os, os.walk ***The code block intends to print out all directories, sub-directories, and files within a specified directory. The os module in Python provides functions related to interacting with the operating system. The os.walk() function specifically allows us to traverse a directory tree, yielding the root directory, its subdirectories, and the files contained within them. Therefore, the correct module and function to import are os and os.walk. With os.walk('c:\\MyPythonDir'), we can iterate over the directory structure, obtaining root (the current directory being visited), dirs (a list of subdirectories in the current directory), and files (a list of files in the current directory). Printing out root, dirs, and files allows us to inspect the directory structure. Thus, the correct answer is option C: os, os.walk.

( Indicates where string extraction is to start, ) Indicates where string extraction is to end. The capturing order is: from external to internal. In order to extract both email addresses and user names, as follows: # return [('[email protected]', 'whzhou'), ('[email protected]', 'tom2020'), ('[email protected]', 'kati'), ('[email protected]', 'hadoop')] Fill in the blank in the following codes. s= "My e-mail is [email protected]. His E-mail is [email protected]. Her E-mail is [email protected]. His father's Email is [email protected] " email=re.findall("______" ,s) A.) (\w+@(\w+)\.\w+) B.) ((\w)@\w\.\w) C.) ((\w+)@\w+.\w+) D.) ((\w+)@\w+\.\w+)

D.) ((\w+)@\w+\.\w+) ****(\w+)@\w+.\w+: This pattern matches an email address followed by a username.(\w+): This captures one or more word characters (letters, digits, or underscores) before the "@" symbol, representing the username.@: This matches the "@" symbol.\w+: This matches one or more word characters after the "@" symbol, representing the domain name (excluding the top-level domain)..: This matches the dot "." symbol.\w+: This matches one or more word characters after the dot, representing the top-level domain. In the given string s, this pattern correctly identifies both email addresses and their corresponding usernames. Therefore, the output of re.findall("(\w+)@\w+\.\w+", s) will be a list of tuples containing both email addresses and usernames. Option D, ((\w+)@\w+\.\w+), is the correct answer.

In Python, t = (23, 'abc', 4.56, (2,3), 'def'). The output of t[2:] is A.) (4.56, (2,3)) B.) ('abc',4.56, (2,3), 'def') C.) None of them D.) (4.56, (2,3), 'def')

D.) (4.56, (2,3), 'def') In Python, you can have collections of items stored together, like in a box. This collection is called a tuple. Each item in the tuple has an index, which is like its position in the box. Now, let's say we have a tuple called t with these items inside: (23, 'abc', 4.56, (2, 3), 'def'). When we write t[2:], it means we want to start from the item at index 2 and go all the way to the end of the tuple. So, we're asking for everything from the third item onwards. In our tuple t, the third item is 4.56, then (2, 3) is the fourth item, and 'def' is the fifth item. So, when we use t[2:], we get (4.56, (2, 3), 'def'). This includes all the items from the third item to the end of the tuple. That's why the correct answer is (4.56, (2,3), 'def').

Regarding functions and the benefits of modularization a program with functions, which statement is wrong? You Answered A.) We can test and debug each function individually. Functions can speed up the software development. B.) Functions promote code reuse, so we can write the function codes once and call it multiple times. C.) A function has a group of statements within a program that perform as specific task D.) None of them E.) Different team members can write different functions, so functions can facilitate the team development.

D.) None of them

The output of the following codes is _______________. def changeme(mylist ): mylist.append([1,2,3,4]); print("Values inside the function: ", mylist) return list = [10,20,30]; changeme(list ); print("Values outside the function: ", list) A.) Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30] B.) Values inside the function: [10, 20, 30] Values outside the function: [10, 20, 30, [1, 2, 3, 4]] C.) Values inside the function: [10, 20, 30] Values outside the function: [10, 20, 30] D.) Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

D.) Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]] ***This code defines a function changeme that appends [1,2,3,4] to a list passed as an argument and prints it. Then, it calls this function with a list [10,20,30]. Since lists are mutable, changes made inside the function affect the original list outside the function. So, both prints show the list with the appended [1, 2, 3, 4].

The output of the following codes is _______________. def printinfo(var1, var2): print("var1: ", var1) print(var2: ",var2) return; printinfo(var2=50, var1="miki" ); Var1: miki Var2: 50 A.) Var1: 50 Var2: 50 B.) Var1: miki Var2: miki C.) Var1: 50 Var2: miki D.) Var1: miki Var2: 50

D.) Var1: miki Var2: 50 *****This code defines a function called printinfo that takes two arguments var1 and var2, and prints their values. Then, the function is called with named arguments var1 assigned to "miki" and var2 assigned to 50. In Python, when calling a function with named arguments, the order doesn't matter. The values are assigned based on the parameter names specified in the function definition. So, when calling printinfo(var2=50, var1="miki"), "miki" is assigned to var1 and 50 is assigned to var2. Therefore, the correct output is: Var1: miki Var2: 50 This matches option D: "Var1: miki Var2: 50".

All of the following are correct regarding scripting languages, except _____. A.) Scripting languages are often used to combine the functionality of other programs. They act as glue. B.) Dynamically typed ( The type of a variable can be changed during the execution of the program) C.) Interpreted (no compilation step) D.) You cannot directly use a variable. You must declare it first.

D.) You cannot directly use a variable. You must declare it first.

$ Matches end of a line and end of a string. Escape \ is to change back to the original meaning. What is the output of the following codes? S="He has {2+50}=70$ and his father has 1000" extr=re.findall("\{\d+\+\d+\}=\d+\$",S) print(extr) A.) ['1000'] B.) ['{2+50}=70'] C.) [] D.) ['{2+50}=70$']

D.) ['{2+50}=70$'] ****{\d++\d+}=\d+$: This pattern matches the specific sequence "{2+50}=70$" in the given string S.\{: Matches the opening curly brace "{".\d+: Matches one or more digits.\+: Matches the plus sign "+".\}: Matches the closing curly brace "}".=: Matches the equals sign "=".\d+: Matches one or more digits.\$: Matches the dollar sign "$" at the end of the string. In the given string S, the sequence "{2+50}=70$" is the only substring that matches this pattern. Therefore, the output of re.findall("\{\d+\+\d+\}=\d+\$", S) will be ['{2+50}=70$'], as it correctly identifies the matching substring in the string S. Option D, ['{2+50}=70$'], is the correct answer.

For the methods of Sets, which statement is wrong? A.) You can use the method add to add a value to a set B.) You can update a set by adding elements from one set to another set. You can use the update() method to do this C.) You can use the clear method to remove all values from a set D.) None of them E.) An existing set can be copied to a new set by using the copy() method F.) The remove() method raises an error when the specified element doesn't exist in the given set, , however the discard() method doesn't raise any error if the specified element is not present in the set and the set remains unchanged G.) You can use the pop method to remove and return an arbitrary value from a set

D.) none of them (these are all methods of sets)

Please select the correct file access modes. ___: Opens a file for reading, error if the file does not exist; ___: Opens a file for appending, creates the file if it does not exist; ___: Opens a file for writing, creates the file if it does not exist; ___: Creates the specified file, returns an error if the file exists. A.) r, w, a, x B.) r, a, x, w C.) w, a, r, x D.) r, a, w, x

D.) r, a, w, x ****r (read): Opens a file for reading. It will raise an error if the file does not exist. a (append): Opens a file for appending. If the file does not exist, it creates the file. w (write): Opens a file for writing. If the file does not exist, it creates the file. x (exclusive creation): Creates the specified file, but it returns an error if the file already exists. So, based on the descriptions provided: "r" is for reading, and it raises an error if the file doesn't exist. "a" is for appending, and it creates the file if it doesn't exist. "w" is for writing, and it creates the file if it doesn't exist. "x" is for exclusive creation, and it returns an error if the file exists. Therefore, the correct sequence is "r, a, w, x", which matches option D.

What is the output of the following codes? txt = "The rai8n in Spai99N. The snow in USA. Thai2000 land! ai2000N" x = re.search("(ai(\d+)([A-Z]+))", txt) print(x.group(2)) re.search("(ai(\d+)([A-Z]+))", txt) print(x.group(2))99 >>> print(x.group())ai99N >>> print(x.group(1))ai99N >>> print(x.group(3))X A.) ai8n B.) ai99 C.) ai99N D.) ai8 E.) 99 F.). 8

E.) 99 *****re.search("(ai(\d+)([A-Z]+))", txt): This line searches for a pattern in the string txt. The pattern consists of: ai: This matches the literal characters "ai". (\d+): This is a capturing group that matches one or more digits. ([A-Z]+): This is another capturing group that matches one or more uppercase letters. print(x.group(2)): This prints the contents of the second capturing group, which is the digits (\d+). In the matched substring "ai99N", the digits are "99", so this line prints "99". print(x.group()): This prints the entire match, which is "ai99N". print(x.group(1)): This prints the contents of the first capturing group, which is the entire match, "ai99N". print(x.group(3)): This prints the contents of the third capturing group, which is the uppercase letters ([A-Z]+). In the matched substring "ai99N", there are no uppercase letters, so this line prints nothing. Therefore, the output of the code is: Copy code 99 ai99N ai99N Option E, 99, is the correct answer.

Is the following statement true or false? A file directory must contain a file named __init__.py in order for Python to consider it as a package

True

Is the following statement true or false? If a requested method is not found in the derived class, it is searched for in the base class. This rule is applied recursively if the base class itself is derived from some other class. To execute the method in the parent class in addition to new code for some method, explicitly call the parent's version of the method.

True

What is the output of the following code block? class Person: def __init__(self,fname,lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname,self.lastname) class Student(Person): def __init__(self,fname,lname,age): self.firstname = fname self.lastname = lname self.Age = age def printage(self): print(self.Age) Tom=Student("Tom","Ray",25) print(isinstance(Tom,Person))

True

About two kinds of attributes, 1) __________ are variable owned by a particular instance of a class. Each instance has its own value for it. These are the most common kind of attributes. 2) __________ are owned by the class as a whole. All class instances share the same value for it. They are good for (1) class-wide constants and (2) building counter of how many instances of the class have been made.

data attributes, class attributes


Kaugnay na mga set ng pag-aaral

AP Psychology Myers Chapter 4 (Nature/Nurture) Extra Study Material

View Set

EverFi Module 1 - Savings - Final Quiz Answers

View Set

Nursing Care of the Child With an Alteration in Intracranial Regulation/Neurologic Disorder

View Set

12; The British Invasion: The Rolling Stones

View Set

Chapter 15: Psychological Disorders

View Set

A&P Chapter 11 Fundamentals of the Central Nervous System and Nervous Tissue - Notes Part 2 of 2

View Set