u02-slides-conditions-loops-flashcards
What are the three main logical operations in Python?
not, or, and
What is short-circuit evaluation in Python?
For ‘or’, if first expression is True, second is skipped. For ‘and’, if first is False, second is skipped.
What objects are interpreted as False in Python?
The special value None, the value 0 of all numeric types, and empty sequences
What is the purpose of assertions in Python?
To implement sanity checks that raise an error if a condition evaluates to False - useful for debugging
How can assertions be disabled in Python?
By running Python with the -O option (python -O …)
What are the main branching statements in Python?
if, elif, and else statements
How is code within branches assigned in Python?
Through indentation (typically 4 spaces) rather than braces
What is pattern matching in Python?
A feature introduced in Python 3.10 that allows structural pattern matching using the match statement
What are the two main types of loops in Python?
while loops and for loops
What is the difference between while and for loops?
while loops repeat based on a condition being True, for loops iterate over elements in an iterable
What are common use cases for while loops?
Asking for input until correct, running main routines until stopped, optimization until convergence
What is a potential danger with while loops?
They can lead to endless/infinite loops if the condition is never False
What is an iterable in Python?
A sequence of elements that can be iterated over (e.g., strings, data structures)
What keywords can manually control loop execution?
break (to exit the loop) and continue (to jump to next iteration)
Why should manual loop control keywords be used sparingly?
They break the normal control flow of the program by creating sudden jumps in code
How do you write a chained comparison in Python?
You can chain operators, e.g., 3 < 4 < 5
What happens if there’s no else statement in an if-elif chain?
No branch might be executed at all
What’s the syntax for adding a message to an assertion?
assert condition, “message”
When should assertions not be used?
For general error/exception handling (since users can disable them)
How do you write a for loop to iterate over a string?
“for char in my_string:”
What is the typical indentation size in Python?
4 spaces
How are multiple conditions evaluated in if-elif-else chains?
From top to bottom
What is the default case in pattern matching called?
The underscore (_) case
What happens to code after a break or continue statement?
It is ignored within that loop iteration