if
, while
, and for
statements
if
statement
A conditional statement is what we use when we want our code to make decisions. For example, suppose we wanted to divide a number by 2 only if it is even. We can do this in Sage by using an if
statement. The general syntax for Python's if-else
statement is
if <condition>:
<statement>
:
else:
<statement>
:
<condition>
is an expression that can use relational operators <
, >
, <=
, >=
, ==
(is equal), and !=
(is not equal), as well as logical operators: and
, or
, not
. Its value is either True
or False
. If the condition is True
, the statements indented under if
are executed, otherwise the statements under else
are executed. The else
clause is optional: you can have if
alone. In that case, if the condition is True
the program executes the statements indented under if
, otherwise the program skips them.
Output:
n is divisible by 3
Often you'll need to string a chain of several if-else
statements together. For example
def letterGrade(score):
if score >= 90:
return 'A'
else:
if score >= 80:
return 'B'
else:
if score >= 70:
return 'C'
else:
if score >= 60:
return 'D'
else:
return 'F'
Python lets you simplify the indentation and compress the if-else
on one line by using the keyword elif
. The above code can be shortened to
def letterGrade(score):
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif score >= 60:
return 'D'
else:
return 'F'
while
loop
while
loops are one of the most useful techniques in programming. Essentially, a while
loop allows us to repeat the same block of statements multiple times (but with different values of variables) while a certain condition holds true.
The general syntax for Python's while
loop is
while <condition>:
<statement>
:
As long as the condition remains true the program repeats the statements in the while
block.
The next example uses a while
loop to add the integers from 1 to 10.
i = 1
sum1ton = 0
while i <= 10:
sum1ton += i # equivalent to sum1ton = sum1ton + i
i += 1 # increments i by 1
sum1ton
Output:
55
for
loop
for
loops are traditionally used when you have a block of code which you want to repeat a fixed number of times. In Python, for
loops iterate over a fixed list. As an alternative, the while
loop could be used, however, while
is used when a condition is to be met, or if you want a block of code to theoretically repeat forever, for example repeatedly asking for user input until the format the user provides is correct. The general syntax for Python's for
loop is
for x in <list>:
<statement>
:
Here is an example of using the for
loop to step through the entries of a list and square each one.
Output:
1
4
9
16
25
In the next example we use a for
loop together with an if
statement to print the list of integers from 1 to 20 which are divisible by 3.
Output:
3
6
9
12
15
18
This has been a quick introduction to get up and running with python.