您好,很抱歉初学者的问题,但这使我挠头。我以前曾尝试在if语句中使用break语句退出代码,但是无论输入如何都中断了。该代码如下所示:
def describePet(petBreed, petName):
print('I have a pet ' + petBreed)
print('My ' + petBreed + '\'s name is ' + petName + '.')
while True:
print('Type quit to exit.')
breed = input('What is your pets breed?: ')
name = input('What is your pets name?: ')
if name or breed == 'quit':
break
else:
describePet(breed, name)
print('test')
我几乎将其发布为问题,但此后对其进行了重新格式化(但是我仍然希望得到一个答案),以便我获得所需的输出,但在输入预期的退出语句时无法脱离循环。重做代码如下:
def describePet(petBreed, petName):
print('I have a pet ' + petBreed)
print('My ' + petBreed + '\'s name is ' + petName + '.')
breed = None
name = None
while breed or name != 'quit':
print('Type quit to exit.')
breed = input('What is your pets breed?: ')
name = input('What is your pets name?: ')
describePet(breed, name)
print('test')
如果您可以让我知道为什么当我将quit字符串存储在任何一个变量中时为什么这段代码没有退出,我们将不胜感激。谢谢!
答案 0 :(得分:1)
在while循环中,执行以下操作:
def describePet(petBreed, petName):
print('I have a pet ' + petBreed)
print('My ' + petBreed + '\'s name is ' + petName + '.')
while True:
print('Type quit to exit.')
breed = input('What is your pets breed?: ')
name = input('What is your pets name?: ')
if name == 'quit' or breed == 'quit':
break
else:
describePet(breed, name)
print('test')
使用类似name or breed == 'quit'
之类的东西永远不会取值为true,因为它将首先计算name or breed
,该值始终是布尔值,而这并不是您所期望的。
答案 1 :(得分:0)
请尝试在您的代码中执行以下步骤。 1.在代码的第一部分中,更改if条件,如下所示。 (如果名称=='退出'或品种=='退出')
def describePet(petBreed, petName):
print('I have a pet ' + petBreed)
print('My ' + petBreed + '\'s name is ' + petName + '.')
while True:
print('Type quit to exit.')
breed = input('What is your pets breed?: ')
name = input('What is your pets name?: ')
if name =='quit' or breed == 'quit':
break
else:
describePet(breed, name)
然后按如下所示修改while循环条件。
同时繁殖!='退出'或名字!='退出'