Python 为什么我不能打破while循环?
我一直在尝试根据用户输入创建一个国家及其资本的字典,但我似乎无法打破这个循环,即使我做了一个实例,它应该在用户成对输入Q,Q时结束Python 为什么我不能打破while循环?,python,loops,dictionary,for-loop,while-loop,Python,Loops,Dictionary,For Loop,While Loop,我一直在尝试根据用户输入创建一个国家及其资本的字典,但我似乎无法打破这个循环,即使我做了一个实例,它应该在用户成对输入Q,Q时结束 capital_dict = {} country,capital = input("Enter Country, Enter Capital").split(',') while ('country','capital') != ('Q','Q'): capital_dict['country']=capital country,capital
capital_dict = {}
country,capital = input("Enter Country, Enter Capital").split(',')
while ('country','capital') != ('Q','Q'):
capital_dict['country']=capital
country,capital = input("Enter Country, Enter Capital").split(',')
else:
print(capital_dict)
感谢您的帮助 看这一行:
while ('country','capital') != ('Q','Q'):
这一行永远不会是真的,因为字符串不会改变,看看第一个元组,它是一个字符串元组,应该是一个变量元组,所以如果您将这一行替换为:
while (country,capital) != ('Q','Q'):
它将按预期工作。请看这一行:
while ('country','capital') != ('Q','Q'):
这一行永远不会是真的,因为字符串不会改变,看看第一个元组,它是一个字符串元组,应该是一个变量元组,所以如果您将这一行替换为:
while (country,capital) != ('Q','Q'):
它将按预期工作。问题是您正在使用字符串而不是变量名进行比较 还请注意,您可以通过while True子句避免重复逻辑:
问题是您使用字符串而不是变量名进行比较 还请注意,您可以通过while True子句避免重复逻辑: