Monday, 6 March 2017

Advanced Functions - python (part 7)

Advanced Functions Example 

Some people find this section useful, and some find it confusing. If you find it confusing you can skip it (or just look at the examples.) Now we will do a walk through for the following program:
def mult(a, b):
    if b == 0:
        return 0
    rest = mult(a, b - 1)
    value = a + rest
    return value
print "3 * 2 = ", mult(3, 2)
Output
Basically this program creates a positive integer multiplication function (that is far slower than the built in multiplication function) and then demonstrates this function with a use of the function. This program demonstrates the use of recursion, that is a form of iteration (repetition) in which there is a function that repeatedly calls itself until an exit condition is satisfied. It uses repeated additions to give the same result as mutiplication: e.g. 3 + 3 (addition) gives the same result as 3 * 2 (multiplication).
RUN 1
Question: What is the first thing the program does?
Answer: The first thing done is the function mult is defined with all the lines except the last one.
function mult defined
This creates a function that takes two parameters and returns a value when it is done. Later this function can be run.
What happens next?
The next line after the function, print "3 * 2 = ", mult(3, 2) is run.
And what does this do?
It prints 3 * 2 = and the return value of mult(3, 2)
And what does mult(3, 2) return?
We need to do a walkthrough of the mult function to find out.
RUN 2
What happens next?
The variable a gets the value 3 assigned to it and the variable b gets the value 2 assigned to it.
And then?
The line if b == 0: is run. Since b has the value 2 this is false so the line return 0 is skipped.
And what then?
The line rest = mult(a, b - 1) is run. This line sets the local variable rest to the value of mult(a, b - 1). The value of a is 3 and the value of b is 2 so the function call is mult(3,1)
So what is the value of mult(3, 1) ?
We will need to run the function mult with the parameters 3 and 1.
RUN 2

RUN 3
So what happens next?
The local variables in the new run of the function are set so that a has the value 3 and b has the value 1. Since these are local values these do not affect the previous values of aand b.
And then?
Since b has the value 1 the if statement is false, so the next line becomes rest = mult(a, b - 1).
What does this line do?
This line will assign the value of mult(3, 0) to rest.
So what is that value?
We will have to run the function one more time to find that out. This time a has the value 3 and b has the value 0.
So what happens next?
The first line in the function to run is if b == 0:. b has the value 0 so the next line to run is return 0
And what does the line return 0 do?
This line returns the value 0 out of the function.
So?
So now we know that mult(3, 0) has the value 0. Now we know what the line rest = mult(a, b - 1) did since we have run the function mult with the parameters 3 and 0. We have finished running mult(3, 0) and are now back to running mult(3, 1). The variable rest gets assigned the value 0.
What line is run next?
The line value = a + rest is run next. In this run of the function, a = 3 and rest = 0 so now value = 3.
What happens next?
The line return value is run. This returns 3 from the function. This also exits from the run of the function mult(3, 1). After return is called, we go back to runningmult(3, 2).
Where were we in mult(3, 2)?
We had the variables a = 3 and b = 2 and were examining the line rest = mult(a, b - 1).
So what happens now?
The variable rest get 3 assigned to it. The next line value = a + rest sets value to 3 + 3 or 6.
So now what happens?
The next line runs, this returns 6 from the function. We are now back to running the line print "3 * 2 = ", mult(3, 2) which can now print out the 6.
What is happening overall?
Basically we used two facts to calculate the multiple of the two numbers. The first is that any number times 0 is 0 (x * 0 = 0). The second is that a number times another number is equal to the first number plus the first number times one less than the second number (x * y = x + x * (y - 1)). So what happens is 3 * 2 is first converted into 3 + 3 * 1. Then 3 * 1 is converted into 3 + 3 * 0. Then we know that any number times 0 is 0 so 3 * 0 is 0. Then we can calculate that 3 + 3 * 0 is 3 + 0which is 3. Now we know what 3 * 1 is so we can calculate that 3 + 3 * 1 is 3 + 3 which is 6.
This is how the whole thing works:
3 * 2
3 + 3 * 1
3 + 3 + 3 * 0
3 + 3 + 0
3 + 3
6
Should you still have problems with this example, look at the process backwards. What is the last step that happens? We can easily make out that the result of mult(3, 0) is 0. Since b is 0, the function mult(3, 0) will return 0 and stop.
So what does the previous step do? mult(3, 1) does not return 0 because b is not 0. So the next lines are executed: rest = mult (a, b - 1), which is rest = mult (3, 0), which is 0 as we just worked out. So now the variable rest is set to 0.
The next line adds the value of rest to a, and since a is 3 and rest is 0, the result is 3.
Now we know that the function mult(3, 1) returns 3. But we want to know the result of mult(3,2). Therefore, we need to jump back to the start of the program and execute it one more round: mult(3, 2) sets rest to the result of mult(3, 1). We know from the last round that this result is 3. Then value calculates as a + rest, i. e. 3 + 3. Then the result of 3 * 2 is printed as 6.
The point of this example is that the function mult(a, b) starts itself inside itself. It does this until b reaches 0 and then calculates the result as explained above.
Recursion
Programming constructs of this kind are called recursive and probably the most intuitive definition of recursion is:
Recursion
If you still don't get it, see recursion.
These last two sections were recently written. If you have any comments, found any errors or think I need more/clearer explanations please email. I have been known in the past to make simple things incomprehensible. If the rest of the tutorial has made sense, but this section didn't, it is probably my fault and I would like to know. Thanks.
Examples
factorial.py
#defines a function that calculates the factorial

def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

print "2! =", factorial(2)
print "3! =", factorial(3)
print "4! =", factorial(4)
print "5! =", factorial(5)
Output:
2! = 2
3! = 6
4! = 24
5! = 120
countdown.py
def count_down(n):
    print n
    if n > 0:
        return count_down(n-1)

count_down(5)
Output:
5
4
3
2
1
0
Commented function_interesting.py
# The comments below have been numbered as steps, to make explanation
# of the code easier. Please read according to those steps.
# (step number 1, for example, is at the bottom)


def mult(a, b): # (2.) This function will keep repeating itself, because....
    if b == 0:
        return 0
    rest = mult(a, b - 1) # (3.) ....Once it reaches THIS, the sequence starts over again and goes back to the top!
    value = a + rest
    return value # (4.) therefore, "return value" will not happen until the program gets past step 3 above

print "3 * 2 = ", mult(3, 2) # (1.) The "mult" function will first initiate here


# The "return value" event at the end can therefore only happen
# once b equals zero (b decreases by 1 everytime step 3 happens).
# And only then can the print command at the bottom be displayed.

# See it as kind of a "jump-around" effect. Basically, all you
# should really understand is that the function is reinitiated
# WITHIN ITSELF at step 3. Therefore, the sequence "jumps" back
# to the top.
Commented factorial.py
# Another "jump-around" function example:

def factorial(n): # (2.) So once again, this function will REPEAT itself....
    if n <= 1:
        return 1
    return n * factorial(n - 1) # (3.) Because it RE-initiates HERE, and goes back to the top.

print "2! =", factorial(2) # (1.) The "factorial" function is initiated with this line
print "3! =", factorial(3)
print "4! =", factorial(4)
print "5! =", factorial(5)
Commented countdown.py
# Another "jump-around", nice and easy:


def count_down(n): # (2.) Once again, this sequence will repeat itself....
    print n
    if n > 0:
        return count_down(n-1) # (3.) Because it restarts here, and goes back to the top

count_down(5) # (1.) The "count_down" function initiates here

Functions - python (part 6)

Defining Functions

Creating Functions
To start off this chapter I am going to give you an example of what you could do but shouldn't (so don't type it in):
a = 23
b = -23

if a < 0:
    a = -a
if b < 0:
    b = -b
if a == b:
    print "The absolute values of", a, "and", b, "are equal"
else:
    print "The absolute values of", a, "and", b, "are different"
with the output being:
The absolute values of 23 and 23 are equal
The program seems a little repetitive. Programmers hate to repeat things -- that's what computers are for, after all! (Note also that finding the absolute value changed the value of the variable, which is why it is printing out 23, and not -23 in the output.) Fortunately Python allows you to create functions to remove duplication. Here is the rewritten example:
def absolute_value(n):
    if n < 0:
        n = -n
    return n

a = 23
b = -23

if absolute_value(a) == absolute_value(b):
    print "The absolute values of", a, "and", b, "are equal"
else:
    print "The absolute values of", a, "and", b, "are different"
with the output being:
The absolute values of 23 and -23 are equal
The key feature of this program is the def statement. def (short for define) starts a function definition. def is followed by the name of the function absolute_value. Next comes a '(' followed by the parameter n (n is passed from the program into the function when the function is called). The statements after the ':' are executed when the function is used. The statements continue until either the indented statements end or a return is encountered. The return statement returns a value back to the place where the function was called.
Notice how the values of a and b are not changed. Functions can be used to repeat tasks that don't return values. Here are some examples:
def hello():
    print "Hello"

def area(w, h):
    return w * h

def print_welcome(name):
    print "Welcome", name

hello()
hello()

print_welcome("Fred")
w = 4
h = 5
print "width =", w, "height =", h, "area =", area(w, h)
with output being:
Hello
Hello
Welcome Fred
width = 4 height = 5 area = 20
That example shows some more stuff that you can do with functions. Notice that you can use no arguments or two or more. Notice also when a function doesn't need to send back a value, a return is optional.
Variables in functions
When eliminating repeated code, you often have variables in the repeated code. In Python, these are dealt with in a special way. So far all variables we have seen are global variables. Functions have a special type of variable called local variables. These variables only exist while the function is running. When a local variable has the same name as another variable (such as a global variable), the local variable hides the other. Sound confusing? Well, these next examples (which are a bit contrived) should help clear things up.
a = 4

def print_func():
    a = 17
    print "in  print_func a = ", a

print_func()
print "a = ", a
When run, we will receive an output of:
in print_func a = 17
a = 4
Variable assignments inside a function do not override global variables, they exist only inside the function. Even though a was assigned a new value inside the function, this newly assigned value was only relevant to print_func, when the function finishes running, and the a's values is printed again, we see the originally assigned values.
Complex example
a_var = 10
b_var = 15
e_var = 25

def a_func(a_var):
    print "in a_func a_var = ", a_var
    b_var = 100 + a_var
    d_var = 2 * a_var
    print "in a_func b_var = ", b_var
    print "in a_func d_var = ", d_var
    print "in a_func e_var = ", e_var
    return b_var + 10

c_var = a_func(b_var)

print "a_var = ", a_var
print "b_var = ", b_var
print "c_var = ", c_var
print "d_var = ", d_var
The output is:
in a_func a_var =  15
in a_func b_var =  115
in a_func d_var =  30
in a_func e_var =  25
a_var =  10
b_var =  15
c_var =  125
d_var =

Traceback (most recent call last):
  File "C:\Python24\def2", line 19, in -toplevel-
     print "d_var = ", d_var

NameError: name 'd_var' is not defined
In this example the variables a_var, b_var, and d_var are all local variables when they are inside the function a_func. After the statement return b_var + 10 is run, they all cease to exist. The variable a_var is automatically a local variable since it is a parameter name. The variables b_var and d_var are local variables since they appear on the left of an equals sign in the function in the statements b_var = 100 + a_var and d_var = 2 * a_var .
Inside of the function a_var has no value assigned to it. When the function is called with c_var = a_func(b_var), 15 is assigned to a_var since at that point in time b_varis 15, making the call to the function a_func(15). This ends up setting a_var to 15 when it is inside of a_func.
As you can see, once the function finishes running, the local variables a_var and b_var that had hidden the global variables of the same name are gone. Then the statementprint "a_var = ", a_var prints the value 10 rather than the value 15 since the local variable that hid the global variable is gone.
Another thing to notice is the NameError that happens at the end. This appears since the variable d_var no longer exists since a_func finished. All the local variables are deleted when the function exits. If you want to get something from a function, then you will have to use return something.
One last thing to notice is that the value of e_var remains unchanged inside a_func since it is not a parameter and it never appears on the left of an equals sign inside of the function a_func. When a global variable is accessed inside a function it is the global variable from the outside.
Functions allow local variables that exist only inside the function and can hide other variables that are outside the function.
Examples
temperature2.py
# converts temperature to fahrenheit or celsius

def print_options():
    print "Options:"
    print " 'p' print options"
    print " 'c' convert from celsius"
    print " 'f' convert from fahrenheit"
    print " 'q' quit the program"

def celsius_to_fahrenheit(c_temp):
    return 9.0 / 5.0 * c_temp + 32

def fahrenheit_to_celsius(f_temp):
    return (f_temp - 32.0) * 5.0 / 9.0

choice = "p"
while choice != "q":
    if choice == "c":
        temp = input("Celsius temperature: ")
        print "Fahrenheit:", celsius_to_fahrenheit(temp)
    elif choice == "f":
        temp = input("Fahrenheit temperature: ")
        print "Celsius:", fahrenheit_to_celsius(temp)
    elif choice != "q":
        print_options()
    choice = raw_input("option: ")
Sample Run:
Options:
'p' print options
'c' convert from celsius
'f' convert from fahrenheit
'q' quit the program
option: c
Celsius temperature: 30
Fahrenheit: 86.0
option: f
Fahrenheit temperature: 60
Celsius: 15.5555555556
option: q
area2.py
# By Amos Satterlee
print
def hello():
    print 'Hello!'

def area(width, height):
    return width * height

def print_welcome(name):
    print 'Welcome,', name

name = raw_input('Your Name: ')
hello(),
print_welcome(name)
print
print 'To find the area of a rectangle,'
print 'enter the width and height below.'
print
w = input('Width: ')
while w <= 0:
    print 'Must be a positive number'
    w = input('Width: ')

h = input('Height: ')
while h <= 0:
    print 'Must be a positive number'
    h = input('Height: ')

print 'Width =', w, 'Height =', h, 'so Area =', area(w, h)
Sample Run:
Your Name: Josh
Hello!
Welcome, Josh

To find the area of a rectangle,
enter the width and height below.

Width: -4
Must be a positive number
Width: 4
Height: 3
Width = 4 Height = 3 so Area = 12
Exercises
Rewrite the area2.py program from the Examples above to have a separate function for the area of a square, the area of a rectangle, and the area of a circle (3.14 * radius ** 2). This program should include a menu interface.

Debugging - python (part 5)

Debugging 

What is debugging?
"As soon as we started programming, we found to our surprise that it wasn't as easy to get programs right as we had thought. Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs." — Maurice Wilkes discovers debugging, 1949
By now if you have been messing around with the programs you have probably found that sometimes the program does something you didn't want it to do. This is fairly common. Debugging is the process of figuring out what the computer is doing and then getting it to do what you want it to do. This can be tricky. I once spent nearly a week tracking down and fixing a bug that was caused by someone putting an x where a y should have been.
This chapter will be more abstract than previous chapters.
What should the program do?
The first thing to do (this sounds obvious) is to figure out what the program should be doing if it is running correctly. Come up with some test cases and see what happens. For example, let's say I have a program to compute the perimeter of a rectangle (the sum of the length of all the edges). I have the following test cases:
height width perimeter
3 4 14
2 3 10
4 4 16
2 2 8
5 1 12
I now run my program on all of the test cases and see if the program does what I expect it to do. If it doesn't then I need to find out what the computer is doing.
More commonly some of the test cases will work and some will not. If that is the case you should try and figure out what the working ones have in common. For example here is the output for a perimeter program (you get to see the code in a minute):
Height: 3
Width: 4
perimeter = 15
Height: 2
Width: 3
perimeter = 11
Height: 4
Width: 4
perimeter = 16
Height: 2
Width: 2
perimeter = 8
Height: 5
Width: 1
perimeter = 8
Notice that it didn't work for the first two inputs, it worked for the next two and it didn't work on the last one. Try and figure out what is in common with the working ones. Once you have some idea what the problem is finding the cause is easier. With your own programs you should try more test cases if you need them.
What does the program do?
The next thing to do is to look at the source code. One of the most important things to do while programming is reading source code. The primary way to do this is code walkthroughs.
A code walkthrough starts at the first line, and works its way down until the program is done. While loops and if statements mean that some lines may never be run and some lines are run many times. At each line you figure out what Python has done.
Lets start with the simple perimeter program. Don't type it in, you are going to read it, not run it. The source code is:
height = input("Height: ")
width = input("Width: ")
print "perimeter =", width + height + width + width
Question: What is the first line Python runs?
Answer: The first line is always run first. In this case it is: height = input("Height: ")
What does that line do?
Prints Height: , waits for the user to type a number in, and puts that in the variable height.
What is the next line that runs?
In general, it is the next line down which is: width = input("Width: ")
What does that line do?
Prints Width: , waits for the user to type a number in, and puts what the user types in the variable width.
What is the next line that runs?
When the next line is not indented more or less than the current line, it is the line right afterwards, so it is: print "perimeter = ", width + height + width + width (It may also run a function in the current line, but that's a future chapter.) What does that line do?
First it prints perimeter = , then it prints width + height + width + width.
Does width + height + width + width calculate the perimeter properly?
Let's see, perimeter of a rectangle is the bottom (width) plus the left side (height) plus the top (width) plus the right side (huh?). The last item should be the right side's length, or the height.
Do you understand why some of the times the perimeter was calculated "correctly"?  
It was calculated correctly when the width and the height were equal.
The next program we will do a code walkthrough for is a program that is supposed to print out 5 dots on the screen. However, this is what the program is outputting:
. . . .
And here is the program:
number = 5
while number > 1:
    print ".",
    number = number - 1
print
This program will be more complex to walkthrough since it now has indented portions (or control structures). Let us begin.
What is the first line to be run?
The first line of the file: number = 5
What does it do?
Puts the number 5 in the variable number.
What is the next line?
The next line is: while number > 1:
What does it do?
Well, while statements in general look at their expression, and if it is true they do the next indented block of code, otherwise they skip the next indented block of code.
So what does it do right now?
If number > 1 is true then the next two lines will be run.
So is number > 1?
The last value put into number was 5 and 5 > 1 so yes.
So what is the next line?
Since the while was true the next line is: print ".",
What does that line do?
Prints one dot and since the statement ends with a ',' the next print statement will not be on a different screen line.
What is the next line?
number = number - 1 since that is following line and there are no indent changes.
What does it do?
It calculates number - 1, which is the current value of number (or 5) subtracts 1 from it, and makes that the new value of number. So basically it changes number's value from 5 to 4.
What is the next line?
Well, the indent level decreases so we have to look at what type of control structure it is. It is a while loop, so we have to go back to the while clause which is while number > 1:
What does it do?
It looks at the value of number, which is 4, and compares it to 1 and since 4 > 1 the while loop continues.
What is the next line?
Since the while loop was true, the next line is: print ".",
What does it do?
It prints a second dot on the line.
What is the next line?
No indent change so it is: number = number - 1
And what does it do?
It takes the current value of number (4), subtracts 1 from it, which gives it 3 and then finally makes 3 the new value of number.
What is the next line?
Since there is an indent change caused by the end of the while loop, the next line is: while number > 1:
What does it do?
It compares the current value of number (3) to 1. 3 > 1 so the while loop continues.
What is the next line?
Since the while loop condition was true the next line is: print ".",
And it does what?
A third dot is printed on the line.
What is the next line?
It is: number = number - 1
What does it do?
It takes the current value of number (3) subtracts from it 1 and makes the 2 the new value of number.
What is the next line?
Back up to the start of the while loop: while number > 1:
What does it do?
It compares the current value of number (2) to 1. Since 2 > 1 the while loop continues.
What is the next line?
Since the while loop is continuing: print ".",
What does it do?
It discovers the meaning of life, the universe and everything. I'm joking. (I had to make sure you were awake.) The line prints a fourth dot on the screen.
What is the next line?
It's: number = number - 1
What does it do?
Takes the current value of number (2) subtracts 1 and makes 1 the new value of number.
What is the next line?
Back up to the while loop: while number > 1:
What does the line do?
It compares the current value of number (1) to 1. Since 1 > 1 is false (one is not greater than one), the while loop exits.
What is the next line?
Since the while loop condition was false the next line is the line after the while loop exits, or: print
What does that line do?
Makes the screen go to the next line.
Why doesn't the program print 5 dots?
The loop exits 1 dot too soon.
How can we fix that?
Make the loop exit 1 dot later.
And how do we do that?
There are several ways. One way would be to change the while loop to: while number > 0: Another way would be to change the conditional to: number >= 1 There are a couple others.
How do I fix the program?
You need to figure out what the program is doing. You need to figure out what the program should do. Figure out what the difference between the two is. Debugging is a skill that has to be practiced to be learned. If you can't figure it out after an hour, take a break, talk to someone about the problem or contemplate the lint in your navel. Come back in a while and you will probably have new ideas about the problem. Good luck.

If statement - python (part 4)

Decisions

If statement
As always I believe I should start each chapter with a warm-up typing exercise, so here is a short program to compute the absolute value of a number:
n = input("Number? ")
if n < 0:
   print "The absolute value of", n, "is", -n
else:
   print "The absolute value of", n, "is", n
Here is the output from the two times that I ran this program:
Number? -34
The absolute value of -34 is 34
Number? 1
The absolute value of 1 is 1
So what does the computer do when it sees this piece of code? First it prompts the user for a number with the statement "n = input("Number? ")". Next it reads the line "if n < 0:". If n is less than zero Python runs the line "print "The absolute value of", n, "is", -n". Otherwise it runs the line "print "The absolute value of", n, "is", n".
More formally Python looks at whether the expression n < 0 is true or false. An if statement is followed by an indented block of statements that are run when the expression is true. Optionally after the if statement is an else statement and another indented block of statements. This second block of statements is run if the expression is false.
There are a number of different tests that an expression can have. Here is a table of all of them:
operator function
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal
!= not equal
<> another way to say not equal (old style, not recommended)
Another feature of the if command is the elif statement. It stands for else if and means if the original if statement is false but the elif part is true, then do the elif part. And if neither the if or elif expressions are true, then do what's in the else block. Here's an example:
a = 0
while a < 10:
    a = a + 1
    if a > 5:
        print a, ">", 5
    elif a <= 7:
        print a, "<=", 7
    else:
        print "Neither test was true"
and the output:
1 <= 7
2 <= 7
3 <= 7
4 <= 7
5 <= 7
6 > 5
7 > 5
8 > 5
9 > 5
10 > 5
Notice how the elif a <= 7 is only tested when the if statement fails to be true. There can be more than one elif expression, allowing multiple tests to be done in a singleif statement.
Examples
# This Program Demonstrates the use of the == operator
# using numbers
print 5 == 6
# Using variables
x = 5
y = 8
print x == y
And the output
False
False
High_low.py
# Plays the guessing game higher or lower

# This should actually be something that is semi random like the
# last digits of the time or something else, but that will have to
# wait till a later chapter.  (Extra Credit, modify it to be random
# after the Modules chapter)
number = 78
guess = 0

while guess != number:
    guess = input("Guess a number: ")
    if guess > number:
        print "Too high"
    elif guess < number:
        print "Too low"

print "Just right"
Sample run:
Guess a number: 100
Too high
Guess a number: 50
Too low
Guess a number: 75
Too low
Guess a number: 87
Too high
Guess a number: 81
Too high
Guess a number: 78
Just right
even.py
# Asks for a number.
# Prints if it is even or odd

number = input("Tell me a number: ")
if number % 2 == 0:
    print number, "is even."
elif number % 2 == 1:
    print number, "is odd."
else:
    print number, "is very strange."
Sample runs:
Tell me a number: 3
3 is odd.
Tell me a number: 2
2 is even.
Tell me a number: 3.14159
3.14159 is very strange.
average1.py
# keeps asking for numbers until 0 is entered.
# Prints the average value.

count = 0
sum = 0.0
number = 1 # set to something that will not exit the while loop immediately.

print "Enter 0 to exit the loop"

while number != 0:
    number = input("Enter a number: ")
    if number != 0:
        count = count + 1
        sum = sum + number

print "The average was:", sum / count
Sample runs:
Enter 0 to exit the loop
Enter a number: 3
Enter a number: 5
Enter a number: 0
The average was: 4.0
Enter 0 to exit the loop
Enter a number: 1
Enter a number: 4
Enter a number: 3
Enter a number: 0
The average was: 2.66666666667
average2.py
# keeps asking for numbers until count numbers have been entered.
# Prints the average value.

sum = 0.0

print "This program will take several numbers then average them"
count = input("How many numbers would you like to average: ")
current_count = 0

while current_count < count:
    current_count = current_count + 1
    print "Number", current_count
    number = input("Enter a number: ")
    sum = sum + number

print "The average was:", sum / count
Sample runs:
This program will take several numbers then average them
How many numbers would you like to average: 2
Number 1
Enter a number: 3
Number 2
Enter a number: 5
The average was: 4.0
This program will take several numbers then average them
How many numbers would you like to average: 3
Number 1
Enter a number: 1
Number 2
Enter a number: 4
Number 3
Enter a number: 3
The average was: 2.66666666667
Exercises
Modify the higher or lower program from this section to keep track of how many times the user has entered the wrong number. If it is more than 3 times, print "That must have been complicated." Note that the program does not have to quit asking for the number before it is guessed, it just has to print this after the number is guessed.
Write a program that asks for two numbers. If the sum of the numbers is greater than 100, print "That is a big number."
Write a program that asks the user their name, if they enter your name say "That is a nice name", if they enter "John Cleese" or "Michael Palin", tell them how you feel about them ;), otherwise tell them "You have a nice name."

While loops - python (part 3)

Count to 10 

While loops
Here we present our first control structure. Ordinarily the computer starts with the first line and then goes down from there. Control structures change the order that statements are executed or decide if a certain statement will be run. Here's the source for a program that uses the while control structure:
a = 0
while a < 10:
    a = a + 1
    print a
And here is the extremely exciting output:
1
2
3
4
5
6
7
8
9
10
And you thought it couldn't get any worse after turning your computer into a five dollar calculator?
So what does the program do? First it sees the line a = 0 and sets a to zero. Then it sees while a < 10: and so the computer checks to see if a < 10. The first time the computer sees this statement a is zero so it is less than 10. In other words as long as a is less than ten the computer will run the tabbed in statements. This eventually makes aequal to ten (by adding one to a again and again), and the while a < 10 is not true any longer. Reaching that point the program will not run the indented lines any longer.
Always remember to put a colon ":" after the "while" statement!
Here is another example of the use of while:
a = 1
s = 0
print 'Enter Numbers to add to the sum.'
print 'Enter 0 to quit.'
while a != 0:
    print 'Current Sum:', s
    a = input('Number? ')
    s = s + a
print 'Total Sum =', s
Enter Numbers to add to the sum.
Enter 0 to quit.
Current Sum: 0
Number? 200
Current Sum: 200
Number? -15.25
Current Sum: 184.75
Number? -151.85
Current Sum: 32.9
Number? 10.00
Current Sum: 42.9
Number? 0
Total Sum = 42.9
Notice how print 'Total Sum =', s is only run at the end. The while statement only affects the lines that are indented with whitespace. The != means "does not equal" so"while a != 0:" means: "until a is zero, run the tabbed statements that follow."
Infinite loops
Now that we have while loops, it is possible to have programs that run forever. An easy way to do this is to write a program like this:
while 1 == 1:
   print "Help, I'm stuck in a loop."
The "==" operator is used to test equality of the expressions on the two sides of the operator, just as "<" was used for "less than" before (you will get a complete list of all comparison operators in the next chapter).
This program will output Help, I'm stuck in a loop. until the heat death of the universe or until you stop it, because 1 will forever be equal to 1. The way to stop it is to hit the Control (or Ctrl) button and C (the letter) at the same time. This will kill the program. (Note: sometimes you will have to hit enter after the Control-C.)
Examples
Fibonacci.py
# This program calculates the Fibonacci sequence
a = 0
b = 1
count = 0
max_count = 20
while count < max_count:
    count = count + 1
    # we need to keep track of a since we change it
    old_a = a
    old_b = b
    a = old_b
    b = old_a + old_b
    # Notice that the , at the end of a print statement keeps it
    # from switching to a new line
    print old_a,
Output:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
Note the output on a single line by use of a comma at the end of the print statement.
Password.py
# Waits until a password has been entered.  Use Control-C to break out without
# the password

# Note that this must not be the password so that the
# while loop runs at least once.
password = "no password"

# note that != means not equal
while password != "unicorn":
    password = raw_input("Password: ")
print "Welcome in"
Sample run:
Password: auo
Password: y22
Password: password
Password: open sesame
Password: unicorn
Welcome in
Exercises
Write a program that asks the user for a Login Name and password. Then when they type "lock", they need to type in their name and password to unlock the program

Input and Variables - python (part 2)

Who Goes There?

Input and Variables
Now I feel it is time for a really complicated program. Here it is:
print "Halt!"
user_reply = raw_input("Who goes there? ")
print "You may pass,", user_reply
When I ran it, here is what my screen showed:
Halt!
Who goes there? Josh
You may pass, Josh
Note: After running the code by pressing F5, the Python shell will only give output:
Halt!
Who goes there?
You need to enter your name in the Python shell, and then press Enter to get the rest of the output.
Of course when you run the program your screen will look different because of the raw_input() statement. When you ran the program you probably noticed (you did run the program, right?) how you had to type in your name and then press Enter. Then the program printed out some more text and also your name. This is an example of input. The program reaches a certain point and then waits for the user to input some data that the program can use later.
Of course, getting information from the user would be useless if we didn't have anywhere to put that information and this is where variables come in. In the previous programuser_reply is a variable. Variables are like a box that can store some piece of data. Here is a program to show examples of variables:
a = 123.4
b23 = 'Spam'
first_name = "Bill"
b = 432
c = a + b
print "a + b is",c
print "first_name is",first_name
print "Sorted Parts, After Midnight or",b23
And here is the output:
a + b is 555.4
first_name is Bill
Sorted Parts, After Midnight or Spam
The variables in the above program are a, b23, first_name, b, and c. A variable in Python can store any type of data - in this example we stored some strings (e.g. "Bill") and some numbers (e.g. 432).
Note the difference between strings and variable names. Strings are marked with quotation marks, which tells the computer "don't try to understand, just take this text as it is":
print "first_name"
This would print the text:
first_name
as-is. Variable names are written without any quotation marks and instruct the computer "use the value I've previously stored under this name":
print first_name
which would print (after the previous example):
Bill
=== Assignment ===
Okay, so we have these boxes called variables and also data that can go into the variable. The computer will see a line like first_name = "Bill" and it reads it as "Put the string Bill into the box (or variable) first_name. Later on it sees the statement c = a + b and it reads it as "put the sum of a + b or 123.4 + 432 which equals 555.4into c". The right hand side of the statement (a + b) is evaluated and the result is stored in the variable on the left hand side (c). This is called assignment, and you should not confuse the assignment equal sign (=) with "equality" in a mathematical sense here (that's what == will be used for later).
Here is another example of variable usage:
a = 1
print a
a = a + 1
print a
a = a * 2
print a
And of course here is the output:
1
2
4
Even if it is the same variable on both sides the computer still reads it as "First find out the data to store and then find out where the data goes".
One more program before I end this chapter:
number = input("Type in a number: ")
text = raw_input("Type in a string: ")
print "number =", number
print "number is a", type(number)
print "number * 2 =", number * 2
print "text =", text
print "text is a", type(text)
print "text * 2 =", text * 2
The output I got was:
Type in a Number: 12.34
Type in a String: Hello
number = 12.34
number is a <type 'float'>
number * 2 = 24.68
text = Hello
text is a <type 'str'>
text * 2 = HelloHello
Notice that number was gotten with input() while text was gotten with raw_input(). raw_input() returns a string while input() returns a number. When you want the user to type in a number use input() but if you want the user to type in a string use raw_input().

Only use input() when you trust your users with the computer the program runs on.
Everything entered into input() dialog is evaluated as a Python expression and thus allows the user to take control of your program. For example, entering __import__('os').system('dir') executes the dir command. You should instead get a string and convert it to the neccessary type like int(raw_input()) or float(raw_input()).
The second half of the program uses type() which tells what a variable is. Numbers are of type int or float, which are short for integer and floating point (mostly used for decimal numbers), respectively. Text strings are of type str, short for string. Integers and floats can be worked on by mathematical functions, strings cannot. Notice how when python multiplies a number by an integer the expected thing happens. However when a string is multiplied by an integer the result is that multiple copies of the string are produced (i.e., text * 2 = HelloHello).
The operations with strings do different things than operations with numbers. Here are some interactive mode examples to show that some more.
>>> "This" + " " + "is" + " joined."
'This is joined.'
>>> "Ha, " * 5
'Ha, Ha, Ha, Ha, Ha, '
>>> "Ha, " * 5 + "ha!"
'Ha, Ha, Ha, Ha, Ha, ha!'
>>>
This could also be done as a program:
print "This" + " " + "is" + " joined."
print "Ha, " * 5
print "Ha, " * 5 + "ha!"
Here is the list of some string operations:
Operation Symbol Example
Repetition * "i" * 5 == "iiiii"
Concatenation + "Hello, " + "World!" == "Hello, World!"
Examples
Rate_times.py
# This program calculates rate and distance problems
print "Input a rate and a distance"
rate = input("Rate: ")
distance = input("Distance: ")
print "Time:", (distance / rate)
Sample runs:
Input a rate and a distance
Rate: 5
Distance: 10
Time: 2
Input a rate and a distance
Rate: 3.52
Distance: 45.6
Time: 12.9545454545
Area.py
# This program calculates the perimeter and area of a rectangle
print "Calculate information about a rectangle"
length = input("Length: ")
width = input("Width: ")
print "Area", length * width
print "Perimeter", 2 * length + 2 * width
Sample runs:
Calculate information about a rectangle
Length: 4
Width: 3
Area 12
Perimeter 14
Calculate information about a rectangle
Length: 2.53
Width: 5.2
Area 13.156
Perimeter 15.46
temperature.py
# Converts Fahrenheit to Celsius
temp = input("Fahrenheit temperature: ")
print (temp - 32.0) * 5.0 / 9.0
Sample runs:
Fahrenheit temperature: 32
0.0
Fahrenheit temperature: -40
-40.0
Fahrenheit temperature: 212
100.0
Fahrenheit temperature: 98.6
37.0
Exercises
Write a program that gets 2 string variables and 2 integer variables from the user, concatenates (joins them together with no spaces) and displays the strings, then multiplies the two numbers on a new line.

Hello, World python in linux (part 1)

Hello, World

What you should know
You should know how to edit programs in a text editor or IDLE, save the file and run the file once the files have been saved to your disk.
Printing
Programming tutorials since the beginning of time have started with a little program called "Hello, World!"[1] The syntax changed in Python 3.0. If you are using Python 3.0, you should be reading Non-Programmer's Tutorial for Python 3 instead. So here is the Python 2.6

example:
print "Hello, World!"

If you are using the command line to run programs then type it in with a text editor, save it as hello.py and run it with python hello.py
Otherwise go into IDLE, create a new window, and create the program as in section Creating and Running Programs.
When this program is run here's

what it prints:
Hello, World!
Now I'm not going to tell you this every time, but when I show you a program I recommend that you type it in and run it. I learn better when I type it in and you probably do too.
Now here is a more complicated program:
print "Jack and Jill went up a hill"
print "to fetch a pail of water;"
print "Jack fell down, and broke his crown,"
print "and Jill came tumbling after."
When you run this program it prints out:
Jack and Jill went up a hill
to fetch a pail of water;
Jack fell down, and broke his crown,
and Jill came tumbling after.
When the computer runs this program it first sees the line:
print "Jack and Jill went up a hill"
so the computer prints:
Jack and Jill went up a hill
Then the computer goes down to the next line and sees:
print "to fetch a pail of water;"
So the computer prints to the screen:
to fetch a pail of water;
The computer keeps looking at each line, follows the command and then goes on to the next line. The computer keeps running commands until it reaches the end of the program.
Terminology
Now is probably a good time to give you a bit of an explanation of what is happening - and a little bit of programming terminology.
What we were doing above was using a command called print. The print command is followed by one or more arguments. So in this example
print "Hello, World!"
there is one argument, which is "Hello, World!". Note that this argument is a group of characters enclosed in double quotes ("). This is commonly referred to as a string of characters, or string, for short. Another example of a string is "Jack and Jill went up a hill".
A command and its arguments are collectively referred to as a statement, so
print "Hello, World!"
is an example of a statement.
That's probably more than enough terminology for now.
Expressions
Here is another program:
print "2 + 2 is", 2 + 2
print "3 * 4 is", 3 * 4
print "100 - 1 is", 100 - 1
print "(33 + 2) / 5 + 11.5 is", (33 + 2) / 5 + 11.5
And here is the output when the program is run:
2 + 2 is 4
3 * 4 is 12
100 - 1 is 99
(33 + 2) / 5 + 11.5 is 18.5
As you can see, Python can turn your six hundred dollar computer into a 2 dollar calculator.
In this example, the print command is followed by two arguments, with each of the arguments separated by a comma. So with the first line of the program
print "2 + 2 is", 2 + 2
The first argument is the string "2 + 2 is" and the second argument is the mathematical expression 2 + 2, which is commonly referred to as an expression.
What is important to note is that a string is printed as is (the string is what is within the double quotes but doesn't include the double quotes themselves. So the string is printed without the enclosing double quotes.) But an expression is evaluated, (in other words, converted) to its actual value.
Python has six basic operations for numbers:
Operation Symbol Example
Power (exponentiation) ** 5 ** 2 == 25
Multiplication * 2 * 3 == 6
Division / 14 / 3 == 4
Remainder (modulo) % 14 % 3 == 2
Addition + 1 + 2 == 3
Subtraction - 4 - 3 == 1
Notice that division follows the rule, if there are no decimals to start with, there will be no decimals to end with. The following program shows this:
print "14 / 3 = ", 14 / 3
print "14 % 3 = ", 14 % 3
print
print "14.0 / 3.0 =", 14.0 / 3.0
print "14.0 % 3.0 =", 14.0 % 3.0
print
print "14.0 / 3 =", 14.0 / 3
print "14.0 % 3 =", 14.0 % 3
print
print "14 / 3.0 =", 14 / 3.0
print "14 % 3.0 =", 14 % 3.0
print
With the output:
14 / 3 = 4
14 % 3 = 2

14.0 / 3.0 = 4.66666666667
14.0 % 3.0 = 2.0

14.0 / 3 = 4.66666666667
14.0 % 3 = 2.0

14 / 3.0 = 4.66666666667
14 % 3.0 = 2.0
Notice how Python gives different answers for some problems depending on whether or not decimal values are used.
The order of operations is the same as in math:
parentheses ()
exponents **
multiplication *, division /, and remainder %
addition + and subtraction -
So use parentheses to structure your formulas when needed.
Talking to humans (and other intelligent beings)
Often in programming you are doing something complicated and may not in the future remember what you did. When this happens, the program should probably be commented. Acomment is a note to you and other programmers explaining what is happening. For example:
# Not quite PI, but an incredible simulation
print 22.0 / 7.0    # 355/113 is even more incredible rational approx to PI
Which outputs
3.14285714286
Notice that the comment starts with a hash: #. Comments are used to communicate with others who read the program and your future self to make clear what is complicated.
Note that any text can follow a comment, and that when the program is run, the text after the # through to the end of that line is ignored. The # does not have to be at the beginning of a new line:
# Output PI on the screen
print 22.0 / 7.0 # Well, just a good approximation
Examples
Each chapter (eventually) will contain examples of the programming features introduced in the chapter. You should at least look over them and see if you understand them. If you don't, you may want to type them in and see what happens. Mess around with them, change them and see what happens.
Denmark.py
print "Something's rotten in the state of Denmark."
print "                -- Shakespeare"
Output:
Something's rotten in the state of Denmark.
                -- Shakespeare
School.py
# This is not quite true outside of USA
# and is based on my dim memories of my younger years
print "First Grade"
print "1 + 1 =", 1 + 1
print "2 + 4 =", 2 + 4
print "5 - 2 =", 5 - 2
print
print "Third Grade"
print "243 - 23 =", 243 - 23
print "12 * 4 =", 12 * 4
print "12 / 3 =", 12 / 3
print "13 / 3 =", 13 / 3, "R", 13 % 3
print
print "Junior High"
print "123.56 - 62.12 =", 123.56 - 62.12
print "(4 + 3) * 2 =", (4 + 3) * 2
print "4 + 3 * 2 =", 4 + 3 * 2
print "3 ** 2 =", 3 ** 2
print
Output:
First Grade
1 + 1 = 2
2 + 4 = 6
5 - 2 = 3

Third Grade
243 - 23 = 220
12 * 4 = 48
12 / 3 = 4
13 / 3 = 4 R 1

Junior High
123.56 - 62.12 = 61.44
(4 + 3) * 2 = 14
4 + 3 * 2 = 10
3 ** 2 = 9
Exercises
Write a program that prints your full name and your birthday as separate strings.
Write a program that shows the use of all 6 math functions.