Section 4
Section 4
Loops
If Statement
• condition operators can be used in several ways, most
commonly in
Short Hand If
• Used when you have only one statement to execute.
Elif
• if the previous conditions were not true, then try this
condition.
Else
• The else keyword catches anything which isn't caught by the
preceding conditions.
Short Hand If ... Else
If you have only one statement to execute, one for if, and
one for else, you can put it all on the same line.
pass Statement
if statements cannot be empty, but if you for some reason
have an if statement with no content, put in
the pass statement to avoid getting an error.
Loops
• python has two type of loop:
1. while loop
2. for loop
While Loop
break Statement
With the break statement we can stop the loop even if the
while condition is true.
continue Statement
• With the for loop we can execute a set of statements, once for
each item in a list, tuple, set etc.
Nested Loops
• A nested loop is a loop inside a loop.
• The "inner loop" will be executed one time for each iteration
of the "outer loop"
Range() Function
• To loop through a set of code a specified number of times, we
can use the range() function,
• The range() function returns a sequence of numbers, starting
from 0 by default, and increments by 1 (by default), and ends
at a specified number.
• Extras:
- Ask the user for two numbers: one number to check (call
it num) and one number to divide by (check). If check divides
evenly into num, tell that to the user. If not, print a different
appropriate message.
Take a list, say for example this one:
and write a program that prints out all the elements of the
list that are less than 5.
Create a program that asks the user for a number and then
prints out a list of all the divisors of that number. (If you don’t
know what a divisor is, it is a number that divides evenly into
another number. For example, 13 is a divisor of 26 because 26
/ 13 have no remainder.)
Any Question…?