在Python中使用break和if语句编写小程序

2024-10-04 07:35:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一名编码初学者,但学习的积极性和决心都很强。我用Python3编写了一些小程序,以便更好地理解if和break语句。在我下面写的程序中,即使我把我的答案写为Yes,它仍然打印I'm sorry, I must've misheard you sir, my apologies。最重要的是,当我将break添加到else的末尾时,它告诉我它不在循环中。我想添加break,这样如果我说No,程序就可以停止了。有人能解释一下吗

name = str(input('What is your name? '))
wrongname = input('Are you really ' + name + '?')
if wrongname != 'Yes':
    print("I'm sorry, I must've misheard you sir, my apologies")
else:
    print('I heard all about you Mr. ' + name + '!')  
input('What are you doing in town?')
input('Ah I see, well, I hope you enjoy your stay !')
print('Thank you !')

Tags: name程序youinputifmyveyes
2条回答

您可以这样做:

import sys

name = str(input('What is your name? '))
wrongname = input('Are you really ' + name + '?')
if wrongname == 'No':
    print('Exiting program')
    sys.exit(0)
if wrongname != 'Yes':
    print("I'm sorry, I must've misheard you sir, my apologies")
else:
    print('I heard all about you Mr. ' + name + '!')  
input('What are you doing in town?')
input('Ah I see, well, I hope you enjoy your stay !')
print('Thank you !')

您的回答可能不完全是Yes,而是稍有不同,例如yes

要使其不区分大小写,您可以使用,例如:

if wrongname.lower() != 'yes':

(或其他类似变化)

还要注意的是,代码中目前没有循环,所以现在讨论从循环中中断有点模糊

相关问题 更多 >