2017-02-21 42 views
0

所以我嘗試使用input號碼打印斐波那契序列。我不知道如何在我的代碼中輸入數字。從輸入號碼打印斐波那契

def fibonacci(n): 
    a,b=0,1 
    while(a<n): 
     print(a,end=' ') 
     a,b=b,a+b 
    print() 

fibonacci(fibo_entry=input("enter number")) 

我得到這個錯誤:

TypeError               Traceback (most recent call last) 
    <ipython-input-113-d552685b93df> in <module>() 
     7   a,b=b,a+b 
     8  print() 
    ----> 9 fibonacci(fibo_entry=input("enter number")) 

    TypeError: fibonacci() got an unexpected keyword argument 'fibo_entry' 

回答

4

TypeError是因爲你的功能不採取fibo_entry -argument。你可以這樣調用它:

fibonacci(input("enter number")) 

但是這會給你一個錯誤,因爲input總是返回上python3一個字符串,所以你需要將其轉換爲數值:

import ast 
fibonacci(ast.literal_eval(input("enter number"))) 

或明確:

fibonacci(int(input("enter number"))) 

不過,我會建議捕捉輸入作爲獨立變量,只是變量傳遞給函數:

fibo_entry = int(input("enter number")) 
fibonacci(fibo_entry) 
+0

非常感謝!顯式方法起作用並且看起來很簡單。 –

+0

@KrithikaKrishnan沒問題。請不要忘記[接受](http://stackoverflow.com/help/accepted-answer)/ upvote有用的答案。 :) – MSeifert

+0

嗨@KrithikaKrishnan *如果*答案解決了您的問題,如您所示,請考慮接受答案(在左側上/下箭頭下方勾選大「V」)。這是指出答案適用於您的適當方式,並增加您未來可以獲得良好答案的機會。 –

1

在這一行中,python解釋器認爲你試圖爲fibonacci指定一個參數。

fibonacci(fibo_entry=input("enter number")) 

最簡單的解決方法是分離出來。你也必須轉換爲int,因爲輸入返回一個字符串:

fibo_entry=int(input("enter number")) 
fibonacci(fibo_entry) 
0

你需要使用類型轉換爲你「輸入」功能, 這樣做:

num=int(input("enter number: ")) 
fibonacci(num) 

或做這樣的:

fibonacci(int(input("enter number: ")))