This is a question for a homework problem that I cant figure out:
Question Beginning
Q3. Let’s try to write a function that does the same thing as an if statement:
def if_function(condition, true_result, false_result):
"""Return true_result if condition is a true value, and false_result otherwise."""
if condition:
return true_result
else:
return false_result
This function actually doesn’t do the same thing as an if statement in all cases. To prove this fact, write functions c, t, and f such that one of these functions returns the number 1, but the other does not:
def with_if_statement():
if c():
return t()
else:
return f()
def with_if_function():
return if_function(c(), t(), f())
Question End
Heres what I figured out:
with_if_statement() does not evaluate f() if c() is true, but with_if_function() evaluates all 3 before checking if c() is true or not.
So, I thought of assigning a global variable in c(), and changing its value in f()
heres my code (which does not work):
def c():
try:
global x
except NameError:
x=1
if x==1:
return True
else:
return False
def t():
if x==1:
return (1)
else:
return (0)
def f():
global x
x=2
if x==1:
return (1)
else:
return (0)
can anyone help me figure out the answer? Thanks..!
The
globalstatement shouldn’t throw aNameError(and so you won’t runx=1inc()). I would try rewriting your code without using exceptions, they won’t be necessary to solve this and are making it more complicated than it needs to be. Using a global variable and having side effects in your functions is certainly the right track.