嵌套在循环无法正常工作的情况下工作

发布于 2025-02-12 07:14:37 字数 2405 浏览 0 评论 0原文

创建了一个简单的数学计算:

用户进行第一次计算后,他们被问到3个问题。

  1. 用最终答案做更多的数学。
  2. 重新启动新鲜退出

循环时使用的巢穴来实现这一目标。

下图显示了

  1. 进行计算时的成功。
  2. 然后询问用户是否想对最终答案进行更多作用。答案是“ n”。
  3. 然后,他们被问到他们是否想完全开始或完全退出。答案退出了:'n'。
  4. 因此程序成功结束了。

成功地结束了代码

但是,在重新

  1. 测试中成功。
  2. 要继续最终答案=否。
  3. 您想开始新鲜吗? =是。
  4. 程序重新启动。伟大的!
  5. 成功。
  6. 要继续最终答案=否。
  7. 您想开始新鲜吗? =否。
  8. 在这一点上,程序应该结束(就像上面的那样),但它继续持续,好像上面的步骤2中的用户说“是”。

继续循环,它不应该

无法解决原因。尝试使用断点来查看正在发生的事情,但在如何正确使用此工具方面仍然没有经验。也使用索尼。 Thonny表明它承认“断路”命令(因此应该从时循环中滑出),但是然后跳到下一条编码线,然后计算继续。

enter code here
    more_calc = user_continue_check(data=math_question)

    if more_calc == 3:
        break

    elif more_calc == 2:
        main()

    print("Error checking: When do we get to here?")
    start_calc += 1

下面的循环时嵌套的问题是吗?只是不知道。在这个几个小时里被黑客入侵了。使用Thonny,此嵌套环正常工作。它可以正确返回正确的变量int结果。如此困惑。

enter code here
     def user_continue_check(data):

         user_answer = False
         ans = True

         while not user_answer:

             more_calc = str(input("\n\tDo you want to do more math with the calculated result of "
                          + fg.orange + "{0}".format(data['result']) + fg.rs + "?" + fg.blue + " y/n: "
                          + fg.rs)).strip().lower()

             if more_calc == "n":
                final_check = True

                while final_check:

                   final_user_check = str(input("You you want to start a new calculation: y/n: ")).strip().lower()

                   if final_user_check == "n":
                        ans = 3
                        break
                   elif not final_user_check == "y":
                        print(fg.red + "\t\tYou need to enter y or n" + fg.rs)
                   else:
                        ans = 2
                        break
               break
    
             elif not more_calc == "y":
                print(fg.red + "\t\tYou need to enter y or n" + fg.rs)
             else:
                ans = 1
                break


         return ans

以下是整个脚本的链接。我只是不知道在哪里寻找答案。无法确定为什么它确实有效。

Created a simple maths calc:

After user does their first calc they are asked 3 questions.

  1. Do more math with the final answer.
  2. Restart fresh
  3. Quit completely.

Used nest while loops to achieve this.

Picture below shows

  1. Success at doing a calc.
  2. User was then asked if they wanted to do more with the final answer. Answer was 'n'.
  3. They were then asked if they wanted to start fresh or quit completely. Answer was quit: 'n'.
  4. So program ended successfully.

Successful end to code

However on retest

  1. Calc successful.
  2. Do want to continue with final answer = no.
  3. Do you want to start fresh? = yes.
  4. Program restarts. Great!
  5. Calc successful.
  6. Do want to continue with final answer = no.
  7. Do you want to start fresh? = no.
  8. At this point the program should end (as it did above) BUT it continued as if the user in step 2 above had said 'yes'.

Keeps looping and it shouldn't

Cannot work out why. Tried using breakpoints to see what is happening but still too inexperienced on how to correctly used this tool. Used Thonny as well. Thonny shows that it acknowledges the 'break' command (so it should slip out of the while loop) however it then skips ahead to the next coded line and the calc continues.

enter code here
    more_calc = user_continue_check(data=math_question)

    if more_calc == 3:
        break

    elif more_calc == 2:
        main()

    print("Error checking: When do we get to here?")
    start_calc += 1

Is the problem in the nested while loops below? Just don't know. Been hacking away at this for hours. Using Thonny this nested loop works fine. It breaks out correctly returning the correct variable int result. So confused.

enter code here
     def user_continue_check(data):

         user_answer = False
         ans = True

         while not user_answer:

             more_calc = str(input("\n\tDo you want to do more math with the calculated result of "
                          + fg.orange + "{0}".format(data['result']) + fg.rs + "?" + fg.blue + " y/n: "
                          + fg.rs)).strip().lower()

             if more_calc == "n":
                final_check = True

                while final_check:

                   final_user_check = str(input("You you want to start a new calculation: y/n: ")).strip().lower()

                   if final_user_check == "n":
                        ans = 3
                        break
                   elif not final_user_check == "y":
                        print(fg.red + "\t\tYou need to enter y or n" + fg.rs)
                   else:
                        ans = 2
                        break
               break
    
             elif not more_calc == "y":
                print(fg.red + "\t\tYou need to enter y or n" + fg.rs)
             else:
                ans = 1
                break


         return ans

Below is a link to the whole script. I just don't know where to look for the answer. Cannot work out why it does work then doesn't.

enter link description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

忆梦 2025-02-19 07:14:37

原因是因为您的休息确实确实打破了所有三个循环,但是您在主机上使用了递归电话,因此您可以回到主的递归呼叫。

因此解释:

main =>输入loop =>输入main =>输入loop =>输入loop => enter loop => exit all three last loops => 退出Main

您仍然处于第一个主循环中,该循环称为您刚刚终止的第二个主。

当函数使用递归呼叫自己时,它不会终止,一旦内部呼叫完成,该函数将在呼叫后立即继续执行。

但是通常,我会在提高代码质量方面有点努力,您可能会发现将来更容易调试,这里有一些建议:

  • 使用明确的,非模棱两可的名称(no“ ans ans”“ fg”,final_check /final_user_check“)
  • 如果可以避免避免突破(并且在大多数情况下可以在此处使用)不要
  • 重复代码,
  • 请不要将不同类型的类型重新分配到您的变量(例如:ANS启动为true,而是变成一个数字)
  • 不要使用递归,几乎永远不值得。 < =在这种情况下,这将解决

一个不错的开始的问题。

您的代码做一些非常简单的事情,但很难理解,这是一个不好的信号。很高兴您尝试将所有这些概念纳入其中,但是您需要保持代码整洁,以便能够继续进行工作,并了解它的问题

The reason is because your break does indeed break all three loops, but you are using recursive calls on your main, so you are getting back to a lower recursive call of your main.

So to explain:

main => enter loop => enter main => enter loop => enter loop => enter loop => exit all three last loops => exit main

You are still in the first loop in the first main, which called the second main which you just terminated.

When a function calls itself using recursion, it is not terminated, once the inner call is finished, the function continues its execution right after the call.

But generally, I would work a little bit on improving the quality of the code first, you might find it easier to debug in the future, here are some suggestions:

  • Use explicit, non ambiguous names (no "ans" "fg" "final_check/final_user_check")
  • don't use break if it can be avoided (and it can here in most cases)
  • don't repeat code
  • don't reassign different types to your variable (ex: ans starts as True, but then becomes a number)
  • don't use recursion, it is almost never worth it. <= in this case this will fix the issue

That will be a decent start.

Your code does something extremely simple yet it's hard to understand and that is a bad sign. It's great that you are trying to incorporate all these concepts into it, but you need to keep your code tidy in order to be able to continue working on it, and understand the problems with it

木格 2025-02-19 07:14:37

@jeekiii解释了这个问题,即您在中重复添加到中,如果More_calc == 2:确实重新启动计算,但是一旦Inner main 退出,控件返回到外部main,然后将其关闭的位置接收(重复计算)。您可能应该在这里做的是,而不是在那里调用main(),只需通过执行即可清除状态变量:

if more_calc == 2:    
    num_used_list = []
    math_question = {}
    start_calc = 0

就像您在main的顶部一样。

您已经有一个new_calc变量,您可以在循环的顶部检查,因此您可以避免使用break完全通过设置new_calc = false 在下,如果More_calc == 3:

@jeekiii has explained the problem, that you recurse into main in if more_calc == 2:, which does restart the calculation, but once the inner main exits, control returns to the outer main and just picks up where it left off (repeating the calculation). What you probably should do here is instead of calling main() there, just clear the state variables by doing:

if more_calc == 2:    
    num_used_list = []
    math_question = {}
    start_calc = 0

like you do at the top of main.

You already have a new_calc variable you check at the top of your loop so you can additionally avoid having to use break at all by just setting new_calc = False under if more_calc == 3:.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文