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

如何终止循环?Spyder中调查程序限制未成年访问的问题

解决调查程序年龄限制问题

首先,你的代码存在几个关键问题,直接导致了当前的错误和逻辑失效:

  • 年龄列表定义错误:excluded_ages= '17''16'... 这种写法会把所有字符串拼接成一个长字符串,导致age_input in excluded_ages的判断逻辑完全出错。更合理的方式是用列表存储禁止年龄,或者直接判断年龄数值是否小于18。
  • 打印语句错误:print(input)是打印内置函数对象,正确写法应该打印你获取的输入变量,比如print(age_input)。
  • break的误用:break只能在循环(for/while)或switch语句中使用,你这里没有循环结构,所以会触发报错。要终止程序可以用sys.exit(),或者把后续调查代码放在条件分支里。

方法1:用sys.exit()直接终止程序

先导入sys模块,当年龄不符合要求时直接退出程序:

import sys

age_input = input('Enter your age: ')
print(age_input)

# 将输入转为整数,判断是否未满18岁
try:
    age = int(age_input)
    if age < 18:
        print('You may not proceed with this survey')
        sys.exit()
except ValueError:
    print('Please enter a valid number for your age')
    sys.exit()

# 年龄符合要求才执行后续调查
postcode_input = input('Enter your postcode: ')
print(postcode_input)

方法2:用else分支包裹后续调查代码

不需要额外导入模块,把调查内容放在年龄验证通过的分支里:

age_input = input('Enter your age: ')
print(age_input)

try:
    age = int(age_input)
    if age < 18:
        print('You may not proceed with this survey')
    else:
        postcode_input = input('Enter your postcode: ')
        print(postcode_input)
except ValueError:
    print('Please enter a valid number for your age')

这里加入了try-except处理非数字输入的情况,避免程序直接崩溃,适合新手完善程序逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 21:15:36