+ 1
How can i put a random num gen in a function so i don't have to keep typing out random.randint for every variable.
i've tried using the return function as well as putting the var = function but it comes back with an error that the var is not defined and I've tried looking through the modules. Heres the code im working with: import random def max(num): num = random.randint(1,100) return num print(max(num)) z = max(num) print(z)
4 Respuestas
+ 3
1)
from random import randint as rd
print(rd(1, 100))
print(rd(1, 100))
2)
from random import randint
rd = lambda: randint(1, 100)
print(rd())
print(rd())
+ 3
cody stephens Change the last two lines of your code to
a = numbers(1)
print(*a)
to actually print the number instead of the name of the generator function
+ 1
addition:
I've done this and it works for putting it in list (1st code) format but when i take away the list portion to assign just a variable i get a return of something along the lines of <generater object number at 0x622237> (2nd code)
import random
def numbers(x):
for i in range(x):
i = random.randint(1,100)
yield i
print(list(numbers(1)))
a = (list(numbers(1)))
print (a)
----------------------------------
import random
def numbers(x):
for i in range(x):
i = random.randint(1,100)
yield i
print(list(numbers(1)))
a = (list(numbers(1)))
print (a)
+ 1
Thank you modus, its working. I appreciate it