I have multiple functions, the first one generates a random number, the others use the value of the first one. But I want to fix the return value of the first function and use it in the rest of my code
how can I do this without the random changes every time I call the other functions?
import random
def list():
return [i for i in range(1, 11)]
def fun1():
return random.choice(list())
def fun2():
return 2 + fun1()
def fun3():
return 4 + fun1()
print(fun2(), fun3())
Related
i want use loop correctly inside function
This is my code :
def test():
for i in range(1,10):
return i
def check():
print(test())
check()
output is 1
i want to full iteration
output : 1 ,2,4....10
When you return inside a function, it immediately terminates the function and returns the specified value. This means that it goes into the for loop and returns 1, then stops running. One way to get around this is to use the yield keyword instead of return.
def test():
for i in range(1, 10):
yield i
This will make test() a generator, which can then be printed in check by unpacking its values.
def check():
print(*test())
Alternative ways of doing this would be to return a list in test() or to simply print the values within test() itself.
In Python (as with almost all programming languages), functions can only return once (ish). As soon as Python encounters return, it'll exit the function.
Python does have a feature called "generators", though: with the yield keyword, you can (sort of) return more than once:
def test():
for i in range(1,10):
yield i
To expand those values to the print function's arguments, use * like so:
def check():
print(*test())
>>> check()
1 2 3 4 5 6 7 8 9
>>> sum(test())
45
wim points out that you can sometimes return more than once from a function – but later return statements will "replace" the return value from earlier ones.
>>> def f():
... try:
... return 1
... finally:
... return 2
...
>>> f()
2
Unfortunately, CPython's optimising this too much for me to make sense of the dis bytecode decompilation; I have no idea how this works under the hood.
If you want to return all the values in the range you can do something like this:
def test():
return [i for i in range(1,10)]
def check():
print(test())
check()
I have the following code:
class MyClass:
def __init__(self):
self.some_variable = None
def func1(self):
i = 1
while i < 10:
yield i * i
self.some_variable = len(str((i * i)))
i += 1
def func2(self):
*_, last = my_class.func1()
print(self.some_variable)
my_class = MyClass()
my_class.func2()
As you can see, some_variable is the length of the last element in the generator. Basically, I was wondering, is this the most pythonic way of getting this variable? If not, how should this be done? I'm just wondering if this is how it should be done or if there's a better way of doing this.
Probably the simplest code is to simply use a for loop to consume the generator, doing nothing in the loop body. The loop variable will have the last value from the generator after the loop ends, which is exactly what you want.
for x in some_generator():
pass
print(x) # print the last value yielded by the generator
This may be a little more efficient than other options because it discards all the values before the last one, rather than storing them in a list or some other data structure.
I think that one pythonic way would be to yield both the element and the length:
def func1():
i = 1
while i < 10:
yield i * i, len(str((i * i)))
i += 1
def func2():
*_, (_, last_len) = func1()
print(last_len)
func2()
or even to extract the calculation of the derived value to another function and call it after consuming the generator:
def func1():
i = 1
while i < 10:
yield i * i
i += 1
def func2(i):
return len(str(i))
def func3():
*_, last = func1()
print(func2(last))
func3()
I think that you have simplified your example too much to be able to find the solution that fits your real use case the best.
I was asked to create a function to give a square of a value. Here is the defined function:
def square(x):
print(x**2)
secondly I was asked to define another function to check weather the number is odd or even:
def oddeve(x):
if x % 2 == 0:
print ("{} is even".format(x))
else:
print ("{} is odd".format(x))
However now they want me to use both the function together to check whether the square is odd or even. Can anyone help me with how to combine two pre defined functions?
You can simply call one function inside of the other function. However, this requires that you don't print out the value, but rather return it:
def square(x):
return(x**2)
Now you can simply call:
oddeve(square(x))
For example, if x = 4, square(4) returns 16, and oddeve(16) prints out that it is even.
I want to achieve this
for i in range(1,10):
print(i)
but using different functions, by putting values of for-loop to variable named valuee and then as an argument to clamp function then printing it. Why am I getting just 1? and not from 1->9?
def clamp(valuee):
print(valuee)
def value():
for i in range(1,10):
return i
valuee=value()
clamp(valuee)
If you use return you will end the function. You are looking for a generator; just change the return for yield.
def clamp(valuee):
print(valuee)
def value():
for i in range(1,10):
yield i
You can use your generator in 2 ways: inside a loop
for valuee in value():
clamp(valuee)
Or as you originally wanted, but you have to add the keyword next:
def clamp(valuee):
print(valuee)
def value():
for i in range(1,10):
yield i
valuee = value()
clamp(next(valuee))
clamp(next(valuee))
clamp(next(valuee))
...
It is not printing all the values because in value() method you are using return and when i=1 in loop, value() returns 1 and exits from the function and loop too.
you can use ...
def clamp(valuee):
print(valuee)
def value():
for i in range(1,10):
clamp(i)
value()
>>> import math
#defining first function
>>> def f(a):
return a-math.sin(a)-math.pi/2
#defining second fuction
>>> def df(a):
return 1-math.cos(a)
#defining third function which uses above functions
>>> def alpha(a):
return a-f(a)/df(a)
How to write a code in which alpha(a) takes a starting value of a=2, and the solution of alpha(2) will become the input the next time. For eg: let's suppose alpha(2) comes to 2.39 , hence the next value would be alpha(2.39) and go on {upto 50 iterations}. Can somebody please help me a bit. thanks in advance.
You can let the program iterate with a for loop, and use a variable to store the intermediate results:
temp = 2 # set temp to the initial value
for _ in range(50): # a for loop that will iterate 50 times
temp = alpha(temp) # call alpha with the result in temp
# and store the result back in temp
print(temp) # print the result (optional)
print(temp) will print the intermediate results. It is not required. It only demonstrates how the temp variable is updated throughout the process.
You can objectify it.
import math
class inout:
def __init__(self, start):
self.value = start
def f(self, a):
return a-math.sin(a)-math.pi/2
def df(self, a):
return 1-math.cos(a)
def alpha(self):
self.value = self.value-self.f(self.value)/self.df(self.value)
return self.value
Then create an inout object and each time you call its alpha method it will give the next value in the series.
demo = inout(2)
print(demo.alpha())