python-3.x 如何将int变量与返回int的函数进行比较

yxyvkwin  于 2023-08-08  发布在  Python
关注(0)|答案(2)|浏览(105)

我试图使代码(我偷来的)输出斐波那契序列,我遇到了麻烦,让函数Terms能够与变量进行比较。我知道这是混乱的代码,但我喜欢3天进入python,所以我不知道该怎么办。

# 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()

字符串
我试着用int来表示术语,但还是不行

bxjv4tth

bxjv4tth1#

有几件小事。所以你从几个地方调用了不同的函数。因此,我删除了一些调用,并将ReturnValue从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

# Calls Terms then generates
def Fibonacci():
   # first two terms
   n1, n2 = 0, 1
   count = 0
   terms = Terms() # This is the new variable
   print("Fibonacci sequence:")
   while count < terms: # And using the variable here
      print(n1)
      nth = n1 + n2
     # update values
      n1 = n2
      n2 = nth
      count += 1
Fibonacci()

字符串

kxe2p93d

kxe2p93d2#

解决办法可能是

while count < Terms():

字符串
错误消息明确地告诉您,您不能与函数进行比较(而是与函数结果进行比较)。(但是在这个修复之后,你会遇到另一个问题...)
替代实施方式:

# Query the number of terms
while True:
    try:
        n = int(input("How many terms [integer > 1] ? "))
        if n > 1:
            break
    except:
        pass
    print("Invalid input, try again")

# Output the desired number of terms
f0, f1= 0, 1
for i in range(n):
    print("F"+str(i)+" =", f0)
    f0, f1= f1, f0+f1

相关问题