无法在Python中退出循环。

huangapple go评论74阅读模式
英文:

(Guessing Game) Can't Break a loop on Python

问题

I was trying to make a guessing game that keeps playing if you choose that, but I'm having a problem breaking the loop. Every time the code reaches "quit()," the program gives me an error.

When I used repl:
repl process died unexpectedly

When I used programiz.com:

Traceback (most recent call last):
  File "<string>", line 42, in <module>
  File "<string>", line 40, in game
  File "<frozen _sitebuiltins>", line 26, in __call__
SystemExit: None

So I need some help here. Here is the code:

import random
import time

Name = input("Hello there! What is your name? ")

print(f"Hi {Name}! Welcome to the guessing game. I'm going to pick a number between 1 and 100")

def game():
  time.sleep(2)
  print('picking ...')
  time.sleep(2)

  guess = int(input("Alright! What is your guess?: "))
  correct_number = random.randint(1, 2)
  guess_count = 1

  while guess != correct_number:
    guess_count += 1
    if guess < correct_number:
      guess = int(input("Nope. Try higher. What is your guess?: "))
    else:
      guess = int(input("Nope. Try lower. What is your guess?: "))

  print(f"Congrats {Name}! The right answer was {correct_number}. It took you {guess_count} guesses.")

  time.sleep(3)

  Next_Try = input('''
    Wanna Try again?
    1: Yes!
    2: No thanks
    ''')
  
  while Next_Try:
    if Next_Try == "1":
      game()
    else:
     time.sleep(2)
     print("Thanks for Playing!")
     quit()

game()

I have tried exit() but still having the same problem.

英文:

I was trying to make a guessing game that keep playing if you choose that, but I'm having a problem to break the loop, every time the code reach "quit()", the program give me an error

when I used repl:
repl process died unexpetily

when I used programiz.com:
Traceback (most recent call last): File &quot;&lt;string&gt;&quot;, line 42, in &lt;module&gt; File &quot;&lt;string&gt;&quot;, line 40, in game File &quot;&lt;frozen _sitebuiltins&gt;&quot;, line 26, in __call__ SystemExit: None

so I need some hand here, here is the code

ـــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ

import random
import time

Name = input(&quot;Hello there!, What is your name? &quot;)

print(f&quot;Hi {Name}! Welcome to the guessing game. I&#39;m going to pick a number between 1 and 100&quot;)

def game():
  time.sleep(2)
  print(&#39;picking ...&#39;)
  time.sleep(2)

  guess = int(input(&quot;Alright! What is your guess?: &quot;))
  correct_number = random.randint(1,2)
  guess_count = 1

  while guess != correct_number:
    guess_count += 1
    if guess &lt; correct_number:
      guess = int(input(&quot;Nope.Try higher. What is your guess?: &quot;))
    else:
      guess = int(input(&quot;Nope.Try lower. What is your guess?: &quot;))

  print(f&quot;Congrats {Name}! The right answer was {correct_number}. It took you {guess_count} guess.&quot;)

  time.sleep(3)

  Next_Try = input(&#39;&#39;&#39;
    Wanna Try again?
  1: Yes!
  2: No thanks
  &#39;&#39;&#39;)
  
  while Next_Try:
    if Next_Try == &quot;1&quot;:
      game()
    else:
     time.sleep(2)
     print(&quot;Thanks for Playing!&quot;)
     quit()

game()

I have tried exit() but still having the same problem

答案1

得分: 1

在Python中,exitquit基本上都是立即终止程序的方法。一般情况下,它们只应在出现问题时使用。在你的代码中,在Next_Try循环的末尾,应该使用关键字break。这是退出循环的正确方式。尝试这样做:

while Next_Try:
    if Next_Try == "1":
        game()
    else:
        time.sleep(2)
        print("Thanks for Playing!")
        break

这里是一个链接到Python文档,详细介绍了break关键字的更多信息。

英文:

In Python, exit and quit basically are both ways to immediately kill the program. In general, they should be used only when things go wrong. In your code, on the Next_Try loop at the end, you should use the keyword break. That is the proper way to exit a loop. Try this:

  while Next_Try:
    if Next_Try == &quot;1&quot;:
      game()
    else:
     time.sleep(2)
     print(&quot;Thanks for Playing!&quot;)
     break

Here's a link to the Python docs that go over more about the break keyword.

答案2

得分: 0

have you tried using break instead of exit()?

while Next_Try:
    if Next_Try == "1":
      game()
    else:
     time.sleep(2)
     print("Thanks for Playing!")
     break
英文:

have you tried using break instead of exit()?

while Next_Try:
    if Next_Try == &quot;1&quot;:
      game()
    else:
     time.sleep(2)
     print(&quot;Thanks for Playing!&quot;)
     break

答案3

得分: -1

你提供的代码似乎是一个猜数字游戏,用户尝试猜出在1到100之间随机生成的数字。虽然代码似乎可以正常工作,但有一些改进可以进行:

correct_number 变量应该生成1到100之间的随机数,而不是1到2。更新这一行为 correct_number = random.randint(1, 100)。

不要使用 exit() 函数来终止程序,最好将游戏逻辑放入一个循环中,并为用户提供退出选项。这样,程序将一直运行,直到用户明确选择退出。

以下是您的代码的更新版本,包括上述改进:

import random
import time

def game():
    Name = input("Hello there! What is your name? ")
    print(f"Hi {Name}! Welcome to the guessing game. I'm going to pick a number between 1 and 100")
    
    while True:
        time.sleep(2)
        print('Picking a number...')
        time.sleep(2)
        correct_number = random.randint(1, 100)
        guess_count = 0
        
        while True:
            guess = int(input("Alright! What is your guess?: "))
            guess_count += 1
            if guess < correct_number:
                print("Nope. Try higher.")
            elif guess > correct_number:
                print("Nope. Try lower.")
            else:
                print(f"Congrats {Name}! The right answer was {correct_number}. It took you {guess_count} guess.")
                break
        
        time.sleep(3)
        next_try = input('''
            Wanna try again?
            1: Yes!
            2: No thanks
        ''')
        
        if next_try != "1":
            break
    
    print("Thanks for playing!")

game()

在这个更新的代码中,游戏逻辑被包含在一个 while True 循环中。它会持续运行,直到用户在要求再次尝试时输入不是 "1" 的内容以选择退出游戏。

希望这有所帮助!如果您有任何进一步的问题或疑虑,请随时告诉我。

英文:

The code you provided appears to be a guessing game where the user tries to guess a randomly generated number between 1 and 2. While the code seems to work correctly, there are a few improvements that can be made:

The variable correct_number should generate a random number between 1 and 100 instead of 1 and 2. Update the line to correct_number = random.randint(1, 100).

Instead of using the exit() function to terminate the program, it's better to wrap the game logic in a loop and provide an option for the user to exit. This way, the program will continue running until the user explicitly chooses to exit.

Here's an updated version of your code with the mentioned improvements:

import random
import time
def game():
  Name = input(&quot;Hello there! What is your name? &quot;)
  print(f&quot;Hi {Name}! Welcome to the guessing game. I&#39;m going to pick a number between 1 and 100&quot;)
  while True:
    time.sleep(2)
    print(&#39;Picking a number...&#39;)
    time.sleep(2)
    correct_number = random.randint(1, 100)
    guess_count = 0
    while True:
      guess = int(input(&quot;Alright! What is your guess?: &quot;))
      guess_count += 1
      if guess &lt; correct_number:
        print(&quot;Nope. Try higher.&quot;)
      elif guess &gt; correct_number:
        print(&quot;Nope. Try lower.&quot;)
      else:
        print(f&quot;Congrats {Name}! The right answer was {correct_number}. It took you {guess_count} guess.&quot;)
        break
    time.sleep(3)
    next_try = input(&#39;&#39;&#39;
      Wanna try again?
      1: Yes!
      2: No thanks
    &#39;&#39;&#39;)
    if next_try != &quot;1&quot;:
      break
  print(&quot;Thanks for playing!&quot;)
game()

In this updated code, the game logic is enclosed within a while True loop. It keeps the game running until the user chooses to exit by entering something other than "1" when prompted to try again.

I hope this helps! Let me know if you have any further questions or concerns.

huangapple
  • 本文由 发表于 2023年6月15日 00:42:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76475817.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定