Home > Enterprise >  No error code, but output repeats itself until kernal is interrupted
No error code, but output repeats itself until kernal is interrupted

Time:07-16

I am a bit new to coding and am trying to build a code in python that asks the user what country they are from, and based on the answer the code assigns a numerical output.

Unfortunately, every time I try to run this code, I do not get any errors, but instead, the code output just asks over and over again 'Enter Country Name' until I interrupt the kernel.

What can I do to remedy this? Any help would be very appreciated.

   #high income
   A = ("Aruba", "Andorra",
       "United Arab Emirates", "Antigua and Barbuda",
      "Australia", "Austria", "Belgium", "Bahrain", "Bahamas", "Bermuda", "Barbados")
   # Low income
   B = ("Afghanistan", "Burundi", "Zambia", "Burkina Faso", "Central African 
    Republic", "Syrian Arab Republic","Congo Dem. Rep")

 # Middle Income
    C = ("Angola", "Albania", "Argentina", "Armenia", "American Samoa", "Azerbaijan", 
    "Benin", "Bangladesh","Bulgaria")
 while True:
     user_input = input('Enter Country Name: ')
   total = 0.
   if user_input == A:
            total  = 1
            print(total, "Added")
  elif user_input == B:
            total  = 2
            print(total, "Added")
  elif user_input == C:
            total  = 3
            print(total, "Added")
 else:
     print("country does not exist")

CodePudding user response:

In your while condition your mentioning True then it will run the set of statements till it gets False.

The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.

cond = True
while cond:
    user_input = input('Enter Country Name: ')
    total = 0
    if user_input in A:
        total  = 1
       print(total, "Added")
    elif user_input in B:
        total  = 2
        print(total, "Added")
    elif user_input in C:
        total  = 3
        print(total, "Added")
    else:
        print("country does not exist")
        cond = False

so in the above example first we are setting true in the variable on the end of while we are setting cond as False so the while will stop executing

CodePudding user response:

you are using a while loop with the True as condition. It is an infinite loop as True is always true. To make it work you need to insert a break condition in some of the if-else statements so that the code can exit the loop somewhen. Or you can rewrite your while statement to make the code more reasonable. I do not know exactly what you want to do but if you just want to ask the user for the input you do not need a while loop.

Hope this helped.

  • Related