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

Python中while循环程序退出时触发TypeError错误求助

Python代码修复:循环退出时的TypeError问题

错误根源

报错TypeError: argument of type 'builtin_function_or_method' is not iterable是因为这行代码:

if 'y' in q.lower:

lower是字符串的内置方法,必须通过()调用它才能得到小写的字符串结果。直接写q.lower得到的是方法对象本身,而in运算符要求右侧是可迭代对象(比如字符串、列表),因此触发错误。

修复后的完整代码

import sys

finish = True
while finish:
    lst = []  # 每次循环重置列表,避免累积之前的输入
    num = int(input('How many numbers will be in the list?: '))
    
    for n in range(num):
        number = int(input('Please enter a number: '))
        lst.append(number)
        
    print(f'The largest number is: {max(lst)} \nThe smallest number is: {min(lst)}')
    
    q = input('Do you wish to exit?: ')
    if 'y' in q.lower():  # 调用lower()获取小写字符串
        print('We are done!')
        break
    else:
        print('We will continue!')
    
sys.exit(0)

额外优化点

  • 将lst = []移到while循环内部:原代码中列表会累积所有输入的数字,导致后续的最值计算包含之前的输入,重置后才能保证每次计算的是当前输入的列表。
  • 使用f-string格式化输出:让打印语句更简洁直观。
  • 移除多余的continue:while循环在未触发break时会自动继续迭代,无需额外声明。

内容的提问来源于stack exchange,提问作者Christian James Lavada

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 05:45:49