如何退出此程序中的循环

2024-06-25 06:51:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近开始使用python,在这个基于文本的游戏中,我似乎无法退出while循环。我尝试将循环从while更改为for a循环和If Else循环,但我无法找到退出它的方法。我希望它退出循环,并在用户输入的数字与系统的随机数字匹配时打印下面写的文本

import random
def batting ():         
  print("You can enter a number between 1 and 10")
  bat = input()
  sys_ball = random.randint(1,10)
  print (sys_ball)
  score_board = (bat + bat)
  batting ()
  while bat != sys_ball:
    batting ()

def balling ():             
  print ("Ok! Start balling with a number between 1 and 10!")
  user_ball = input()
  sys_bat = random.randint(1,2)
  print (sys_bat)
  balling ()
  while user_ball != sys_bat:
    balling ()

def oddeve ():
  print("Welcome to finger cricket! Type 1 to start batting and 2 to start balling!")
  odd_eve = input()
  if odd_eve == ('1'):
    batting ()
    print ("You win! You scored".join(score_board))
  else:
    balling()
    print ("You win! You defeated me")
oddeve ()

Tags: andto文本youinputdefsys数字
1条回答
网友
1楼 · 发布于 2024-06-25 06:51:45

仔细看,您的函数递归地调用自己

def batting ():  # <- 1
  print("You can enter a number between 1 and 10")
  bat = input()
  sys_ball = random.randint(1,10)
  print (sys_ball)
  score_board = (bat + bat)
  batting ()  # <- 2
  while bat != sys_ball:
    batting ()

def balling ():  # <- 1           
  print ("Ok! Start balling with a number between 1 and 10!")
  user_ball = input()
  sys_bat = random.randint(1,2)
  print (sys_bat)
  balling ()  # <- 2
  while user_ball != sys_bat:
    balling ()

因此,停止递归调用函数

相关问题 更多 >