Solving problems with Python

From AstroEd

Revision as of 04:53, 14 February 2013 by WikiSysop (talk | contribs) (Functions)

Now with many useful tools in hand, let us see how to make them work together to solve problems.

Flow control

The if statement is fundamental to making decisions within a program. It works simply

if x > 0.:
  y = 1./x
elif x < -1.:
elif x == 0:
  print 'Cannot divide by zero.'
  y = 1./x
z = y

Notice that indentation (by any fixed number of spaces) is used to separate the functions within the statement, and that each branch is defined by a :. The end of a branch occurs when the indentation goes back to the previous level. Each decision is based on a logical boolean value such as (x > 0.), which is True when x is greater than 0. and False otherwise. Within the if processing, a break is a way to get out of that level without doing anything, and an exit() leaves the entire program.

A while statement tests whether its argument is true, and sets up a loop that continues as long as it is. Program

flag = True
x = 0.
while flag:
  x = x + 1.
  if x > 10.:
    flag = False
print x

increases x until it is 11. and then prints the value.

Loops such as this may include a try block. This enables handling an exception, such as in this program to calculate x2 with input from keyboard.

while True:
    x = int(raw_input("Please enter a number: "))
  except ValueError:
  print "Oops!  That was no valid number.  Try again..."
print y

Here a break exits the loop from the try block unless an exception is thrown. A while statement can also test for something that is changed in the loop.


Within a Python program you can define your own functions. Here's one to take an angle in degrees and reduce it an angle between 0 and 360.

def map360(angle):
  if (angle < 0.0):   
    n = int(angle / 360.0) - 1
    return (angle - float(n) * 360.0)
  elif (angle >= 360.0):  
    n = int(angle / 360.0)
    return (angle - float(n) * 360.0)
    return (angle)

Functions may have any number of objects as arguments, of any data type. Once defined, you may use a function anywhere in a program.



For examples of Python illustrating flow control, functions, and iteration, see the examples section.


For the assigned homework to use these ideas, see the assignments section.