# Difference between revisions of "Solving problems with Python"

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 do nothing, 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:
try:
x = int(raw_input("Please enter a number: "))
break
except ValueError:
print "Oops!  That was no valid number.  Try again..."
y=x**2
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.

## Functions

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)

else:
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.

## Iteration

The while loop makes repeated passes through a block of code as long as a test condition is satisfied. This allows us to make sequential changes to achieve a desired outcome, such as evaluating a series until the error is acceptable, or fitting data until the fitting errors are minimized. Python also has several built-in ways to manage interation, and the most useful is the for loop.

```idata = range(10)
print idata
fdata = [-1.]
for x in idata:
f = float(x)**2.
fdata.append(f)
print fdata
```

generates this output

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [-1.0, 0.0] [-1.0, 0.0, 1.0] [-1.0, 0.0, 1.0, 4.0] [-1.0, 0.0, 1.0, 4.0, 9.0] [-1.0, 0.0, 1.0, 4.0, 9.0, 16.0] [-1.0, 0.0, 1.0, 4.0, 9.0, 16.0, 25.0] [-1.0, 0.0, 1.0, 4.0, 9.0, 16.0, 25.0, 36.0] [-1.0, 0.0, 1.0, 4.0, 9.0, 16.0, 25.0, 36.0, 49.0] [-1.0, 0.0, 1.0, 4.0, 9.0, 16.0, 25.0, 36.0, 49.0, 64.0] [-1.0, 0.0, 1.0, 4.0, 9.0, 16.0, 25.0, 36.0, 49.0, 64.0, 81.0]

## 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.
{"ft_lang_label":"__label__en","ft_lang_prob":0.81794846,"math_prob":0.99212253,"size":4258,"snap":"2020-34-2020-40","text_gpt3_token_len":1601,"char_repetition_ratio":0.16126,"word_repetition_ratio":0.25382653,"special_character_ratio":0.41803664,"punctuation_ratio":0.28444803,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.989107,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-08-03T08:46:41Z\",\"WARC-Record-ID\":\"<urn:uuid:fcf6ae09-3ac2-42e1-a74b-30eb6526600b>\",\"Content-Length\":\"26927\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:b7512172-2344-4ae2-ac01-11a3ebcfb68e>\",\"WARC-Concurrent-To\":\"<urn:uuid:f89ad8ae-edcd-45d7-ad20-bb02bc01ceda>\",\"WARC-IP-Address\":\"136.165.82.9\",\"WARC-Target-URI\":\"http://physics.louisville.edu/astrowiki/index.php?title=Solving_problems_with_Python&diff=prev&oldid=1576\",\"WARC-Payload-Digest\":\"sha1:YPJSPMFVGII6P3XEKYZTWJMZQPVL5KCT\",\"WARC-Block-Digest\":\"sha1:VLMLFW7BOTQAKHAWXOLZIMVSYMXKYVG5\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-34/CC-MAIN-2020-34_segments_1596439735792.85_warc_CC-MAIN-20200803083123-20200803113123-00169.warc.gz\"}"}