“while循环"不破坏(使用 Python)

编程入门 行业动态 更新时间:2024-10-20 03:17:21
本文介绍了“while循环"不破坏(使用 Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

这是我的代码:

#Choose Report
def chooseReport():
    print "Choose a report."
    while True:
        choice = raw_input("Enter A or B: ")
        if choice == 'a' or choice == 'A':
            reportA()
            break
        elif choice == 'b' or choice == 'B':
            reportB()
            break
        else:
            continue

当我输入 ab 时,它只是要求我再次输入 A 或 B".它没有执行它应该执行的功能.

When I input either a or b, it just asks me to "Enter A or B" again. It doesn't go to the functions its supposed to.

知道这是为什么吗?

推荐答案

首先,您的代码运行良好,最可能的错误是您编写了错误的输入(例如:输入了更多字符).要解决这个问题,您可以在选择中使用 "a" 或在选择中使用 "A".但如果它不起作用……请继续阅读.

First, your code works fine, the most probably error is that you are writing a wrong input (e.g: with more characters). To solve that you could use "a" in choice or "A" in choice. But if it isn't working... keep reading.

似乎 break 不影响 while 循环,我没有 python 2 所以我不太确定为什么(在 python 3 [更改后raw_inputinputprintprint()] 你的代码工作完美).所以你应该使用 while 的条件来打破它.

It's seems that break isn't affecting the while loop, I don't have python 2 so I am not very sure why (in python 3 [after change raw_input to input and print to print()] your code works perfect). So you should use the condition of the while to break it.

while True 理论上永远有效,因为每次执行代码时,它都会检查条件 -True- 并且因为它为真,它会一直循环.
您可以操纵该条件以中断循环(不允许再次执行其代码).

while True work theorically for ever because each time the code is executed it checks the condition -True- and because it's true it keeps looping.
You could manipulate that condition in order to break the loop (don't allow execute again its code).

例如你可以使用这个:

#Choose Report
def chooseReport():
    print "Choose a report."
    allow = True    # allow start as True so the while will work
    while allow:
        choice = raw_input("Enter A or B: ")
        if choice.lower().strip() == "a":    # This is better. .lower() make "A" > "a", and .strip() delete " a " to "a", and "a/n" to "a".
            reportA()
            allow = False   # allow now is False, the while won't execute again
        elif choice.lower().strip() == "b":
            reportB()
            allow = False   # allow now is False, the while won't execute again
        # The else is complete redundant, you don't need it

这篇关于“while循环"不破坏(使用 Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-26 03:31:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128978.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:quot   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!