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. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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)

30th May 2019, 11:16 AM
cody stephens
cody stephens - avatar
4 Answers
+ 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())
30th May 2019, 11:58 AM
Anna
Anna - avatar
+ 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
30th May 2019, 12:03 PM
Anna
Anna - avatar
+ 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)
30th May 2019, 11:40 AM
cody stephens
cody stephens - avatar
+ 1
Thank you modus, its working. I appreciate it
30th May 2019, 11:51 AM
cody stephens
cody stephens - avatar