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

输入不匹配指定元素列表时无法提示重新输入,求问题排查

代码问题分析与修正

原代码存在的问题:

  • Python布尔值关键字是大写的True,原代码while true :会触发NameError。
  • 条件判断错误:使用了赋值运算符=而非比较运算符==,且省略了每个或条件的elem变量,正确写法要么是elem == 'H' or elem == 'He'...,要么用更简洁的elem in El_List。
  • break,末尾的逗号属于语法错误,应改为break。
  • 字符串未闭合:print ('Not Found in Element list)缺少末尾单引号,引发SyntaxError。
  • 异常捕获格式错误:except: ValueError :写法不符合Python语法,正确格式是except ValueError:,且当前场景下input()不会抛出ValueError,该try-except块可移除。
  • str(input(...))多余,input()本身返回字符串类型,无需二次转换。

修正后的代码:

El_List = ('H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne')

user_instructions = 'Select Elements value from following list to create a molecule'
print(user_instructions)

while True:
    elem = input('add molecular formula: ')
    if elem in El_List:
        print(elem)
        break
    else:
        print('Not Found in Element list')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 02:46:23