Python中如何将整数变量与返回整数的函数比较?斐波那契代码报错
解决斐波那契数列代码中函数调用的问题
我正在修改一段借鉴来的斐波那契数列生成代码,目前遇到一个问题:没办法让返回整数的Terms()函数和变量进行比较。我知道代码写得很乱,但刚接触Python3天,不知道该怎么解决。我尝试把terms转为整数,但还是没用。
原代码:
# first two terms n1, n2 = 0, 1 count = 0 # Asks amount of terms to be generated def Terms(): while True: nterms = (input("How many terms? ")) if nterms.isdigit(): nterms= int(nterms) if nterms > 0: break else: print("0") else: print("Please choose an number that is able to be used") return nterms Terms() # Calls Terms then generates print(int(Terms)) def Fibonacci(): # first two terms n1, n2 = 0, 1 count = 0 Terms() print("Fibonacci sequence:") while count < Terms: #Problem right here TypeError: int() argument must be a string, a bytes-like object or a real number, not 'function' print(n1) nth = n1 + n2 # update values n1 = n2 n2 = nth count += 1 Fibonacci()
问题原因和修改方案
核心错误:你把函数本身(
Terms)当成了函数的返回值。在Python里,函数名不加括号代表的是函数对象,只有加括号调用(Terms())才能执行函数并拿到它返回的整数。具体修改步骤:
- 调用
Terms()时,把返回的结果存到变量里,比如num_terms = Terms(),后续所有需要用到这个数值的地方都用这个变量。 - 删掉
print(int(Terms))这行无效代码,正确的写法是先存变量再打印,或者直接print(Terms())。 - 在
Fibonacci()函数里,先获取用户输入的项数并存到变量,再用这个变量和count做比较。
- 调用
修改后的完整代码:
# Asks amount of terms to be generated def Terms(): while True: nterms = input("How many terms? ") if nterms.isdigit(): nterms = int(nterms) if nterms > 0: break else: print("请输入大于0的数字") else: print("请输入有效的数字") return nterms def Fibonacci(num_terms): # first two terms n1, n2 = 0, 1 count = 0 print("斐波那契数列:") while count < num_terms: print(n1) nth = n1 + n2 # update values n1 = n2 n2 = nth count += 1 # 先获取项数,再传入斐波那契函数 num_terms = Terms() Fibonacci(num_terms)
内容的提问来源于stack exchange,提问作者MapleTofu
相关产品推荐
相关产品推荐

