Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
help on first function
#1
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
Reply
#2
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.
Reply
#3
So what I have to do for make this function working please?
Reply
#4
import random
>>> def rand():
for i in range(6): 
…   return random.randint(1,40)
 
>>> x = rand()
print(x)
I suppose you want this
Reply
#5
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
>>>
Reply
#6
(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
Reply
#7
(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!!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020