Here we will have a look at how you control which of the Python statements that are evaluated in your code using True/False tests. We will also look at functions, how you make use of them and even how you can make your own ones.
This page contains both some explanation of the topics we cover and some exercises for you to do. Read through the page and complete the exercises at the end. Spend any remaining time playing around on the code examples in the explanatory text. Remember that the key here is learning by doing. Type some of the code examples into your IDLE editor and try them out yourself — and be curious. Try and see what happens if you change things a bit.
if and else:
Writing else after an if statement is just a convenient way of specifying the opposite of some test. In other words: this
x = 2 y = 5 if x > y: print "x is larger" if x <= y: print "x the same or smaller" print x
is equivalent to this:
x = 2 y = 5 if x > y: print "x is larger" else: print "x the same or smaller" print x
Remember to indent the code that is controlled by the if and else statements. Try and indent the last line like this and see what happens:
if x > y: print "x is larger" else: print "x the same or smaller" print x
while loops
If we want to decrement a variable x from 6 to 3 by subtracting one at a time we can write a series of if statements like this:
x = 6 if x > 3: print "x is larger than three" x = x - 1 if x > 3: print "x is larger than three" x = x - 1 if x > 3: print "x is larger than three" x = x - 1 if x == 3: print "x is now 3"
Here we knew that we had to decrement x three times so we checked the value three times and decremented it once each time. But what if we did not know the starting value of x when we had to write the code? Then we did not know how many if statements to put in. Luckily we have the while statement. This is a convenient way to pack many identical if statements together. Using a while statement we can write the above code like this:
x = 6 while x > 3: print "decrementing x" x = x - 1 if x == 3: print "x is now 3"
So as long as x > 3 the program will keep looping over the block of code under the while statement. The cool thing is that you do not need to know how many loops you are going to need in advance. Try it out with different starting values of x. What happens if you set x to 2?
A problem with while loops you are bound to run into is exemplified by the following snippet:
x = 7 while x > 3: print "x is still larger than 3"
What is happening?
Boolean expressions
A boolean expression is an expression that evaluates into True or False. You already know them from the tests you make in if-statements. Examples of boolean expressions are x > y and x == 0. Python will treat anything you write after the if, elif or while keywords as boolean expressions even if they are just single values or single variables. The values True, 1, 42, and -8, as well as variables with those values, all evaluate to True. To see if an expression evaluates to True or False use the built-in function bool() in the interactive Python shell.
>>> bool(True) True >>> bool(-8) True >>> bool(0) False >>> bool(0 == 0) True
You can combine boolean expressions with the logical operators and and or and use not to turn something True in to False and the other way around.
>>> bool(True or False) True >>> bool(True and False) False >> bool(True and not False) True
Remember the precedence rules for these operators. not "sticks" more than and, which again "sticks" more than or, but you can always put parentheses in to force the behaviour you want.
for loops
for loops lets you run a block of code a certain number of times by looping over the values in a list:
n = 4 for i in range(n): print i
As you can see each time the block of code is executed the variable after for (here i) gets a new value. But what is the range(n) thing? This brings us straight to the topic of functions:
Built-in Functions
Functions work pretty much the way you are used to them from math. The notation is the same as we typically use in mathematics, anyway. To call a function, f, with the value x, we write f(x).
Simple, right?
Python has a lot functions built in to make your life easier. range() is one of these. What do you think it does? Try this out:
print range(4) print range(2, 5)
There are plenty more. You will get acquainted with them over time but here are some of them to try out:
max(7, 3) abs(-3) pow(2, 4)
What do you think they do?
Getting documentation for functions
Memorizing all the functions you have available, and exactly what they do and how they are used, is tedious at best. Luckily there is a helpful function for finding such things out in the interactive shell itself.
The function dir() gives you a list of all variables and functions currently defined — try calling it as just dir() in the shell — and the function help() will give you a short text describing how the function is supposed to be used. The function displays the help text, and you need to press "q" to return to the prompt again.
For now, try "help(range)". The function range() we used above, but I never explained to you what it did. Now you can read the documentation and see for yourself. You should also try out what you learn from the documentation to make sure you understand it.
Defining your own functions
Functions are very powerful and can do a lot more than what I will describe to you now, but we will see all that later in the class. For now, we will just see how to define a function that evaluates simple expressions.
def square(x): s = x**2 return s
Don't forget to write "return" before the expression you want the function to return. If you do this, Python will happily calculate the expression, but the function will return the special value None rather than the value you want it to return.
You can define functions with more than one parameter. To do that, you just write more than one variable name between the parenthesis in the function definition, like this:
def squareAndAdd(x,y): r = x**2 + y return r
Exercises
Boolean expressions
Add parentheses to the following boolean expression to make it evaluate to True.
not False and False
Add parentheses to the following boolean expression to make it evaluate to False.
True or True and False
Functions for geometrical calculations
In these exercises you will need the constant pi. It is defined in the math module and you can import by writing this at the top of your file:
from math import *
Write separate functions sphereArea(x) and spereVolume(x) that calculate the surface area and volume of a sphere. The argument x is the radius of the sphere. You can sneak a peak on the this formula sheet for the formulas. Example usage:
area = sphereArea(7) volume = sphereVolume(7)
Write a function sphereMetrics(x) that calculates both area and volume by using the functions sphereArea(x) and sphereVolume(x). Example usage:
area, volume = sphereMetrics(7)
Write a function circleArea(x) that calculates the area of circle. The argument x is the radius.
area = circleArea(7)
Write a function squareArea(x) that calculates the area of square. The argument x is the length of one edge. Example usage:
area = squareArea(7)