Made with ScholarlyMake flashcards like these from your own notes
Question:How does a Python interpreter run a program saved in a .py file?
Answer:The interpreter reads the code and translates it into instructions the computer can understand. For example, python hello.py runs the program in hello.py.
Question:How do arguments influence a function such as print?
Answer:Arguments are inputs passed to a function that influence its behavior. The argument to print determines what it displays.
Question:How does assignment store a function’s returned value for later use?
Answer:The assignment operator copies the value returned by the expression on the right into the variable on the left. For example, name = input(...) stores the user’s response in name.
Question:How do parameters differ from arguments in a function call?
Answer:Parameters describe what inputs a function can accept. Arguments are the actual values passed to the function when it is called.
Question:How does strip() change a string when applied to user input?
Answer:It removes whitespace from the left and right ends of the string, but not from between its characters.
Question:How can split() separate a full name into two variables?
Answer:Call name.split(" ") to split at a space, then assign the returned values to two variables, such as first, last.
Question:Why can adding two values from input() produce concatenated text instead of a numeric sum?
Answer:input() returns user input as a string. Convert numeric input with int() before addition to perform integer arithmetic.
Question:How does a Python function use a parameter with a default value?
Answer:The parameter receives its default value when the function is called without an argument. Supplying an argument uses that value instead.
Question:Why must a value be passed into hello when name is local to main?
Answer:A variable exists only within the scope where it is defined. Passing its value as an argument makes it available to the called function, where the parameter may have a different name.
Question:How does return change a function’s result compared with printing?
Answer:Printing displays output as a side effect. return explicitly hands a value back, allowing the caller to pass it to another function or use it in further computation.
Question:How do if, elif, and else reduce unnecessary conditional checks?
Answer:if tests the first condition; elif tests another only when earlier conditions are false. else handles the remaining case without testing another condition. This mutually exclusive structure stops checking once a true branch is reached.
Question:How can a function determine whether an integer is even using modulo?
Answer:Test whether n % 2 == 0. The modulo operator gives the remainder, and a zero remainder means the integer divides evenly by two; the comparison evaluates to a Boolean value.
Question:How does Python’s match statement group several values into one case?
Answer:Separate the alternatives with vertical bars (|) in a single case, such as case "Harry" | "Hermione" | "Ron".
Question:Why can a while loop run indefinitely, and how can a counter prevent this?
Answer:If the loop condition remains true because its variables never change, the loop continues indefinitely. Update the counter so it eventually makes the condition false.
Question:How does a for loop use range(n) to repeat an action?
Answer:It iterates over values from zero up to, but not including, n, repeating the indented action once for each value.
Question:How does a Python for-loop iterate over a dictionary by default?
Answer:It iterates over the dictionary’s keys. Each loop iteration assigns the next key to the loop variable.
Question:How do nested loops generate a two-dimensional square of characters?
Answer:The outer loop processes each row. For every row, the inner loop prints the characters across it; a newline after the inner loop moves output to the next row.
Question:How should a program handle invalid integer input with exceptions?
Answer:Place the integer conversion in a try block and handle a ValueError in an except block. Keep the try block limited to the operation that can raise that exception.
Question:Why can a NameError occur after int(input(...)) raises a ValueError?
Answer:The conversion fails before the assignment completes, so no value is assigned to the variable. Code that later uses that variable can therefore raise a NameError.
Question:How does random.choice support a simulated coin toss?
Answer:It selects one element from a sequence at random. Choosing between a two-element list of heads and tails gives each outcome a 50% probability.
Question:How do command-line arguments provide input to a program?
Answer:They are words, numbers, or phrases entered after the command when the program is executed. The program receives them as input without prompting separately through input().
Question:How does Python’s sys.argv represent command-line input?
Answer:It is a list containing the program’s filename at index 0, followed by the words supplied at the command line.
Question:How can a program prevent invalid sys.argv indexing when a required argument is missing?
Answer:Check the length of sys.argv before indexing it. If the argument count is invalid, report the problem and use sys.exit to stop execution.
Question:How does Python retrieve and use data from a web API in the demonstrated example?
Answer:The requests package sends an HTTP request, and the response’s JSON can be accessed as Python data. The example iterates through the results list and prints each item’s trackName.
Question:Why should a Python module guard its main call with if name == "main"?
Answer:The guarded call runs when the file is executed directly, but not when the file is imported. This prevents importing a function from unintentionally running the module’s main program.
Question:How can representative test inputs expose a bug that one passing example misses?
Answer:Different inputs can reveal cases where incorrect behavior coincidentally matches the expected result. For example, replacing multiplication with addition still gives the correct square for 2 and 0, but fails for 3 and negative inputs.
Question:Why should a testable function return a value rather than only print it?
Answer:Assertions compare function return values with expected values. A function that only prints has a side effect instead, so its output cannot be tested by directly comparing its return value.
Question:How can a loop test several inputs within one pytest function?
Answer:Loop over the inputs and assert the expected result for each one. The loop remains part of a single test function.
Question:How do Python file modes w and a differ when writing?
Answer:w creates or recreates the file, replacing its existing contents. a adds new content to the end of the file.
Question:How does with open(...) as file manage a file?
Answer:It assigns the opened file to file and automatically closes it when execution leaves the with block.
Question:How does sorted() use its key parameter to order dictionaries?
Answer:It calls the supplied function on each dictionary and sorts using the returned values. Pass the function by name, without parentheses.
Question:Why can splitting CSV rows directly on commas fail when a field contains a comma?
Answer:The split treats a comma inside a field as a column separator, producing too many values to unpack. The csv module’s reader handles quoting and parsing.
Question:How does csv.DictReader make CSV-reading code more robust to column reordering?
Answer:It uses the header row as column names and returns each row as a dictionary. Code can access values by names such as name or home rather than fixed column positions.
Question:How do * and + differ when quantifying a regular-expression pattern?
Answer:* matches zero or more repetitions. + requires one or more repetitions.
Question:How do ^ and $ constrain a regular-expression match?
Answer:^ anchors the match to the start of the string. $ anchors it to the end of the string.
Question:How can a regular expression distinguish a literal period from any character?
Answer:Use \. to match a literal period. An unescaped . matches any character except a newline.
Question:How does the re.IGNORECASE flag affect a regular-expression search?
Answer:It makes the match case-insensitive without changing the original input string.
Question:How can a regular expression make an entire subdomain optional?
Answer:Group the subdomain and its literal dot in parentheses, then place ? after the group. The question mark allows the group to appear zero or one time.
Question:How does re.search return specific parts of a matched string?
Answer:Parentheses create capturing groups. The match object provides captured values through numbered groups, beginning with group 1.
Question:Why should a complex regular expression be developed incrementally?
Answer:Build a simple pattern, verify that it works, then add one feature at a time and test again. This makes mistakes easier to locate and helps ensure each step is correct.
Question:How does a non-capturing group differ from a capturing group in regular expressions?
Answer:Both groups can organize pattern elements, such as making a subpattern optional. A capturing group stores its match for extraction; a non-capturing group, written with (?:...), does not.
Question:How do tuples, lists, and dictionaries differ when storing student data?
Answer:A tuple is immutable and uses numeric indices. A list is mutable and uses numeric indices. A dictionary is mutable and uses keys, such as name and house, to access values.
Question:How does calling Student(name, house) initialize a new student object?
Answer:The class call constructs a Student object and automatically invokes init. The method receives the object as self, then stores the supplied values in instance variables such as self.name and self.house.
Question:How can a class reject invalid student data during initialization?
Answer:Check the values in init and use raise ValueError(...) when they are invalid. For example, reject a blank name or a house outside Gryffindor, Hufflepuff, Ravenclaw, and Slytherin. A caller can handle the exception with try and except.
Question:How do Python’s new and init methods differ?
Answer:new creates an empty object in memory. init initializes that object’s contents. Python generally handles new automatically, while programmers commonly define init.
Question:How does a Python property setter validate attribute assignments?
Answer:Assigning through the property calls its setter, which can validate the value and raise a ValueError for invalid input. Assignments in init also pass through the setter when they use the property name.
Question:What does a leading underscore on a Python instance variable indicate?
Answer:It is a convention asking other programmers to treat the variable as private. It does not prevent access or changes; Python relies on an honor system rather than enforcing visibility.
Question:When can a class method replace an instance method in Python?
Answer:Use a class method when the operation belongs to the class rather than a particular object, so no instance needs to be created first. The method receives the class reference, conventionally named cls, and can access class variables.
Question:How does inheritance reduce duplicated code in related Python classes?
Answer:A subclass inherits shared attributes and methods from a superclass. For example, Student and Professor can inherit common name validation and assignment from Wizard while retaining their own class-specific attributes.
Question:How does Python use add to define addition between two vault objects?
Answer:When + is used, Python calls the left operand’s add method, passing the right operand as other. The method can add corresponding coin counts and return a new Vault object containing the totals.
Question:How does Python distinguish reading a global variable from modifying it inside a function?
Answer:A function can read a global variable directly. To modify it, the function must declare it with the global keyword; otherwise, an assignment treats the name as local and can cause an UnboundLocalError.
Question:How does a read-only property restrict changes to an account balance?
Answer:A getter lets code read the balance through property syntax. Without a setter, code cannot assign a new balance through that property.
Question:How can type hints and mypy help prevent Python type errors?
Answer:Type hints annotate the intended types of variables, arguments, and return values, but Python does not enforce them at runtime. Mypy checks code against those hints and can flag incompatible types before the program runs.
Question:How does argparse simplify handling command-line options in Python?
Answer:It parses command-line arguments and makes their values accessible through an argument object. Options can have help descriptions, defaults, and specified types, reducing the need to parse arguments manually.
Question:How does a single asterisk unpack a sequence into function arguments?
Answer:It passes each sequence element as a separate positional argument, in order. The sequence length must match the function’s required positional arguments unless defaults apply.
Question:How does a double asterisk unpack a dictionary into function arguments?
Answer:It passes dictionary keys and values as named arguments. Each key must match a parameter name accepted by the function.
Question:How do map and filter differ when processing a sequence?
Answer:map applies a function to each element and produces a result for each one. filter applies a function that returns true or false and retains elements for which it returns true.
Question:How does Python’s enumerate simplify indexed iteration over a sequence?
Answer:It provides the current index and the corresponding value together, so a loop need not separately use range, len, and list indexing.
Question:Why can returning a large list at once cause a program to fail?
Answer:The program must build and hold the entire collection in memory before returning it; sufficiently large collections can exceed available memory or computing capacity.
Question:How does yield change value production inside a Python loop?
Answer:It produces one value at a time and suspends the generator while retaining its state. Iteration can then resume to produce the next value instead of building and returning the entire collection at once.