songwentao 发表于 2022-3-27 09:53:59

为什么无法跳出while循环

这是我做的一个GUI猜数字源码:
import easygui as eg
import random
def judge():
    #times += 1
    if answer == number:
      eg.msgbox('恭喜你猜对啦!' ,'光电GUI猜数字',ok_button='游戏结束!')
      a = True
    elif answer > number:
      eg.msgbox('猜大啦!''光电GUI猜数字',ok_button='继续!')
    else:
      eg.msgbox('猜小啦!''光电GUI猜数字',ok_button='继续!')
eg.msgbox('游戏规则:猜一个1-100里的数字,猜对了,不会给你奖励!不过猜错了会提示你!','光电GUI猜数字',ok_button='现在开始!')
number = random.randint(1,100)
times = 0
a = False
while True:   
    try:
      answer = int(eg.enterbox('请输入0-100的一个数字','光电GUI猜数字'))
      judge()
      if a == True:
            break
    except (TypeError,ValueError):
      eg.msgbox('请不要输入字符!''光电GUI猜数字',ok_button='继续!')
    if a == True:
      break

它为什么一直问,无法跳出循环呢?

Gacy 发表于 2022-3-27 10:43:37

while都是true

凋零落叶 发表于 2022-3-27 11:05:40

因为你将a设置为True了,所以你一直输入非零的数就不会跳出循环

songwentao 发表于 2022-3-27 18:32:14

能发下解决代码吗?

简单是福 发表于 2022-3-28 14:36:22

本帖最后由 简单是福 于 2022-3-28 16:40 编辑

是你自定义的那块出了问题具体的问题我也是初学者知识浅薄找不出来,
现在的代码已经稳定运行,加入了次数限制和密码





import easygui as eg
import random

#密码保护程序
M = str(123456) # 密码,
Y = 0 # while语句限制条件
tset = 0 # 密码输入次数
while   M != Y : # while循环开始
    Y = eg.enterbox('请输入密码')# 用户输入密码(整形后)
    if M != Y :#判断密码是否正确
          eg.msgbox ('密码错误请重新输入',ok_button='继续')
    tset += 1 #密码输入次数递增
    if tset == 3:#当用户输错三次密码时
      eg.msgbox('密码三次错误,程序退出')
      quit()#退出
if M == Y:#当用户输入密码正确时
      eg.msgbox('欢迎进入猜数字游戏 ')


eg.msgbox('游戏规则:猜一个1-100里的数字,猜对了,不会给你奖励!不过猜错了会提示你!你只有6次机会哦!','光电GUI猜数字',ok_button='现在开始!')
number = random.randint(1,100)
times = 0
a = False
while not a and times < 6:
    try:
      answer = int(eg.enterbox('请输入0-100的一个数字','光电GUI猜数字'))
    except (TypeError,ValueError):
      eg.msgbox('请不要输入字符!''光电GUI猜数字',ok_button='继续!')

    if answer == number:
      eg.msgbox('恭喜你猜对啦!' ,'光电GUI猜数字',ok_button='游戏结束!')
      a = True
    elif answer > number:
      eg.msgbox('猜大啦!''光电GUI猜数字',ok_button='继续!')
      times += 1
    else:
      eg.msgbox('猜小啦!''光电GUI猜数字',ok_button='继续!')
      times += 1
eg.msgbox(number,'这个数字是',ok_button='游戏结束!')

页: [1]
查看完整版本: 为什么无法跳出while循环