Python: How do I get this function to print?
#integers to be input
n = input('Enter \"n\" trials')
x = input('Enter \"x\" number of succeses')
p = input('Enter the probability \"p\" of success on a single trial')
#Probability Distribution function
def probDist(n, x, p):
q = (1-p)**(n-x)
numerator = math.factorial(n);
denominator = math.factorial(x)* math.factorial(n-x);
C = numerator / denominator;
answer = C*p**x*q;
return answer
# Does this have to come after I define the function? Or does this matter in Python
# Also this part just doesn't work.
dist = probDist(n, x, p);
print(dist);
Here's the error that I get after I run and I input all the values.
Traceback (most recent call last):
line 17, in <module>
开发者_C百科dist = probDist(n, x, p);
line 9, in probDist
q = (1-p)**(n-x)
TypeError: unsupported operand type(s) for -: 'int' and 'str'
In Python 3.x, input
always returns a string, without applying eval
the the user input. Python 2.x input
does eval
, but that's rarely what you want. If you want an integer, use int(input(...))
and if you want a float (not quite the same as a real number, as it has only limited range!), use float(input)
. (You should propably catch ValueError
to handle the cases where the input is not appropiate; if this is for exercise/education, it's propably okay to leave error handling out for now.)
Does this have to come after I define the function?
Yes.
q = (1-p)**(n-x)
TypeError: unsupported operand type(s) for -: 'int' and 'str'
You have two -
operations. One of those two is a mixture of int
and str
data.
Let's go through each operand.
1 - int
p - result of input()
, and therefore a string
n - result of input()
, and therefore a string
x - result of input()
, and therefore a string
You probably want to do something to convert the results of input()
to a proper floating-point value. float()
works well for this.
精彩评论