为什么我的if语句不执行其print语句Python 2.7.11

时间:2016-04-24 06:47:38

标签: python python-2.7 if-statement printing while-loop

我在Python 2.7.11中有一个main方法(在第一次执行之后)会询问用户是否想要继续(y/n)'y'的响应重新执行我在main中实例化的while循环就好了,并且考虑了错误的输入并重新询问了问题。但是,当用户输入'n'时,它不会打印'Goodbye.',而是在没有达到print语句的情况下退出循环。这是我的代码:

def main():

    will_continue = 'y' # Default for the first execution

    while will_continue == 'y':
        # A bunch of execution code here for the program...

        # After executing rest of code
        will_continue = raw_input('Do you wish to continue? (y/n): ')

        while will_continue != 'y' and will_continue != 'n':
            if will_continue == 'n':
                print 'Goodbye.'
            else:
                will_continue = raw_input('Invalid input. Do you wish to continue? (y/n): ')


if __name__ == "__main__":
    main()

我想我的问题可能是and中的while continue != 'y' and continue != 'n':,所以我将其更改为while continue != 'y' or continue != 'n':,但如果我在'Goodbye'打印,这会让我处于无限循环中'n'如果我输入'y',则输入print 'Goodbye.'或无限无响应。

关于为什么main语句在终止//Function to generate a HTML table from a SQL query function myTable($obConn,$sql) { $rsResult = mysqli_query($obConn, $sql) or die(mysqli_error($obConn)); if(mysqli_num_rows($rsResult)>0) { //We start with header echo "<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"0\"><tr align=\"center\" bgcolor=\"#CCCCCC\">"; $i = 0; while ($i < mysqli_num_fields($rsResult)){ $field = mysqli_fetch_field_direct($rsResult, $i); $fieldName=$field->name; echo "<td><strong>$fieldName</strong></td>"; $i = $i + 1; } echo "</tr>"; //We dump info $bolWhite=true; while ($row = mysqli_fetch_assoc($rsResult)) { echo $bolWhite ? "<tr bgcolor=\"#CCCCCC\">" : "<tr bgcolor=\"#FFF\">"; $bolWhite=!$bolWhite; foreach($row as $data) { echo "<td>$data</td>"; } echo "</tr>"; } echo "</table>"; } } 之前不会执行的任何想法?

3 个答案:

答案 0 :(得分:2)

您要求用户输入else块。如果用户输入了&#39; n,则while块将在下一次迭代中终止,从而导致if will_continue == 'n'永不执行。快速解决此问题的方法是将if放在内部while循环的之外。

或者,您可以避开if块,只需将程序打印为“再见”即可。无论发生什么,最后都会结束。

答案 1 :(得分:0)

will_continue永远不会在上面的代码中更改,因此它永远不会是&#39; n&#39;。

答案 2 :(得分:0)

以下是适用的代码的更新版本。

def main():

    con = 'y' # Default for the first execution

    while con == 'y':
        # A bunch of execution code here for the program...

        # After executing rest of code
        con = raw_input('Do you wish to continue? (y/n): ')
        while con != 'y' and con != 'n':
            con = raw_input('Invalid Input. Type y/n: ')
        if con == 'n':
            print 'Goodbye.'


if __name__ == "__main__":
    main()
相关问题