2017-09-04 54 views
-1

我聲明瞭一個空列表並詢問用戶輸入,以便我可以將其附加到列表中。我還保留了一個計數器,讓用戶在列表中告訴他們想要的最大數量的術語。但是當我運行該程序時,while循環不起作用,比較無用。列表增量未在Python中自動生成3/2

我也嘗試過製作跨Python,所以它可以在Python 2,3以上版本中運行。

這裏是我的代碼

# Asking users for their search terms # 
def user_searchterms(): 
    version = (3,0) # for python version 3 and above 
    cur_version = sys.version_info 
    if cur_version >= version: 
     try: 
      maxterms = input("Enter Maximum Terms By You[EX: 1/2/3] >> ") # User tells the maximum search terms he wants 
      maxlist = maxterms 
      while len(search_keyword) < maxlist: 
       item = input("Enter Your Item >> ") 
       search_keyword.append(item) 
     except Exception as e: 
      print(str(e)) 
    else: 
     try: 
      maxterms = raw_input("Enter Maximum Terms By You[EX: 1/2/3] >> ") 
      maxlist = maxterms 
      while len(search_keyword) < maxlist: 
       item = raw_input("Enter Your Items >> ") 
       search_keyword.append(item) 
     except Exception as e: 
      print "ERROR: Exception Occured!" 

user_searchterms() # for starting the function 

Image to demonstrate the problem

編輯:我在Python2.7測試。 我想讓用戶輸入數字來告訴他們想添加多少搜索詞。然後while循環運行一個循環來追加用戶輸入的搜索詞。

這裏的想法: 假設用戶輸入3時詢問搜索詞的數量,一個變量將保存該值。然後while循環會將該值與數組的長度進行比較。如果數組小於該值(數組中的項小於用戶輸入的數字),則循環將要求用戶輸入字符串search_term並將該字符串附加到數組中。

我試圖製作一個谷歌圖片下載器,可以詢問用戶的搜索條件。

在此先感謝

+0

請準確地說出您的期望會發生什麼,以及發生了什麼。 「while循環不起作用,並且比較沒有用」,這是相當模糊的。 – Carcigenicate

+0

你讓它跨越python,但是你跑的是什麼版本? P2? – roganjosh

+1

'input'和'raw_input()'返回字符串值。如果你想把它轉換成一個整數,就像你看到的那樣,對結果調用int()。 –

回答

1

您忘記的search_keywordmaxlist INT轉換初始化。這工作:

import sys 

# Asking users for their search terms # 
def user_searchterms(): 
    version = (3,0) # for python version 3 and above 
    cur_version = sys.version_info 
    if cur_version >= version: 
     try: 
      search_keyword = list() 
      maxterms = input("Enter Maximum Terms By You[EX: 1/2/3] >> ") # User tells the maximum search terms he wants 
      maxlist = maxterms 
      while len(search_keyword) < int(maxlist): 
       item = input("Enter Your Item >> ") 
       search_keyword.append(item) 
     except Exception as e: 
      print(str(e)) 
    else: 
     try: 
      search_keyword = list() 
      maxterms = raw_input("Enter Maximum Terms By You[EX: 1/2/3] >> ") 
      maxlist = maxterms 
      while len(search_keyword) < int(maxlist): 
       item = raw_input("Enter Your Items >> ") 
       search_keyword.append(item) 
     except Exception as e: 
      print "ERROR: Exception Occured!" 

user_searchterms() # for starting the function 
1

你應該在方法的開頭

search_keyword=[] 

初始化空列表,你也應該適用INT()輸入()和的raw_input(輸出)調用

+0

謝謝我做到了:) –