Statements
This part will cover the following topics:
loop statements
for
loopwhile
loop
conditional statements
if
,elif
, andelse
statements
break and continue statements
break
continue
assert statement
assert
Loop statements
for
loop
for
loopThe for
loop is used to iterate over a sequence (list, tuple, string, etc.) or other iterable objects.
range()
function is normally used with the for
loop to iterate over a sequence of numbers.
while
loop
while
loopThe while
loop is used to execute a block of code as long as the condition is true.
To create an infinite loop, you can use while True
.
hint: To stop the infinite loop, press Ctrl + C
(Windows) or Cmd + C
(Mac).
Conditional statements
if
, elif
, and else
statements
if
, elif
, and else
statementsThe if
statement is used to execute a block of code if the condition is true.
The elif
statement is used to check multiple expressions for True
and execute a block of code as soon as one of the conditions is true.
The else
statement is used to execute a block of code if the condition is false.
Q: What is the difference between elif
and else
?
Break and continue statements
break
break
The break
statement is used to exit the loop.
In this example, the loop will stop when the element is equal to 3.
continue
continue
The continue
statement is used to skip the current iteration and continue with the next iteration.
In this example, when the element is equal to 3, the loop will skip the current iteration and continue with the next iteration.
Assert statement
The assert
statement is used to check if the condition is True
. If the condition is False
, the program will raise an AssertionError
. The assert
statement is used for debugging code.
In this example, the program will raise an AssertionError
because the score is less than 60. The message will be displayed as follows:
Last updated