Sunday, July 19, 2015

Python on the go - Revision of Repetitions

To repeat a certain task a fixed number of times, a for loop is used:-


 for x in range(5): 
    print x


To repeat a task until a certain condition is met, a while loop is used:-

def countdown(n):
    while n > 0:
          print n
          n = n-1
    print 'Blastoff!'


Another way a process can be repeated is recursion  which can be difficult to implement :-

def countdown(n):
    if n <= 0:
       print 'Blastoff!'
    else:
         print n
         countdown(n-1)


A recursion  usually consists of
(1)  a base case (when to stop)
(2) a work towards a base case
(3) a recursive call that calls itself


Updated - 27-7-2015

Saturday, July 11, 2015

Python on the go - Revision of Conditional Execution

There are times in a program when there is a need to execute certain instructions after a certain condition is met  and this process may be carried out by using   "if"  statements as shown:-


num = raw_input('Input a number? ')
num2=float(num)
if num2>0:
   print "The number is positive"
elif num2==0:
     print "The number is zero"
else:
     print "The number is negative"


elif is an abbreviation for  "else if"  and it can be used more than once. else is used for the possible remaining conditions and normally used at the end of the "if" statements.  However, there does not need to be one.


Sunday, July 5, 2015

Python on the go - Revision of Functions

A function is a block of code which performs a computation. They can be reused in a program.
Here are some functions that can be used on lists

https://docs.python.org/2/tutorial/datastructures.html

These are inbuilt functions.  Certain functions like maths functions can be imported into the program by typing

from math import* 

We can also create our own functions. The 'Hello World' program can be written in a function as shown below.

def hello():
      print  "Hello World"

To call and run the function type  hello()  in the python shell