Python: Operators, Truthiness, Exceptions & more
24 Questions
3 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

Consider the following Python code: x = 5. What is the fundamental distinction between using = and ==?

  • Both `=` and `==` perform assignment, but `==` also checks for data type.
  • Both `=` and `==` perform equality comparison, but `==` returns a boolean.
  • `=` performs equality comparison, while `==` assigns a value.
  • `=` assigns a value, while `==` performs equality comparison. (correct)

Given Python's concept of truthiness and falsiness, what is the combined output of the following expressions: bool(""), bool(0), bool([])?

  • False, True, False
  • False, False, False (correct)
  • True, False, True
  • True, True, True

What is the consequence of attempting to directly modify a string object in Python?

  • Python raises a TypeError exception due to the immutability of strings. (correct)
  • The string is modified in place, and the original string object is updated.
  • The program continues without error, but the modifications are not applied.
  • A new string object is created with the modifications, and the original variable now points to this new object.

When calling the int() function, what exception will be raised if it receives a string that can't be parsed to an integer?

<p><code>ValueError</code> (C)</p> Signup and view all the answers

What does the id() function return in Python, and what guarantees does it provide?

<p>A unique integer representing the object, guaranteed to be unique only for the object's lifetime. (B)</p> Signup and view all the answers

Examine the following code: x = 10 \n y = "5" \n z = x + y. What behavior can we expect and why?

<p>The code will raise a TypeError because Python does not allow implicit addition of integers and strings. (D)</p> Signup and view all the answers

Considering the following code, what will be the output?

x = 5
if x > 10:
 print("Greater than 10")
elif x > 5:
 print("Greater than 5")
else:
 print("Less than or equal to 5")

<p>&quot;Less than or equal to 5&quot; (A)</p> Signup and view all the answers

If a Python program attempts to open a file for reading that does not exist, which exception is raised?

<p>FileNotFoundError (B)</p> Signup and view all the answers

What is the primary use of the id() function in Python?

<p>To understand object identity by returning a unique integer identifier for each object. (D)</p> Signup and view all the answers

Given the expression 15 // 4 + 15 / 4, what is the resulting data type and value in Python?

<p>Float, 6.75 (C)</p> Signup and view all the answers

Evaluate the Python expression: not (True and False) or (True and not False)

<p>True (C)</p> Signup and view all the answers

How do logical operators in Python handle operands that are not explicitly Boolean values?

<p>They treat the operands as their truthy or falsy equivalents, as determined by Python's truthiness rules. (B)</p> Signup and view all the answers

In Python, how does the evaluation of conditions differ between an if-elif-else structure and a series of independent if statements when multiple conditions could potentially be true?

<p>In <code>if-elif-else</code>, only the first <code>True</code> condition's block is executed, and subsequent conditions are skipped; in multiple <code>if</code> statements, all <code>True</code> conditions' blocks are executed. (A)</p> Signup and view all the answers

What is the significance of short-circuit evaluation in Python's and and or operators?

<p>It allows Python to skip evaluating conditions once the outcome of the expression is known, potentially improving performance and preventing errors. (A)</p> Signup and view all the answers

Consider the following Python code: result = 'High' if score > 90 else 'Mid' if score > 70 else 'Low'. Under what circumstances would the result variable be assigned the value 'Mid' using this ternary operator?

<p>When <code>score</code> is greater than 70, but not greater than 90. (C)</p> Signup and view all the answers

Given the nested if statements structure below, under what condition will the code print "Condition C is met"?

if condition_a:
    if condition_b:
        if condition_c:
            print("Condition C is met")

<p>When <code>condition_a</code>, <code>condition_b</code>, and <code>condition_c</code> are all true. (B)</p> Signup and view all the answers

Consider the following Python code:

x = 5
y = 0
result = (x > 3) or (y / x > 0)

What is the value of result and why?

<p><code>True</code>, because the first condition <code>(x &gt; 3)</code> is True and short-circuit evaluation prevents division by zero. (A)</p> Signup and view all the answers

In Python, how does the behavior of the and operator change when the first operand is falsy?

<p>It immediately returns the first operand without evaluating the second one. (B)</p> Signup and view all the answers

In Python, which of the following methods is the most concise and Pythonic way to determine if a variable x falls within the inclusive range of 10 to 20, assuming x is an integer?

<pre><code class="language-python">if 10 &lt;= x &lt;= 20: # Code here ``` (B) </code></pre> Signup and view all the answers

Given that x = [1, 2, 3] and y = [1, 2, 3], how do id(x) and id(y) relate, and what does this imply about x and y?

<p><code>id(x)</code> and <code>id(y)</code> are different, indicating that <code>x</code> and <code>y</code> are distinct objects with the same values. (B)</p> Signup and view all the answers

Given that Python stops evaluating conditions in a compound Boolean expression as soon as the result is known, what is this behavior commonly referred to as, and how does it optimize code execution?

<p>Short-circuit evaluation; it avoids unnecessary computations by skipping the evaluation of the remaining expressions once the overall outcome is determined. (C)</p> Signup and view all the answers

In Python, the statement if not 0: evaluates to True. Based on this behavior, how would Python interpret if not ' ': and why?

<p>Evaluates to <code>False</code> because any non-empty string, including one containing a space, is considered truthy. (C)</p> Signup and view all the answers

Consider the following Python code snippet:

x = -5
if x > 0:
    print("Positive")
elif x < -10:
    print("Negative and very small")
else:
    print("Non-positive or close to zero")

What will be the output of this code, and why?

<p>&quot;Non-positive or close to zero&quot;, because neither <code>x &gt; 0</code> nor <code>x &lt; -10</code> is true. (A)</p> Signup and view all the answers

What distinguishes the ternary operator in Python from a traditional if-else statement, and in what scenarios might its use be most appropriate?

<p>The ternary operator is an expression that returns a value and must be used in an assignment, while an <code>if-else</code> statement is for executing blocks of code; suitable for simple conditional assignments. (C)</p> Signup and view all the answers

Flashcards

What does = do?

Used to assign a value to a variable (e.g., x = 5).

What does == do?

Used to check if two values are equal (e.g., 5 == 5 is True).

What are Falsy values?

Values that evaluate to False when converted to boolean. Examples: None, False, 0, "", [], {}, set().

Are Python strings mutable?

Strings in Python are immutable, meaning they cannot be changed after creation. "Modification" creates a new string.

Signup and view all the flashcards

String to Integer?

Use the int() function to convert a string to an integer. Example: int("123").

Signup and view all the flashcards

What does id() do?

Returns a unique identifier (memory address) of an object. This ID is constant during the object's lifetime.

Signup and view all the flashcards

What is an Exception?

An error that occurs during the execution of a program, disrupting the normal flow.

Signup and view all the flashcards

Exception Handling

A block of code used to gracefully handle exceptions, preventing program termination. Uses try and except blocks.

Signup and view all the flashcards

Difference between // and /?

// performs integer division, rounding down to the nearest whole number. / performs true division, returning a float.

Signup and view all the flashcards

Result of not True or False and True?

The expression evaluates as follows: not True is False. False and True is False. False or False is False.

Signup and view all the flashcards

Python's logical operators

and: Returns True if both conditions are True. or: Returns True if at least one condition is True. not: Inverts the Boolean value.

Signup and view all the flashcards

Short-circuit Evaluation

Stops evaluating conditions as soon as the result is known. For and, it stops at the first False. For or, it stops at the first True.

Signup and view all the flashcards

Short-circuit evaluation with and

With 'and' if the first condition is false, the second condition is not evaluated.

Signup and view all the flashcards

Short-circuit evaluation with or

With 'or' if the first condition is true, the second condition is not evaluated.

Signup and view all the flashcards

if not 0: in Python

In Python, if not 0: evaluates to True because 0 represents a falsy value, and not inverts the Boolean value.

Signup and view all the flashcards

if-elif-else vs. multiple if

if-elif-else evaluates mutually exclusive conditions. Multiple if statements evaluate independent conditions.

Signup and view all the flashcards

Ternary Operator

A shorthand for if-else statements: value_if_true if condition else value_if_false

Signup and view all the flashcards

Nested if statements

If statements can be nested inside other if statements to create more complex condition checks.

Signup and view all the flashcards

Check if variable within range

Use and to combine two conditions (e.g., if 10 < x < 20:).

Signup and view all the flashcards

Output of ternary operator

It will print 'Positive', because x > 0 is True.

Signup and view all the flashcards

The pass statement

The pass statement is a null operation; nothing happens when it executes. Used as a placeholder.

Signup and view all the flashcards

More Like This

Use Quizgecko on...
Browser
Browser