请原谅我初学者的错误:)我有一项任务要求我找出用户输入的总彩票和抽奖球的概率。我的代码也很可能有其他错误,但我无法通过错误代码,即n是没有定义的。这就是我所拥有的:
import math
def winning(n, p):
"""Find the probability of guessing all balls correct"""
a = math.factorial(n)/(math.factorial(n - p) * math.factorial(p))
b = 1/a
return b
win = winning(n, p)
def main():
n = int(input("Enter the total number of lottery balls:", ))
# number of balls
p = int(input("Enter the number of the drawn balls:", ))
# number of balls drawn
if p > n:
print("At most the total number of balls can be drawn.")
if n < 1:
print("The number of balls must be a positive number.")
else:
print("The probability of guessing all", p, "balls correctly is", win)
main()另外,math.factorial()是一种在Python中使用阶乘的工作方式,还是应该使用其他东西?
发布于 2022-07-16 21:28:35
你在打电话给赢(n,p),而事先没有定义n或p。正如Tim提到的,将调用移动到Tim(n,p)到main()定义之后,就意味着在用户声明n和p之后调用它。
例如,以下内容会产生错误:
def sum(a, b):
return (a + b)
sum(a, b)
a = int(input('Enter 1st number: '))
b = int(input('Enter 2nd number: '))鉴于以下情况并非如此:
def sum(a, b):
return (a + b)
a = int(input('Enter 1st number: '))
b = int(input('Enter 2nd number: '))
sum(a, b)https://stackoverflow.com/questions/73007682
复制相似问题