Dear respected coders,
I have a question regarding my code which is not working. Actually, I want to generate random numbers which should be presented in a list, whenever I call the function. Could someone please help me clarifying what goes wrong here and how to continue? I am a bit confused right now.
This is the error message I got:
TypeError: RandomNumbers() missing 1 required positional` argument: 'Number'
I understand, but I do not want to enter a number, it should output me a random list consisting of 7 elements with elements varying between 0 and 9. For example: [2,3,5,0,2,0,9)
import random
Number = []
def RandomNumbers(Number):
for i in range(0,7):
x = Number.randint(0,9)
Number.append(x)
print(Number)
RandomNumbers()
CodePudding user response:
Considering you've mentioned that you do not want to input any numbers, change your Python function declaration to not take in any arguments - Number
in this case - as it currently expects one.
You also need to replace x = Number.randint(0,9)
with x = random.randint(0,9)
as randint
is a method belonging to random
.
This should do what you want:
import random
Number = []
def RandomNumbers():
for i in range(0,7):
x = random.randint(0,9)
Number.append(x)
print(Number)
RandomNumbers()
Output:
[1, 7, 6, 5, 5, 7, 5]
There's also a smaller, cleaner solution, which achieves the same output as above using list comprehensions:
import random
Number = [random.randint(0,9) for _ in range(7)]
print(Number)
CodePudding user response:
just replace the last line of code
RandomNumbers()
with
RandomNumbers(ANYNUMBER)
CodePudding user response:
You can't call a function that receives object without it. so you could do this:
import random
Number = []
def RandomNumbers():
for i in range(0,7):
x = random.randint(0,9)
Number.append(x)
return Number
print(RandomNumbers())
CodePudding user response:
You have to change Number.randint
to random.randint
. The corrected code looks like that:
import random
Number = []
def RandomNumbers(Number):
for i in range(0,7):
x = random.randint(0,9)
Number.append(x)
print(Number)
RandomNumbers(Number)
Output:
[9]
[9, 1]
[9, 1, 5]
[9, 1, 5, 8]
[9, 1, 5, 8, 3]
[9, 1, 5, 8, 3, 9]
[9, 1, 5, 8, 3, 9, 2]
But this code is not cleaned up at all. You can instead learn about the module numpy
which has great functions including creating arrays with random integers!
CodePudding user response:
import random
def RandomNumbers():
arr = []
for i in range(0,7):
x = random.randint(0,9)
arr.append(x)
return(arr)
Number = RandomNumbers()
print(Number)
Use random.randint(0,9) instead of Number.randint(0,9)
You probably want to use this function more than once so it is advisable to declare an array inside the function.