You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从C#转Python开发时遇到while循环布尔值判断不生效问题

问题根因

问题出在答案校验循环的逻辑判断错误,你写的循环条件为while (answer != 'tak') or (answer != 'nie'):,该条件的返回值永远为真:

  • 若输入tak,answer != 'nie'返回True,逻辑或or只要任意一个条件为真则整体为真,循环继续执行
  • 若输入nie,answer != 'tak'返回True,整体判断仍为真
    只有当answer同时等于tak和nie两个不同值时才会退出循环,显然不可能实现,因此无论输入什么都会一直停在校验循环里。
修复方案

将条件中的逻辑或or替换为逻辑与and即可符合预期,修改后的代码如下:

import MyFunctions


def main():
    game = True
    while game:
        trials = 1
        number = MyFunctions.Generate_random_number()
        print('Próba numer:', trials)
        userNumber = int(input('Podaj liczbe z przedzialu od 1 do 100: '))

        while MyFunctions._is_valid(number, userNumber) != True:
            trials += 1
            print('Próba numer:', trials)
            userNumber = int(input('Podaj liczbe z przedzialu od 1 do 100: '))
        answer = input('Czy chcesz kontynuować grę? "tak" lub "nie" tutaj przed while')
        # 仅修改此处or为and
        while (answer != 'tak') and (answer != 'nie'):
            print('tutaj')
            answer = input('Czy chcesz kontynuować grę? "tak" lub "nie"')
            print(answer)
            if answer == 'nie':
                game = False


main()
可选优化

你也可以用成员运算符简化判断逻辑,可读性更高:
while answer not in ('tak', 'nie'):

内容的提问来源于stack exchange,提问作者user14952566

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 02:45:02