while 语句之后的 Else 语句,以及字符串与字符串列表的比较? [英] Else-statement after while-statement, and string comparison with a list of strings?

查看:17
本文介绍了while 语句之后的 Else 语句,以及字符串与字符串列表的比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个小型测试脚本,用于将某些内容附加到笔记中.下面包含的是我将在脚本中执行的主要功能.问题似乎是当 while 块评估为 false 时(也就是说,当它评估为任何不是不是这四个选项之一),while 块只是在无限循环中继续.我还尝试将 break 插入到 while 循环中,但这会在 while 循环执行后终止脚本.

I'm attempting to create a small test script that appends something to a note. Contained below is the main function that I will execute in the script. The problem seems to be that I can't get the else block to run when the while block evaluates to false (that is to say, when it evaluates to anything that isn't one of those four options), the while block just continues in an infinite loop. I've also attempted to insert a break into the while loop but this terminates the script after the while loop has executed.

while 的计算结果为 false 时,如何将其移动到 else 块?为什么我目前做事的方式不像我希望的那样工作?谢谢.

How do I move from the while to the else block when it evaluates to false? And why doesn't the current way I do things work as I would like it to? Thanks.

def start():
    q01 = input("What is the subject of your note?
")
    q02 = input("Are you certain that the subject of your note is " + q01 + "?
")
    while q02 == 'No' or 'no' or 'NO' or 'n':
       q01 = input("So, what is the subject of your note?
")
       q02 = input("Are you certain now that the subject of your note is " + q01 + "?
")
    else:
       q03 = Enter("Enter the content of your note")

推荐答案

你的罪魁祸首是 while 循环条件:

Your culprit is the while loop condition:

while q02 == 'No' or 'no' or 'NO' or 'n':

这相当于:

while (q02 == 'No') or 'no' or 'NO' or 'n':

作为 'no''NO''n' 都是非空字符串,它们的计算结果为 True 所以你的条件评估为:

As 'no', 'NO' and 'n' are all non-empty strings they evaluate to True and so your condition evaluates to:

while (q02 == 'No') or True or True or True:

显然总是True.

要解决此问题,您需要将条件调整为:

To fix this you need to adjust the condition to:

while q02 == 'No' or q02 == 'no' or q02 == 'NO' or q02 == 'n':

虽然为了更pythonic,你可以改为:

Although to be more pythonic you could instead make this:

while q02 in ['No','no','NO','n']:

这篇关于while 语句之后的 Else 语句,以及字符串与字符串列表的比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆