Presentation is loading. Please wait.

Presentation is loading. Please wait.

Module 3.

Similar presentations


Presentation on theme: "Module 3."— Presentation transcript:

1 Module 3

2 Conditional execution
to check conditions and change the behaviour of the program accordingly. The simplest form is the if statement: if x > 0: print "x is positive" The boolean expression after the if statement is called the condition. If it is true, then the indented statement gets executed. If not, nothing happens. Synatx : HEADER: FIRST STATEMENT ... LAST STATEMENT

3 The header begins on a new line and ends with a colon (:)
The header begins on a new line and ends with a colon (:). The indented statements that follow are called a block. The rest unindented statement marks the end of the block. A statement block inside a compound statement is called the body of the statement. There is no limit on the number of statements that can appear in the body of an if statement, but there has to be at least one.

4 Alternative execution
A second form of the if statement is alternative execution, in which there are two possibilities and the condition determines which one gets executed. The syntax looks like this: if x%2 == 0: print x, "is even" else: print x, "is odd"

5 The return statement The return statement allows you to terminate the execution of a function before you reach the end. One reason to use it is if detecting an error condition import math def printLogarithm(x): if x <= 0: print "Positive numbers only, please." return result = math.log(x) print "The log of x is", result

6 Recursion a function to call itself. def countdown(n): if n == 0:
print "Blastoff!" else: print n countdown(n-1)

7 def nLines(n): if n > 0: print nLines(n-1)

8 Recursion Recursion is a way of programming or coding a problem, in which a function calls itself one or more times in its body. Usually, it is returning the return value of this function call.

9 Termination condition:
A recursive function terminates, if with every recursive call the solution of the problem is downsized and moves towards a base case. A base case is a case, where the problem can be solved without further recursion.

10 Example:  4! = 4 * 3! 3! = 3 * 2! 2! = 2 * 1 Replacing the calculated values gives us the following expression 4! = 4 * 3 * 2 * 1

11 Factorial def factorial(n): if n == 1: return 1 else: return n * factorial(n-1)

12 def factorial(n): print("factorial has been called with n = " +n) if n == 1: return 1 else: res = n * factorial(n-1) print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res) return res print(factorial(5))

13 output

14 Fibonacci def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2)

15 Power of a number def power(a,n) if n==0: return 1 else return a*power(a,n-1) power(2,3)


Download ppt "Module 3."

Similar presentations


Ads by Google