I am trying to compute the probability of rolling a dice n number of times and finding the average.Its basically a Monte Carlo problem. I am new to coding so if someone can help I would really appreciate it.
import random
import sys
num = int(sys.argv[1])
roll =random.randint(1,6)
sum=0
for roll in range(0,num):
sum = sum + int(input())
average = sum / num
print('the average is: ',average)
-
What exactly are you trying to do on the error line? Are you trying to get input from the user, and if so what are you trying to use it for?M-Chen-3– M-Chen-32020年10月02日 23:53:39 +00:00Commented Oct 2, 2020 at 23:53
-
1"asap" ? Is this a homework problem with a deadline? In general "asap" gets a negative reaction on Stack Overflow. You are asking for help, don't demand it on your time schedule. Also, "I am having issues with my code" is vague. What are the issues that you are having?John Coleman– John Coleman2020年10月02日 23:56:39 +00:00Commented Oct 2, 2020 at 23:56
-
@JohnColeman I am sorry for my language, I was just trying to get attention. I am trying to learn python on my own and I am stuck in this particular code for a while. I am also new to the forum. Excuse me again sir. I seriously didn't mean to offend anyone or be meanuser14382501– user143825012020年10月02日 23:59:54 +00:00Commented Oct 2, 2020 at 23:59
-
@M-Chen-3 I am trying to add up the random rolled number. I am not trying to get an input. I think I did a mistakeuser14382501– user143825012020年10月03日 00:02:57 +00:00Commented Oct 3, 2020 at 0:02
1 Answer 1
There are a bunch of issues here.
You should only use the
input()function when you want to prompt the user for input. Here that is not the case.You want the print statement outside of the loop, not inside the loop.
[A minor stylistic point] You should not name a variable "
sum", since that is a built-in function name, and it's not good form. You can do it, but if afterwards you want to use the actualsum()function, you'll run into problems.
I think this is what you intended:
import random
import sys
num_rolls = int(sys.argv[1])
rolls = [random.randint(1, 6) for i in range(num_rolls)]
print('the average is: {}'.format(sum(rolls) / num_rolls))
4 Comments
sum(rolls) adds up all the items in rolls. Then sum(rolls) / num_rolls divides the sum by the number of objects, calculating the average. Then the format() function basically plugs the result into the curly braces (due to how formatted strings work).