Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
54 views

(PPT) Variables, Conditional Statements, and Recursion in Python

Changing values of variables Local vs global variables/constants Different formats of conditional statements (if) Recursive functions

Uploaded by

createthread
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

(PPT) Variables, Conditional Statements, and Recursion in Python

Changing values of variables Local vs global variables/constants Different formats of conditional statements (if) Recursive functions

Uploaded by

createthread
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 50

Variables, Conditional

Statements, and Recursion


Goal
• Become comfortable in Python
• Changing values of variables
• Local vs global variables/constants
• Different formats of conditional statements (if)
• Recursive functions
Python allows us to change the values of variables
• x = "a"
• x = 100
• x = 2*x - 1
Can changing one variable affect another
variable?
• Consider running this program:

x = 1000
y=x
x = "a"

• What are the values of x and y now?


What does this mean for our programs?
• Values of variables may change throughout a program
• Order of execution is very important
x = 10 x=2
x=2 x = 10

• We can write programs that keep track of changing information, for


example:
• current locations particles in an n-body simulation
• voltages and currents in a circuit simulation
Local vs Global variables
• Variables defined inside a function are called local variables
• Local variables can only be updated inside the function they are defined in
• Variables defined outside a function are called global variables
• Global variables cannot be updated inside any functions
Global constants
• A global variable whose value is not changed after the initial
assignment
• You can use the value of any global constant inside any function you
write.

tax_rate = 0.1
def after_tax(amount):
return amount * (1 - tax_rate)
Errors with global variables
• Consider the following program:

grade = 87
def increase_grade(inc):
grade = grade + inc
>>> increase_grade(5)

• This causes an error. Why?


Changing values of parameters?
• Consider the following program:
def add1(n):
n=n+1
return n
starter = 0
>>> y = add1(starter)
• The value of n is changed locally, but the value of starter is not
changed. The change to n is a local change only.
• Even if starter was called n, the same behavior would be observed.
Making decisions in Python
• In Python we
• Have a Boolean type (Bool)
• Can compare two values (>, <, >=, <=, !=, ==)
• Can combine comparisons using and, or, not
• Have a conditional statement (if, elif) for choosing different actions depending
on values of data
Comparisons in Python
• Built-in type Bool:
• True, False
• Equality testing: ==
• Use for most values
• Never use == to compare floating point values due to representation and
round-off errors
• Inequality testing: <, <=, >, >=
• != is shorthand for not equal
Evaluate the following comparisons
Import math
23 < 35
(4 + 3 + math.abs(-4)) == 12
5 * 5 > (3 * 3 + 4 * 4)
5 * 5 >= (3 * 3 + 4 * 4)
“abc” != “ABC”
“elephant” >= “cat”
abs(math.sqrt(2) - 1.41421) <= 0.001
Combining Boolean expressions
• v1 and v2
• True only if both v1 and v2 are True
• v1 or v2
• False only if both v1 and v2 are False
• not v
• True if v is False, otherwise False
• What’s the value of
(2 <= 4) and ((4 > 5) or (5 < 4) or not (3 == 2))
• Python allows shortcuts for some expressions:
x1 < x2 < x3
Evaluating Boolean expressions
• Evaluate from left to right, using precedence
not, and, or
• Stop evaluating as soon as answer is known
• or: stop when one argument evaluates to True
• and: stop when one argument evaluates to False
• Note: an expression’s syntax is checked before the expression is
evaluated. If there is a syntax error, the expression is not evaluated.
• 5 < 2 and (1 / 0) > 2
• 5 > 2 or h8rcahsrc%#%#
• True or ^--^
Basic Conditional Statement
if test: def double_positive(x):
true_action_1 result = x
... if x > 0:
true_action_K result = 2 * x
return result
Another Conditional Statement
if test: def ticket_cost(age):
true_action_1 if age < 18:
... cost = 5.50
true_action_Kt else:
else: cost = 9.25
false_action_1 return cost
...
false_action_Kf
“Chained” Conditional Statement
if test1: def ticket_cost(age):
action1_block if age < 3:
elif test2: cost = 0.0
elif age < 18:
action2_block
cost = 5.50
elif test3:
elif age < 65:
action3_block
cost = 9.25
... else:
else: cost = 8.00
else_action_block return cost
Why are these different?
x = 20 x = 20
if x > 10: if x>10:
x=x+1 x = x+1
elif x > 5: if x>5:
x=x-1 x = x-1
else: else:
x=2*x x = 2*x
Conditional statements can be nested
def categorize_x(x):
if x < 10:
if x > 5:
return "small”
else:
return "very small"
else:
return "big"
Python so far
• Variables
• local, global
• Int, Float, Str, Boolean
• Statements
• assignment
• conditional
• if
• if … else
• if … elif … else
• return statement
• Functions
• def func_name(args): body
Recursion on numbers

𝑛 !=
{ 1 , 𝑛= 0
𝑛× ( 𝑛 − 1 ) ! , 𝑛>0

def fac(n):
if n == 0:
return 1
else:
return n * fac(n - 1)
Example: sum of powers

def sn(n):
if n == 0:
return 1
else:
return 2 ** n + sn(n - 1)
“Countdown” template
def countdown_template(n):
if n==0:
return base_answer
else:
answer = ... n ... ... countdown_template(n-1) ...
return answer
Do countA(5) and countB(5) print the same
result?
def countA(n): def countB(n):
if n == 0: if n == 0:
return return
else: else:
print(n) countB(n - 1)
countA(n - 1) print(n)
Some limitations to the recursive approach
• CountA(10000) 
• “builtins.RecursionError: maximum recursion depth exceeded while calling a
Python object”
• There is a limit to how much recursion Python “can remember”
• Still fine for small problem sizes
• We’ll see a new approach for bigger problems.
Combination number

𝑚
{
1,𝑚=0𝑜𝑟 𝑚=𝑛
𝐶 = 𝑚 𝑚−1
𝑛
𝐶𝑛−1 +𝐶𝑛 −1 , 𝑜𝑡h𝑒𝑟𝑤𝑖𝑠𝑒
Fibonacci sequence
How many times is fib(0) called to calculate
fib(n)?
• Consider fib (10):
• fib(9) is called 1 time
• fib(8) is called 2 times
• fib(7) is called 3 times
• …

• How to make it more efficient?


Redefine fib(n) as a vector

• matrix multiplication

• But how to return a vector ?


How to return a vector ?
• return [1, 0]

• List
• A type of data in Python
List in Python
• Python lists can store
• any number of values
• any types of values (even in one list)
• Creating lists
• Use square brackets to begin and end list, and separate elements with a comma
• Concatenate (using +) existing lists to create a new list
• Examples:
num_list = [4, 5, 0]
str_list = ['a', 'b’]
empty_list = []
mixed_list = ['abc', 12, True, '',-12.4]
Useful Information about Python Lists
• len(L)  number of items in the list L
• L[i]  item at position i
• Called indexing the list
• Causes an error if i is out of range
• Positions: 0 <= i < len(L)
• Actual valid range: -len(L) <= i < len(L)
• "Slicing"a list
• L[i : j]  [L[i], L[i + 1], ... , L[j - 1]]
• L[i : j : k]  [L[i], L[i + k], ... , L[i + m * k]]
• includes all the positions up to (but not including) j
Other list operations
• in
• x in L  True if x is in L, False otherwise
• 5 in [10,2,4,5]
• "a" in ["hello", "there", "anyone"]
• sum
• Returns the sum of all values in a list of numbers
• sum([1, 2.25, 0, -1])  2.25
• sum([])
• sum([0,1,2,'3'])
• min, max
• consume lists as well
More list operations
>>> dir(list)
[ ..., 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort’]

• Most of these methods change the contents of list.


• None of these methods return a new list.
Using list methods
• What does this do?
• L = [1, 2, 3]
• v = L.pop(0)
• L.append(v)
• List mutation
• Lists are mutable (unlike Int, Float and Bool)
• We can add values to a list
• We can remove values from a list
• Memory management in Python
Python Memory Model
• Immutable values (Int, Float, Bool, Str)
• Consider x = 2 x 2
• A box is created and labelled x
• 2 is put inside the box y -1

• Example z “ab”

x=2
y=2–3
z = “a” + “b”
Representing lists in memory
p = [1, 0] + [3]

• Lists are comprised of multiple values, and list components can be


changed, so the representation is more complicated
• [1, 0, 3] is not put in p's box
• It gets its own space in memory which p will reference
Representing lists in memory
p = []
m = [1, 0] + [3]
null

p 1 0 3

m
Mutate a list
p = []
m = [1, 0] + [3]
null
m.append(5)

p 1 0 3 5

m
Mutate a list
m = [1, 0] + [3]
m.append(5)
m.extend([’a’, 0]) null

p 1 0 3 5 ‘a’ 0

m
Sharing list values
m.append(5)
m.extend([’a’, 0])
null
p=m

p 1 0 3 5 ‘a’ 0

m
You can mutate the existing list with either p or m
m.extend([’a’, 0])
p=m
null
p[1] = 4

p 1 4 3 5 ‘a’ 0

m
What’s the memory like after p = [’abc’] is executed?

m.extend([’a’, 0])
p=m
null
p[1] = 4

p 1 4 3 5 ‘a’ 0

m
What’s the memory like after p = [’abc’] is executed?

p=m
p[1] = 4
null
p = [‘abc’]

p 1 4 3 5 ‘a’ 0

m ‘abc’
Exercise: memory management
def dec(t): n=1
m=n
t=t–1
n=2*m
return t L = [3, 6, 9]
Q=L
p = L[2]
Q[0] = dec(m)
L[1] = dec(Q[2])
L[2] = [True, False]
m = L.append(n)
L = "x"
Functions and List Parameters
def change_first_to_1(L):
L[0] = 1 L

my_list = ['a', 2, 'c'] ‘a’


change_first_to_1(my_list) 1 2 ‘c’

my_list
What is different here?
def change_second_to_1(L):
L = [L[0], 1] + L[2:]
return L

1 2 ‘c’

my_list = ['a', 2, ‘c’] my_list


m = change_second_to_1(my_list)
What is different here?
def change_second_to_1(L):
L = [L[0], 1] + L[2:] L
1 1 ‘c’
return L

1 2 ‘c’

my_list = ['a', 2, ‘c’] my_list


m = change_second_to_1(my_list)

m
Example: multiply_by
def multiply_by(vals, multiplier):
‘’’ multiplies each value in vals by multiplier
restrictions: vals contain exactly three Ints
Effects: mutates vals

multiply_by: (list of Int) Int => None


Example:
for L = [1,2,3],
multiply_by(L, 10) => None,
and changes contents of L to [10, 20, 30]
‘’’
vals[0] *= multiplier
vals[1] *= multiplier
vals[2] *= multiplier
Redefine fib(n) as a vector

• matrix multiplication

• But how to return a vector ?


• Use list

You might also like