Python函数调用出现‘函数未定义’错误问题咨询(含组合数代码)
Python函数调用问题解答
Hey there, let's break down your two Python questions one by one, with a focus on solving your specific combination calculation issue first.
1. Why do I get a "function not defined" error when calling one function from another?
This error pops up for a few common reasons in Python:
- You called the function before defining it: Python runs code top to bottom. If you try to run
my_function()before writingdef my_function(): ..., the interpreter hasn't seen the function yet, so it throws the error. - Scope mismatch: If the function you're trying to call is nested inside another function or a class, it might not be accessible in the scope where you're calling it. For example, a function defined inside
main()can't be called directly outsidemain()unless you explicitly expose it. - Typos: Double-check that the name you're using to call the function matches exactly how you defined it (Python is case-sensitive!). A tiny typo like
factorials()instead offactorial()will trigger this error. - Missing imports: If the function lives in a different module, you need to import it first (e.g.,
from my_module import factorialorimport my_modulethen callmy_module.factorial()).
2. Fixing the "name 'factorial' is not defined" error in your combination code
Your factorial works alone but breaks when called from choose—here's the most likely fix and some improvements:
The root cause
The most common issue here is incorrect code order or indentation:
- Make sure your
factorialfunction is defined before thechoosefunction. Python needs to know aboutfactorialbeforechoosetries to use it. - Double-check that
factorialisn't accidentally indented inside another code block (like anifstatement, loop, or another function). If it's nested,choosecan't see it from the outer scope.
Corrected code example
Here's your code with the proper structure to work as expected:
def factorial(number): x = 1 y = 2 while y <= number: x *= y y += 1 return x def choose(n, k): # Add a quick check to avoid invalid inputs (like k > n or negative values) if k < 0 or k > n: return 0 total = factorial(n) / (factorial(k) * factorial(n - k)) return total # Call the function AFTER both are defined print(choose(5, 2)) # Outputs 10.0
Bonus improvements
- Use integer division (
//) instead of/if you want an integer result (since combinations are whole numbers):total = factorial(n) // (factorial(k) * factorial(n - k)) - For a more robust solution, use Python's built-in
math.factorialwhich handles edge cases (like 0! = 1) automatically:import math def choose(n, k): if k < 0 or k > n: return 0 return math.factorial(n) // (math.factorial(k) * math.factorial(n - k))
内容的提问来源于stack exchange,提问作者Gabriel Gunnink
相关产品推荐
相关产品推荐

