2014-05-10 47 views
0

我已經創建了一個函數,它將一個國家的文本文件放入一個列表中,然後向用戶請求一個居住國家,如果該國家無效,那麼該計劃應該不斷向用戶請求一個有效的國家,而且它很有效,但如果這個國家有效,那麼shell會說它正在完成這個動作,但它從來沒有真正完成它。有沒有人有任何建議來解決這個問題?如何使用if語句退出while循環?

def real_country(variable): #function to determine if the country inputted for a new 
    user is valid 
    countries = open('country list.txt', 'r+') 
    country_list = countries.readlines() 
    for i in range(len(country_list)): 
    country_list[i] = country_list[i].strip('\n') 
    for i in range(len(country_list)): 
    if country_list[i] == variable: 
     return True 
    print are you a new or existing user? 
    exisitngORnew = raw_input() 
    if existingORnew == 'new': 
    Real_Country = 'unknown' 
    print 'What is your country of residence' 
    country = raw_input() 
    while Real_Country == 'unknown': 
    if real_country(country) == True: 
     Real_Country == country 
    else: 
     print 'Please enter a real country' 
     country = raw_input() 
    print 'program finally works!' 
+0

該函數是真正的遞歸還是錯誤標籤?如果它確實是遞歸的,那可能是你的問題。 – user3553031

+0

@jonrsharpe我知道該怎麼做,但由於某種原因,我在這個特定的實例中收到一個錯誤 – JDizzle98

+0

@ user3553031確實遞歸意味着infinte? – JDizzle98

回答

0

一個簡單的谷歌搜索會可能已經不是問這裏快:

http://www.tutorialspoint.com/python/python_loop_control.htm - 首先鏈接搜索 「蟒蛇退出while循環」

更新:

我已經採取了現在再看看你的代碼,你已經添加了一些縮進。我認爲你的程序「凍結」的原因是因爲遞歸調用real_country:if real_country(country) == True:。你可能是希望做一些與此類似:

... 
if country in country_list: 
    Real_Country = country; 
... 

在另一方面,對於代碼的這一特定部分:

... 
for i in range(len(country_list)): 
if country_list[i] == variable: 
    return True 
... 

你的程序很可能會過早結束,如果用戶確實輸入一個正確的國家。這意味着該塊下面的所有代碼都將被忽略。所以如果你的用例涉及用戶交互,那麼我會擺脫那個塊。

+0

@jonrsharpe:語法nazi :) – user3553031

1

我不得不重新格式化我的代碼,但我設法修復它。我沒有改變這個函數本身,但我改變了調用它的代碼。

def real_country(variable): #function to determine if the country inputted for a new user is valid 
countries = open('country list.txt', 'r+') 
country_list = countries.readlines() 
for i in range(len(country_list)): 
    country_list[i] = country_list[i].strip('\n') 
for i in range(len(country_list)): 
    if country_list[i] == variable: 
     return True 


print 'What is your country of residence' 
country = raw_input() 
valid = real_country(country) 

while valid!= True: 
    print 'that is not a valid country' 
    country = raw_input() 
    valid = real_country(country)