2013-11-26 182 views
0

我似乎無法獲得多次顯示的用戶輸入。例如,如果輸入的是Python 2.7.5,在函數中使用循環並調用函數

Jeff 6 

輸出應該

Jeff 
Jeff 
Jeff 
Jeff 
Jeff 
Jeff 

我新的功能在Python,但這裏是我的代碼至今:

def getName(): 
    name = raw_input("please enter name") 
    return name 

def getRepval(): 
    irepnum = float(raw_input("please enter number to show name entered")) 
    return irepnum 

def inamed(name, irepnum): 
    count = 1 #the loop to show the name entered by the user 
    while irepnum != count: 
     print name 
     count += 1 #do I need to use return?? 

def main(): #having the main func like this gives me an infinite loop 
    irepnum = 0 

    iname = getName() #I think my problem is somewhere here. 

    irepnum = getRepval() 

    inamed(irepnum,name) 

main() 
+0

你的預期產出是什麼,你得到的是什麼產出?你說你得到這個名字有問題,但不要說出問題所在。我懷疑問題是當你調用inamed時irepnum <1,所以該函數中的循環永遠不會結束。對於像這樣的循環使用少於條件的做法是很好的做法,以防止可能出現的超出範圍的錯誤,例如使用'while count

+0

我的錯,當我有一個無限循環時運行代碼 – JuanB457

+0

我可以閱讀。你將不得不更具描述性。 –

回答

1

你需要撥打inamed(iname, irepnum),而不是inamed(irepnum, name),因爲您現在正在進行此操作。

以外的name沒有被定義(實際變量稱爲iname),以錯誤的順序引起irepnum在功能設置爲用戶輸入的姓名字符串的明顯錯誤。由於count,無論多大,永遠不會等於傳遞的字符串,代碼無限循環。

幾個小竅門:

  • 學習使用for循環和xrange。你想要的成語是for count in xrange(irepnum):。 (使用它可以防止此錯誤。)

  • 爲您的標識符提供更多獨特的名稱。目前您有一個inamed函數和一個iname變量。混亂。

  • 不要使用漂浮在int就足夠。錯用花車是在尋求麻煩。

+0

感謝您的答案,我將所有這些數據從具有不同於python的語法的流程圖工具中移出,我沒有記錄所有變量,但感謝您糾正錯誤。 – JuanB457