Download Python Fundamentals and Best Practices and more Exams Nursing in PDF only on Docsity! Intro to Python Exam Questions: well answered to pass (33) Why are functions helpful? - correct answer ✔✔Functions facilitate code reusability, readability, and maintenance What is "scope" in terms of programming language python? - correct answer ✔✔Scope is the term used to describe the points at which in code variables and functions are defined. Why is there an error when trying to run this code? a=int(input()) b=int(input()) if c<a+b: print("Less than a +b:) a = b= c=1 print (a,b,c) - correct answer ✔✔The variable c is not in scope or defined in line 3. Which of the following lines of code defines a function named "my_func" that has three parameters (a, b, and c) where b defaults to 0 and c defaults to "Yes"? a. my_func(a,b,c): b. def my_func(a, b(0), c("yes"): c. def my_func(a, b=0, c="Yes"): d. def my_func(a, b, c): - correct answer ✔✔c Which of the following lines of code will not call a function named "my_func" that has three parameters (a, b, and c) where b defaults to 0 and c defaults to "Yes"? a.) my_func( ) b.) my_func(1, c="No") c.) my_func(1) d.) my_func(1, 2) - correct answer ✔✔a Which of the following will import a specific function "add_numbers" from a library "adding_library"? - correct answer ✔✔from adding_library import add_numbers import <file name without the .py extension> (How to import the full module/libray) from <file name without the .py extension> import < function name > There is a function, "my_function". Within that function, a variable called "my_var" is created. In which namespace does my_var exist? - correct answer ✔✔local Python's int( ) function will take an argument and convert it to an integer. In which namespace does int( ) exist? - correct answer ✔✔built-in Which best describes the difference between a comment and a docstring in Python? - correct answer ✔✔Comments do not have a functional purpose but docstrings tie into the Python documentation help library. Which of the following is not a Python library used frequently for data science applications? a.) NumPy b.)SciPy if my_num < 0: print(1) elif my_num > 0: print(2) else: print(3) - correct answer ✔✔3 Why will the following code not run? my_num = 0 int(input()) if my_num < 0 print(1) elif my_num > 0 print(2) else print(3) - correct answer ✔✔The colons are missing at the end of the else, elif, and if lines. Which of the following will generate a range of numbers from 11 to 99? - correct answer ✔✔range[11,100] What does this Python expression evaluate to: 8==8 - correct answer ✔✔True I have a variable called my_var that contains the value 10. What does the statement my_var +=5 do? - correct answer ✔✔Adds 5 to the current value of my_var, so my_var will contain the value 15 If I use a variable in an if statement before that variable has been created, what error will I likely get? - correct answer ✔✔NameError I have a variable called my_var that contains the value 10. What does the expression my_var%=4 do? - correct answer ✔✔Computes the modulus of my_var and 4, which is 2 and assigns that value (2) to my_var I have a set called my_set and I want to add a new value (5) to the set. Which of the following will accomplish that? - correct answer ✔✔my_set.add(5) What does the "a" mean when used as the mode argument in opening a file? - correct answer ✔✔Append mode- write at the end of existing data I have a dictionary, defined as (my_dictionary = {"Age":22, "Name":"Bob"}). Which of the following will retrieve the age from my_dictionary? - correct answer ✔✔my_dictionary.get("Age") What does the input function do and which data type does it return? - correct answer ✔✔Prompts the user to input a value. That value is returned as a string. What is the primary benefit of commenting code? How can good and bad comment blocks impact this benefit? - correct answer ✔✔Commenting code makes it easier to read which can speed up debugging. Good comments will help the programmer understand the code while bad comments will not and may even confuse people, other programmers, manual debugging. Describe tow scenarios in which you might want to use a dictionary as a data type. Specifically, mention how you would use the dictionary (what is to be represented by keys and what is to represented by values). - correct answer ✔✔Use a dictionary to represent a phone book. The names would be the keys and the phone numbers would be the values. What are the strengths of Python programming language? - correct answer ✔✔-Free and open source -Large library/database -Large programming community -easy to prototype -readable -interpreted language (codes are processed at runtime without need of comping) -programs can run interactively -cross platform compatible -great for large data analysis -can be used for web development What are the weaknesses of python programming language? - correct answer ✔✔-slow compared to other programming languages such as Java and C++ -lacks support for mobile app development -no security/warranty -uses large amount of memory -lacks support for relational databases What are the benefits of Jupyter Lab? - correct answer ✔✔-There is more you can do in Jupyter lab compared to just using the python interpreter -uses the web browser instead of python terminal prompt environment -combines rich formatted text (markdown), inline code, math formulas, plots/graphs all in single document Which of the following is not a reason why Python is such a popular software development language? a) Python is relatively easy to read. b) Python code is compiled into an executable, which is helpful for web development. c) Python is very concise, meaning you can do more with less code. d) Python has a large community of active developers building libraries and tools for Python development. - correct answer ✔✔b operations: .get("Hair") List: [ ] elements are ordered and changeable (mutable). Duplicates are allowed. How do you write to a file? - correct answer ✔✔my_file= open('my_file.txt', 'w') How do you create a file? - correct answer ✔✔my_file= open('my_file.txt', 'x') How do we open a file, write to it (at the end, not overwrite), and then close the file? - correct answer ✔✔my_file=open('my_file', 'a') <--- this file must already exist. my_file.write('I would love for this exam to be over') (<-- will not appear in the file until the file is closed. ) my_file.close() Why do we se variables in python? - correct answer ✔✔A variable in Python is a reserved memory location to store values. In other words, a variable in a python program gives data to the computer for processing. Declaring and re-declaring a variable in Python is as easy as writing names and assigning values to it. What is the result of 80%25? - correct answer ✔✔5 How would you put quotes into a string in Python? - correct answer ✔✔my_string = "this has \"quotes\"." Or you can use ' ' to open and use " " to add the quotation If I h ave a string "my_string" with the value "Python is so powerful!" how do I substring to get just "is so"? - correct answer ✔✔my_string[7:12] I want to open and write to a file called "thatfile.txt". If the file does not exist, I want to create it. If it does exist, I want to write at the end of the file, preserving what's already in the file. How do I do that? - correct answer ✔✔that_file=open("that_file.txt", "x") that_file=open("that_file.txt", "a") that_file.write('This is a great day!') that_file.close() What are the syntax rules for creating a variable? - correct answer ✔✔Must start with either a letter or an _ May only include letters, numbers, and _ Should be all lowercase. (Only constants have all UPPERCASE, i.e. gravity.) -words should be separated by an underscore, however if they are not, Python will not mark it as an error. example of incorrect variable: &player_age (starts with something other than a lowercase letter or _) What type of value is 0o42? - correct answer ✔✔octal What type of value is 42? - correct answer ✔✔int What type of value is 4 + 2J? - correct answer ✔✔complex What type of value is 4.2? - correct answer ✔✔float What is the result of this equation: int(5.8 * 2)? - correct answer ✔✔11 If there is a string "my_string" with the value "I love Python!" how do you substring to get just "Python!"? - correct answer ✔✔my_string[7: ] If there is a string "my_string" with the value "I love Python!," how do you substring to get just "love"? - correct answer ✔✔my_string[2:6] What is the purpose of an escape character? - correct answer ✔✔To include special characters in a string like a backslash or quotation mark. What is the purpose of a collection in Python? - correct answer ✔✔-to allow you to organize data more effectively -to simplify code -to let the programmer combine multiple pieces of data into one variable object What is a key difference between a dictionary and a set? - correct answer ✔✔Similarity: Both sets and dictionaries cannot have duplicates. (Key for dictionary). They are also both unordered. Differences: Dictionaries store elements in key/value pairs, and sets do not. What is the proper way to add the number 24 as an element to the set that I've named "my_favorite_numbers"? - correct answer ✔✔my_favorite_numbers.add(24) What is the proper way to add the number 24 at index 3 of the list that I've named "my_favorite_numbers"? - correct answer ✔✔my_favorite_numbers.insert(3, 24) LOCATION and then what you want to index. First you need to tell it WHERE you want it to go, then WHAT it is. What does "r" do when used with the file open method? - correct answer ✔✔opens the file in read mode. if x == 4: continue elif x > 6: break print(x) 0,1,2,3,5,6 Iterate the code block with x in range(10) i.e., x runs from0,1,2,...,9.If x is equal to 4, the continue statement skips the remaining codes and continues with the next number in the range i.e. 5. If x is greater than 6, break statement forces the code block to exit. The result of print(x): 0, 1, 2, 3, 5, 6 What is an iterator? - correct answer ✔✔allows the interpreter to loop through values in lists, sets, tuples, and dictionaries example: my_list = [1, 3, 5, 7] for x in my_list: print(x) What are comprehensions? - correct answer ✔✔are container objects (i.e. lists, sets, tuple, dictionaries) that are generated from existing container objects. syntax: [<expression> for n in <existing_list>] example: my_list = [1, 3, 5, 7] my_new_list = [2*n for n in my_list] How do you do a comprehension with a tuple? - correct answer ✔✔my_tuple= (1, 3, 4, 5) my_new_tuple= tuple(n*1 for n in my_tuple) What is the code that will generate a range of numbers from 11 to 99 with increment of 2? - correct answer ✔✔range(11, 100, 2) Why will the following code not run? my_num = 0 int(input()) if my_num < 0 print('negative') elif my_num > 0 print('positive') else print('zero') - correct answer ✔✔no : after each if, elif, and else Which of the following lines of code will print the output of all four variables (a, b, c, and d)? - correct answer ✔✔print(a, b, c, d) I have a variable called my_int that holds the integer value 42. I want to convert that value to a string data type and assign that value to a variable called my_str. Which of the following will do that? - correct answer ✔✔my_str = str(my_int) What is the output of the following code when the user inputs "30" at the prompt? my_int = int(input()) if my_int * 2 < 10: print("Less than 10!") elif my_int * 2 < 20: print("Between 10 and 19!") elif my_int * 2 < 50: print("Between 20 and 49!") else: print("Bigger than 50!") - correct answer ✔✔Bigger than 50! What is the difference between an expression and a statement in Python? - correct answer ✔✔A statement is a line of code the interpreter can execute, an expression is a section of code that the interpreter evaluates to a value. What is the output of the following code? my_str = "I love Python! It is so much fun!" if len(my_str) < 20: print("Python is awesome!") else: print("Python is amazing!") - correct answer ✔✔Python is amazing! my_variable = input() if int(my_variable) < 50 print("Less than 50!") else: print("50 or more!") - correct answer ✔✔There is a missing colon (:) after the if statement on line 2. What is the difference between break and continue? - correct answer ✔✔The break statement will move the execution outside and just after a loop. (Will discontinue the loop, stop the loop.) The continue statement will move the execution to the start of the loop. (skipping one, it will not continue further through the execution.) What does global scope mean? - correct answer ✔✔global keyword inside a function will make a variable accessible outside a function when declaring the variable. (Makes the variable in scope inside the function and outside.) What is the difference between parameter and argument? - correct answer ✔✔A parameter is the variable within a function when it is being defined. An argument is what is passed through the function in place of the parameter. Example: def greetings (first_name): print('Hello, ', first_name,'!') greetings('Jane') first_name= parameter 'Jane' is the argument What is the difference between positional arguments and named arguments? - correct answer ✔✔Once a function is defined with parameters, you can use either positional arguments or named arguments to pass through the function. Positional arguments correspond with the order position of the defined parameters within the function. Named arguments do not necessarily have to correspond with the position of the parameters within the argument. Named arguments use an = (assignment operator) to associate the argument with the correct parameter. Example: personal_info(age=25, position='Senior manager', name= 'Jane') As the arguments are already defined, they do not need to be within " " What is a default argument? - correct answer ✔✔When a function is defined, you can use a default argument as your given parameter, which means if an argument is not provided, the default argument will be utilized. example: def first_name(age=23, address=brook street, name=Alex) : print("Please make sure all given information is correct.) print(age, address, name) first_name(34) Please make sure all given information is correct. 34 69 brook street Alex How does one make a function to return values? - correct answer ✔✔While a function can take on arguments, it can also return values. This can be done by using the "return" keyword inside the function. example: def rectangle_area(length, width): return length * width Note: any codes after the return statement inside a function will not be executed. Which of the following lines of code defines a function named "my_func" that has three parameters (a, b, and c) where b defaults to 0 and c defaults to "Yes"? - correct answer ✔✔def my_func(a, b=0, c="Yes"): Which of the following lines of code will not call a function named "my_func" that has three parameters (a, b, and c) where b defaults to 0 and c defaults to "Yes"? a.) my_func( ) b.) my_func(1, c="No") c.) my_func(1) d.) my_func(1, 2) - correct answer ✔✔a.) my_func( ) there must at least be one argument listed when calling my_func(), because a does not have a default! What is the output of the following code? def print_it(): print("I") print("like") print("it") print_it() print("a lot!") - correct answer ✔✔I like it a lot! I want to define a function called "make_it_happen_captain." Which of the following will accomplish that task? - correct answer ✔✔def make_it_happen_captin(): Why do we use functions in python? - correct answer ✔✔1. to eliminate the need to retype code multiple times 2. to improve code readability 3. to reduce the potential for bugs by placing repetitive code in one location The except block will be ignored if there is no error. You can also add a finally clause or an else clause. The finally clause will be executed regardless of whether there is an exception or not. This is useful for cleaning up operations. try: value = input('Type an integer: ') result = str(5 / int(value)) print('5 divided by ' + value) except ZeroDivisionError: print('You tried to divide by zero!') else: print('The result is ' + result) finally: result = '' print('The try except is completed.') What are the five different levels of logging? - correct answer ✔✔debug info warning error critical DIWEC-DI With Eric C What is the difference between all three error types? - correct answer ✔✔Syntax error: Error due to code not conforming with syntax rules. Syntax errors can prevent an application from running. Exception error: Error due to incorrect arithmetic operations, type mismatch, or unexpected operations. Exceptions, if not caught, will prevent the program from proceeding. (error occurs at runtime) Logical error: Error due to incorrect programming logic. Logical errors do not stop the program execution and are therefore hard to detect. Syntax error: InvalidName - correct answer ✔✔example: 1st_name= 'Jane' corrected: name_1st Rule: variable name must start with either a letter or underscore Syntax error: IncorrectIndentation - correct answer ✔✔example: if x>3: print (x) corrected: if x >3 print(x) Syntax error: MissingColon - correct answer ✔✔example: if x > 3 corrected: if x > 3: Syntax error: Missing keyword - correct answer ✔✔example: add(x, y): return x + y corrected: def add(x, y): return x + y Syntax error: Misspelt keyword - correct answer ✔✔fi x > 3: if x > 3: Syntax error: Invalid expression - correct answer ✔✔if x = 0: if x==0: Description of logging.warning: - correct answer ✔✔Third level of severity. Useful for issuing a warning regarding a particular runtime event. Something unexpected happens. -Indicative of some problem in the near future. "disc space low" the software is still working as expected. Description of logging.error: - correct answer ✔✔Fourth level of severity. Useful for catching a specific error. Due to a more serious problem, the software has not been able to perform some function. Description of logging.critical: - correct answer ✔✔Highest level of severity. Useful for indicating serious errors which can prevent the program from running. -Indicating that the program itself may be unable to continue running. How to change the default setting for logging from warning to debug? - correct answer ✔✔logging.basicConfig(level=logging.DEBUG) DEBUG must be all caps (constant) How to create a logging file? - correct answer ✔✔logging.basicConfig(filename="my log.log', level=logging.DEBUG) How to change the format of your logging file? - correct answer ✔✔logging.basicConfig(filename="my_log.log",level=logging.DEBUG, format='%(asctime)s: % (message)s' All of the various formatting tasks need to be separated by a colon. What does an "invalid syntax" error message mean? - correct answer ✔✔Something in your code does not conform to the Python programming syntax rules and cannot be interpreted properly. What are some ways the interpreter helps you find the cause of a syntax error? - correct answer ✔✔1. The interpreter provides the line number of what it believes to be the cause of the error. 2. The phrase "syntax error" itself helps you understand that something in the code goes against Python programming rules. Which of the following will cause an exception in Python programming? - correct answer ✔✔An error that terminates the program during program execution. Incorrect: -A variable name that does not conform to Python naming standards or conventions (syntax error?) -Forgetting to put the colon at the end of an if statement (syntax error) Dividing by zero will result in what type of error? - correct answer ✔✔ZeroDivisionError I'm writing code where I'll be accessing a file. It's a likely place for a file input/output error to occur. What's the best way to handle that? - correct answer ✔✔Place all file I/O code in a try/except block and specify file-related errors in the except block. This will catch file errors we anticipate, but nothing else. What does the finally clause do within a try block? - correct answer ✔✔Cleans up the code prior to exiting the try/except block. It contains code that executes after a try block regardless of whether an exception occurs. The code in a finally block will always be executed after the try/except block. Which line of code below will set the log level to Warning? - correct answer ✔✔logging.basicConfig(level=logging.WARNING) Besides using whatever text you wish to describe the error, is there a way to further customize the log messages? - correct answer ✔✔Yes, you can pass in attributes representing things such as time of the error, line numbers, process ID, etc. What are Python namespaces and why are they important? - correct answer ✔✔Namespace is where the variable is operable. Build-in: contains all build-in functions and exceptions and is in scope through the program. Global: Contains all the names of variables and functions that are created in the program and reside outside the functioning is in scope outside functions. Local: In scope only inside the function. (contains all names within a function) What are the two ways of documenting Python codes? - correct answer ✔✔docstrings and comments What are the five major data science packages in Python? - correct answer ✔✔Numpy Scipy Pandas Matplotlib Scikit-Learn How do you get help to understand a function? - correct answer ✔✔>>> help(say_hello) help(<function name>) How to indicate an even number in an expression? - correct answer ✔✔even: n % 2 ==0 odd: n % 2 !=0 odd n %2 == 1 What is a boolean? - correct answer ✔✔true or false value What is the difference between = and ==? - correct answer ✔✔One = is to assign the value to a variable and two == is for comparison.