没有错误代码,但输出重复自己,直到内核被中断



我对编码有点陌生,我试图用python构建一个代码,询问用户他们来自哪个国家,并根据答案分配一个数字输出。

不幸的是,每次我尝试运行此代码时,我都没有得到任何错误,而是,代码输出只是一遍又一遍地询问'输入国家名称',直到我中断内核。

我能做些什么来补救?如有任何帮助,我将不胜感激。

#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")

在while条件中,如果你提到True,那么它将运行这组语句,直到它得到False

Python中的while循环用于遍历代码块,只要测试表达式(condition)为真。

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

那么在上面的例子中,首先我们在末尾的变量中设置true同时我们将cond设置为False这样while语句将停止执行

你正在使用一个以True为条件的while循环。这是一个无限循环,因为True总是为True。要使它工作,您需要在一些if-else语句中插入一个中断条件,以便代码可以在某个时候退出循环。或者您可以重写while语句以使代码更合理。我不知道你到底想做什么,但如果你只是想让用户输入,你不需要一个while循环。

希望有帮助。

最新更新