Python Forum
help on first function - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: help on first function (/thread-33466.html)



help on first function - jip31 - Apr-27-2021

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


RE: help on first function - ndc85430 - Apr-27-2021

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.


RE: help on first function - jip31 - Apr-28-2021

So what I have to do for make this function working please?


RE: help on first function - raarkil - Apr-28-2021

import random
>>> def rand():
for i in range(6): 
…   return random.randint(1,40)
 
>>> x = rand()
print(x)
I suppose you want this


RE: help on first function - snippsat - Apr-28-2021

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
>>>



RE: help on first function - jip31 - Apr-28-2021

(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


RE: help on first function - jip31 - Apr-28-2021

(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!!