You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python彩票球概率计算报错:name 'n' is not defined及相关疑问

问题解决:NameError: name 'n' is not defined 及阶乘方法疑问

报错原因分析

你代码里的win = winning(n, p)写在了main()函数外面,此时变量n和p还未定义——这两个变量是在main()函数内部通过用户输入才创建的,Python运行到这行时找不到对应变量,因此抛出NameError。

修正后的代码

把调用winning()函数的逻辑移到main()函数内部,且放在输入验证之后,确保只有合法输入时才计算概率:

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))
    return 1 / a

def main():
    n = int(input("Enter the total number of lottery balls: "))
    p = int(input("Enter the number of the drawn balls: "))
    
    # 调整输入验证为多分支,避免合法输入时触发错误提示
    if n < 1:
        print("The number of balls must be a positive number.")
    elif p > n:
        print("At most the total number of balls can be drawn.")
    elif p < 1:
        # 补充抽取球数的合法性验证
        print("The number of drawn balls must be a positive number.")
    else:
        win_prob = winning(n, p)
        print(f"The probability of guessing all {p} balls correctly is {win_prob}")

main()

原代码的输入验证存在逻辑漏洞:比如n<1时,即使p>n也会同时打印两个错误提示,改成elif分支可避免该问题,同时补充了p为非正数的验证逻辑。

关于math.factorial()的疑问

完全可以用math.factorial()计算阶乘,这也是推荐用法:

  • 它是Python标准库的官方实现,底层用C编写,计算效率远高于自己用递归或循环实现的阶乘函数;
  • 天然支持Python大整数类型,不用担心溢出问题;
  • 自带参数校验,传入负数会直接抛出ValueError,无需额外处理非法输入。

除非你有特殊需求(比如自定义阶乘逻辑、学习阶乘实现原理),否则直接用math.factorial()就足够了。

内容的提问来源于stack exchange,提问作者emkay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 22:27:28