# Difference between revisions of "Solving problems with Python"

Line 22: | Line 22: | ||

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 ''pass'' is a | 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 ''pass'' is a | ||

way to get out of that level without doing anything, and an exit() leaves the entire program. | 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. | ||

+ | |||

+ | |||

+ | |||

+ | |||

+ | |||

== Functions == | == Functions == |

## Revision as of 04:09, 14 February 2013

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

x=0.1 y=10. z=0. if x > 0.: y = 1./x elif x < -1.: pass elif x == 0: print 'Cannot divide by zero.' exit() else: 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 *pass* 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.

## Functions

## Iteration

## Examples

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

## Assignments

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