Vous êtes sur la page 1sur 26

Intro to Computing

ES102

Lecture 4

Some drawings and material from CS101 course pages


and lectures of various universities, esp. IITB and
OCW@MIT
Parameters to functions
def print_lyrics(x):
  print “Papa kehte hain”
  print “Beta “, x, “ banega”

print_lyrics(“engineer”)
print x

● What do you think happens above? Why?


Local variables are temporary
● Variables defined inside functions are not available outside
– They are created each time the function is called and destroyed
immediately

def addone(x):
  x = x + 1
  print “x + 1 = “, x + 1
a = 5
addone(a)
addone(a + 1)

What will this output ?


Local variables are temporary
def addone(x):
x = x + 1
print “x = “, x
a = 5
addone(a)
addone(a)

What will this output ?


Local variables vs. global
def somefunc(a):
    a = 2
    print "a = ", a + 1
a = 5
somefunc(a+1)
print a
a = a + 1
somefunc(a)

Notice that there is a global variable a as well


as a local variable, which is the parameter to the
function
Local variables vs. global
def somefunc(a):
    a = 2
    print "a = ", a
a = 5
somefunc(a)
a = a + 1
somefunc(a)
When the function somefunc is called, there is already a
global variable named a

However, if there is a variable of same name, the function


always uses that

In the above example, the parameter a creates a local


variable that is used by the function
Accessing global variables
# Global scope
X = 99                

def func(Y):          
    # Local scope
    Z = X + Y         
    return Z

func(1)               

Here, the variable X can be accessed even


though it is global, because it available when
the function is called.

What happens when we move the declaration


of X to below func(..) defn?
Order in which the code is evaluated

def func(Y):           def func(Y):          
    Z = X + Y             Z = X + Y        
    return Z     return Z
vs
X = 99 func(1)
func(1)                X = 99        
print “X = “, X  print “X = “, X 

● Are both correct? Are both wrong?


Order in which the code is evaluated

def func(Y):           def func(Y):          
    Z = X + Y             Z = X + Y        
    return Z     return Z
vs
X = 99 func(1) ERROR
func(1)                X = 99        
print “X = “, X  print “X = “, X 

● The function definition is first read but not evaluated


● For the left hand side, by the time the function is called,
the variable X exists globally
Scope of a variable

● Basic rule of python when looking for a variable:


– If local variable exists, then that takes preference
– Else, checks if global variable with this name

● Local variables are created when function is called


and destroyed when function is done

● Variables = containers
Return values
● Functions can often return a value – e.g. math.sin(1.0)

def myfunction ( x ): def myfunction2 ( x ):
    a = x + 1     return x + 1
    return a
Val = myfunction(5)
Val = myfunction(5) print “Val = “,Val
print “Val = “,Val    
   

● return statement returns the values after it


Return values
● Functions can often return a value – e.g. math.sin(1.0)

def myfunction ( x ): def myfunction2 ( x ):
    a = x + 1     return x + 1
    return a
Val = myfunction(5)
Val = myfunction(5) print “Val = “,Val
print “Val = “,Val    
   
● return statement returns the values after it
● If it is a mathematical expression, then the resulting value is returned
Return values

def myfunction ( x ):
    return x + 1

Val = myfunction(myfunction(5)) + myfunction(6)
print “Val = “,Val
   

● What is printed as Val?


Conditionals
In all the examples we have seen till now, we
always execute all the python statements

● What if we want to execute some statements


some of the time, based on some condition?
if...else
● Suppose we want to have a problem like this in
determining a student's grade
– If testscore > 40, then grade = PASS
– else not ….
● In python

 grade = “Y”
 if score >= 40: Note the indentation again and
  grade = “PASS” the colons
else:
  grade = “NOT”
if...else

● Boolean expression = results in True or False


– This is of type bool
– Examples: 1 < 2,  x! = 1,  x == y 
● The math expression following if should be a boolean
expression
 grade = “Y”
 if score >= 40: boolean
  grade = “PASS”
else:
  grade = “NOT”
Comparisons generate boolean values
Chained conditionals
if....elif...else
● What if we have more conditions? e.g. assign grades

 grade = “A”
The middle conditions are all elif
 if score >= 90:
  grade = “A”
elif score >= 80:
  grade = “B”
elif score >= 70:
  grade = “C”
else:
 grade = “D”

Write down this function named findgrade(...) in file grade.py


Nested conditionals
● What if we have more complicated conditions

 grade = “A”
 if testscore >= 90:
  if labscore >= 90: Two different scores –
   grade = “A+” testscore and labscore
 else: 
   grade = “A”
elif testscore >= 80: Note the indentation –
  if labscore >= 90  indicates the nesting
    grade = “B+”
  else:
    grade = “B”
elif...
 ...
Dividing a number
● Suppose we want to read a number and then want to find
one of the following:
– “Number is divisible by 3 but not by 4”
– “Number is divisible by 4 and not 3”
– “Number is divisible by both 4 and 3”
– “Number is divisible by neither 3 nor 4”

Pair up and write a program:


Then exchange your solution with your neighbor pair
Iteration
● Suppose we have the following problem:
– Take a number n
– Calculate the sum 1 * 2 * 3 * …. * n
– Can we do this using what we know till now?

result = 1
result = result * 2
result = result * 3
result = result * 4
….
Iteration
● Suppose we can do this:
– result = 1
– for each of the numbers i from 2,3,...,n 
result = result * i

– Would we be done?
Iteration
● Suppose we can do this:
– result = 1
– while  2,3,...,n 
result = result * i
● Corresponding python code

result = 1
i = 1
while i < 4:
    result = result * i
    i = i + 1
print “result =”, result 
Iteration: while loop
result = 1
i = 1
while i < 4:
    result = result * i
    i = i + 1
print “result =”, result 

● While loop has three parts:


– the condition: which tells us when the loop should end
– the actual calculation
– somewhere where we are actual changing the
variable
Iteration: while loop
result =1

i =1

result = 1
i < 4 condition
i = 1
while i < 4:
    result = result * i
    i = i + 1 result= result * i calculation
print “result =”, result 
i = i + 1 change

i < 4

result= result * i i = i + 1
Iteration: while loop

result =1

i =1
result = 1
i = 1 condition
while i < 4: NO
i < 4 out of loop
    result = result * i
    i = i + 1 YES
print “result =”, result 
result= result * i calculation

i = i + 1 change

Vous aimerez peut-être aussi