Python Forum

Full Version: help on first function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi
Is anybody can tell me why the function below dont works because if I just execute the for loop I have results
import random
>>> def rand():
for i in range(6): 
…	random.randint(1,40)
…     print()

>>> rand()
Thanks in advance
You aren't printing anything - you just throw away the value returned by randint.

Note that without the function, the value is printed only because you're at the REPL - its job is to print out the value of expressions ('P' in 'REPL' is for "print"). If you had written the loop in a script and run it, you'd see nothing printed.
So what I have to do for make this function working please?
import random
>>> def rand():
for i in range(6): 
…   return random.randint(1,40)
 
>>> x = rand()
print(x)
I suppose you want this
If run as script .py file and not in REPL then there is no >>>.
import random

def rand():
    for i in range(6):
        print(random.randint(1, 40))

rand()
Output:
22 35 8 12 21 29
if it's longer code with functions it can be better to run it as a script.
In REPL it would be like this.
>>> import random
>>> 
>>> def rand():
	for i in range(6):
		print(random.randint(1, 40))

		
>>> rand()
22
2
12
14
29
26
>>>
(Apr-28-2021, 12:55 PM)raarkil Wrote: [ -> ]
import random
>>> def rand():
for i in range(6): 
…   return random.randint(1,40)
 
>>> x = rand()
print(x)
I suppose you want this

No
What I need is to execute the function rand() - so it means to pick up 6 numbers randomly and to display it and after to call this function separately
Your code works but I have to do 6 entry for having 6 results
(Apr-28-2021, 01:28 PM)snippsat Wrote: [ -> ]If run as script .py file and not in REPL then there is no >>>.
import random

def rand():
    for i in range(6):
        print(random.randint(1, 40))

rand()
Output:
22 35 8 12 21 29
if it's longer code with functions it can be better to run it as a script.
In REPL it would be like this.
>>> import random
>>> 
>>> def rand():
	for i in range(6):
		print(random.randint(1, 40))

		
>>> rand()
22
2
12
14
29
26
>>>


Perfect, many thanks!!