def subtract1(a, b):
return a - b
if random.randint(0,100) < 99:
print("Yes")
print(subtract(20, 10)
I have tried many different ways of using a random number gen but can't seem to find one that works. I am now quite sure that it has to do something with the other code but I'm not sure what.
When you call your function in the print statement you have [print(subtract(number1, number2)]. Your function is named subtract1 so try to call subtract1 instead of subtract as the function name. Plus the return statement is stopping it before it reaches the if statement.
editing the function as the following way will solve your problem
Note that for any function the return statement always ends the function
and any other lines written in the function body after the return statement will never be compiled. also you call the function with the same name of its defination
import random
def subtract(a, b):
if random.randint(0,100) < 99:
print("Yes")
return a - b
print(subtract(20, 10))
By calling return immediately at the beginning of the function it returns the value you passed (a-b) and won't pass to the rest of the code.
if you want to print a-b before running the code below you can look at yield:
import random
def subtract(a,b):
yield a-b
if random.randint(1,100) < 99: print("yes")
print(subtract(20,10))
I can't understand what's your intention but if what I'm thinking is right,
your code should be like this
def subtract1(a, b):
if random.randint(0,100) < 99:
print("Yes")
return a - b
print(subtract(20, 10))
return statement returns the return value and at the same time ends the function.
So if it were for you to print the subtracted value first and print Yes later,
it has to be like this
def subtract1(a, b):
return a - b
print(subtract(20, 10))
if random.randint(0,100) < 99:
print("Yes")
Related
def sum_factor(num,base):
while num>=base:
if num==base:
return "Yes"
num=num/base
sum_factor(num/base,base)
return "Nope"
print(sum_factor(12,2))
I already see that this code is wrong - inside while you don't change num so this loop will run forever. But using while you will create normal function without recursion. In recursion you rather need only if/elif/else.
And in recursion you have to use retun sum_factor(num/base, base) to return value to previous executed sum_factor() which will return it to previous executed sum_factor(), etc.
Something like this:
def sum_factor(num, base):
if num == base:
return "Yes"
if num < base:
return "Nope"
#if num > base:
# return sum_factor(num/base, base)
return sum_factor(num/base, base)
# --- main ---
print(12, 2, sum_factor(12, 2))
print(16, 2, sum_factor(16, 2))
print(9, 2, sum_factor(9, 2))
I was trying to make variables inside a loop. i.e. I pass a pattern of variables, and the pattern of their values and the variables are accordingly created and stored in a text file.
But, I tried something off topic and did this:
a = lambda a: a
for i in ["a", "b"]:
b = eval(i)(a)
print(i)
the output was:
a
b
Can anyone please explain what has happened here?
Edit:
I have analysed its answer.
I will paste it below.
Please verify if it is correct.
Thank you!
Lets first break the problem in parts.
def a(n):
return n
b = eval("a")(a)
print("a")
b = eval("b")(a)
print("b")
We can clearly see that the output is due to the two print statements.
print("a")
print("b")
Thus the rest of the statements play no part in the output.
def a(n):
return n
b = eval("a")(a)
b = eval("b")(a)
These statements can simply be put across like this:
def a(n):
return n
b = a(a)
b = b(a)
The statement
b = a(a)
makes the same effect as
def b(n):
return n
Thus the entire code can be put across like this:
def a(n):
return n
def b(n):
return n
print("a")
print("b")
Thus there is no ambiguity in this question now.
Here's how you can deconstruct your loop to understand for yourself, and please don't do that as pointed out in the comment.
a = lambda a: a
# First iteration
i = "a"
b = eval(i)(a)
print(i) # a
# Second iteration
i = "b"
b = eval(i)(a) # eval("b") is now <function __main__.<lambda>(a)>
print(i) # b
You are printing the variable i (which takes the values "a" and "b" since you loop over ["a", "b"]). If you want to see which values the variable b takes, print b instead:
a = lambda a: a
for i in ["a", "b"]:
b = eval(i)(a)
print(b)
Lets first break the problem in parts.
def a(n):
return n
b = eval("a")(a)
print("a")
b = eval("b")(a)
print("b")
We can clearly see that the output is due to the two print statements.
print("a")
print("b")
Thus the rest of the statements play no part in the output.
def a(n):
return n
b = eval("a")(a)
b = eval("b")(a)
These statements can simply be put across like this:
def a(n):
return n
b = a(a)
b = b(a)
The statement
b = a(a)
makes the same effect as
def b(n):
return n
Thus the entire code can be put across like this:
def a(n):
return n
def b(n):
return n
print("a")
print("b")
Thus there is no ambiguity in this question now.
please keep in mind that while I showcase my code, that I am fairly new to programming. So please forgive any problems. I am writing a piece of python code that uses the output of one function and then averages it in another function. I am having troubling proceeding on how to do that, this is what I have so far:
def avg(A):
if not A:
return 0
return sum(A) / len(A)
Using the function above, I have to use it to calculate the average of the function produced below:
def SampleFunction(): # Example Function
A = list(range(300))
for i in range(300):
if i%2:
A[i] = 3.1*(i+1)**1.2 - 7.9*i
else:
A[i] = 4.2*(i+2)**.8 - 6.8*i
return A
Below this is a function I have trying to tie the two together.
def average(SampleFunction):
if len(SampleFunction) == 0: return 0
return sum(SampleFunction) / len(SampleFunction)
def avg(A):
if not A:
return 0
return sum(A) / len(A)
def SampleFunction(): # Example Function
A = list(range(300))
for i in range(300):
if i%2:
A[i] = 3.1*(i+1)**1.2 - 7.9*i
else:
A[i] = 4.2*(i+2)**.8 - 6.8*i
return avg(A) #Return the avg of A instead of just A
You are right at the moment of passing SampleFunction as parameter, but it's a function, you have to call invoke it inside average():
def average(some_function):
result = some_function() # invoke
return avg(result) # use the already defined function 'avg'
When you call it, pass the function you want to average():
print average(SampleFunction)
Note:
I would recommend you to follow Python naming conventions. Names like SomeName are used for classes, whereas names like some_name are used for functions.
This is my first time around, so i would appreciate your patience with what might appear as a lame looking question :)
I'm trying to write a function called do_n that takes a function object and a number, n, as arguments and then call the given function n times. Here's the code:
def name():
print 'Jack'
def do_n(fo, x):
if x <= 0:
return
print fo
(fo, x-1)
When making a function call from within main:
do_n(name, 3)
I get the following outcome:
<function name at 0x01F93AF0>
I'm trying to get the program to print out:
Jack
Jack
Jack
Many thanks in advance
You are neither calling the function, nor are you actually doing the recursive call. Corrected version:
def name():
print 'Jack'
def do_n(fo, x):
if x <= 0:
return
fo()
do_n(fo, x - 1)
To call a function n times, you'd usually use a for loop instead of tail recursion in Python:
for dummy in range(10):
name()
Functions are first-class objects in Python.
fo()
I have a function that returns a number. I want to assign a variable to have this value, but python gives a runtime error when I say temp = foo(i, j) : NameError: name 'foo' is not defined. Note that I've changed the function bodies of bar and foo around, obviously having a function that just returns 1 is useless, but it doesn't change my error.
sum = 0
for i in range(2, 100):
for j in range(2, i):
temp = foo(i, j)
if (temp > 100):
sum = sum + 1
print sum
def bar (n, a):
r = 1
return r
def foo (n, a):
s = bar(n, a)/factorial(5);
return s
def factorial (n):
r = 1
for i in range (2, n + 1):
r *= i;
return r
Names in Python do not exist until they are bound. Move the def foo(...): block above the code that uses foo().
Your definition of foo is AFTER you use it in the file. Put your function definition above the for loop.
As per other answers, your issue is the order in which you run your code: foo hasn't been defined yet when you first call it. Just wanted to add a comment about best practices here.
I always try to put everything in a function and then call any scripts at the bottom. You've probably encountered this pattern before, and it's a good habit to get into:
CONSTANT = 5
def run():
for i in xrange(CONSTANT):
print foo(i) # whatever code you want
def foo(n):
# some method here...
pass
if __name__ == "__main__":
run()
if you run this with python script.py or by hitting f5 in idle, run() will be executed after everything is defined.
By following this pattern you don't have to worry about the order you define your functions in, and you get the added benefit of being able to import foo with other functions without having your script execute during the import, which is probably not a desired behavior.