0

I have created a function that takes a text file of countries, puts it in a list, then asks a user for a country of residence, if the country is invalid then the program is supposed to continuously ask the user for a valid country, and it works, but if the country is valid, then the shell says that it is completing the action but it never actually completes it. Does anyone have any suggestions for fixing this?

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!'
JDizzle98
  • 21
  • 1
  • 5

2 Answers2

1

I had to reformat my code entirely, but I managed to fix it. I did not change the function itself, but i changed the code that called upon it.

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)
JDizzle98
  • 21
  • 1
  • 5
0

A simple Google search would have probably been faster than asking here:

http://www.tutorialspoint.com/python/python_loop_control.htm - First link searching "python exit while loop"

Update:

I've taken a second look at your code now that you've added some indentation. I think the reason your progam "freezes" is because of that recursive call to real_country : if real_country(country) == True:. You were probably looking to do something similar to this:

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

On another note, for this particular section of the code:

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

Your program will most likely end prematurely if the user does enter a correct country. Which means that all the code below that block would be ignored. So if your use case involves user interaction then I'd get rid of that block.

jsonmurphy
  • 1,600
  • 1
  • 11
  • 19