Core Python / Control Statements#
What is the type and value of x?
int 10
Use type(x) and print(x) to verify.
or
returns the actual value of the first “true” expression. Forand
if the clause evaluates toTrue
, the last expression evaluated is returned.Why is the order of
if
andelif
clauses important?The Python interpreter evaluates the clauses in their listed order. Only the code block associated with the first clause that evaluates to true executes.
Explain short-circuit evaluation for
and
andor
clauses.Once the Python interpreter can determine the outcome of a Boolean expression, the interpreter no longer needs to continue evaluation.
For
and
, if the first expression evaluates toFalse
, the second expression will not be evaluated as the result of the operator will always beFalse
.For
or
, if the first expression evaluates toTrue
, the second expression will not be evaluated as the result of the operator will always beTrue
.How are code blocks identified in Python?
Indention. This indention must be consistent throughout the source code file. Other programming languages often use curly braces.
What is the difference between
if/elif
statement(s) and a series ofif
statements?With
if/elif
statements, only the code block associated with the first clause that evaluates toTrue
executes. With a series ofif
statements, each code block associated with aTrue
clause will evaluate.Why is testing for equality with float numbers problematic? How do we work around such situations?
Floating-point numbers do not have an exact representation. As such certain calculations may not produce the exact answer expected. Use the
math.isclose()
instead of the equality operator.