Python化学物种验证代码输入始终无效问题排查请求
化学物种验证代码的问题排查与修复
问题描述
编写的Python代码用于验证用户输入是否为有效化学物种,但无论输入列表中的正确名称或分子式,都会返回无效提示。原代码如下:
import numpy as np chemlist = np.array(["carbon dioxide", "co2", "carbon monoxide", "co", "ethane", "c2h6", "methane", "ch4", "nitrogen", "n2", "oxygen", "o2", "water", "h2o (liquid)", "water vapour", "h2o (gas)"]) print(chemlist) chemical = input("Enter name or the chemical formula of your compound:\n") chemical = chemical.lower() print(chemical) for i in range(len(chemlist)): if chemical == chemlist[i]: break else: print("Invalid chemical name. Please input one from the list below:\n") print(chemlist) chemical = input("Enter name or the chemical formula of your compound again:\n") temperature = 0 temperature = float(input("Enter your temperature in degrees Kelvin:\n")) if temperature <= 273.15 or temperature >= 673.15: temperature = float(input('Temperature is not in range. Enter your temperature in degrees Kelvin again:\n')) else: break
问题分析
- 循环逻辑错误:原
for循环会逐个对比列表元素,只要当前元素不匹配就立刻触发错误提示并重新输入,完全没机会检查后续元素。比如输入co2,第一次对比的是carbon dioxide,不匹配就直接进入else分支,根本不会去对比下一个元素co2。 - 温度验证逻辑缺陷:温度输入只做了一次重新输入判断,若用户再次输入无效值,代码不会继续校验;另外
else分支的break语句没有对应的循环,会直接导致语法错误。
修正后的代码
import numpy as np chemlist = np.array(["carbon dioxide", "co2", "carbon monoxide", "co", "ethane", "c2h6", "methane", "ch4", "nitrogen", "n2", "oxygen", "o2", "water", "h2o (liquid)", "water vapour", "h2o (gas)"]) print("Available chemicals:", chemlist) # 验证化学物种的循环:直到输入有效为止 while True: chemical = input("\nEnter name or the chemical formula of your compound:\n").lower() if chemical in chemlist: print(f"Valid chemical: {chemical}") break else: print("Invalid chemical name. Please input one from the list below:") print(chemlist) # 验证温度的循环:直到输入有效为止 while True: try: temperature = float(input("\nEnter your temperature in degrees Kelvin:\n")) if 273.15 < temperature < 673.15: print(f"Valid temperature: {temperature} K") break else: print("Temperature is not in range (273.15 K < T < 673.15 K). Try again.") except ValueError: print("Please enter a valid number for temperature.")
修改说明
- 把化学物种验证改成
while True循环,用in关键字直接判断输入是否在列表中,逻辑更简洁,直到输入有效才退出循环。 - 温度验证也改成循环,同时加入异常处理,防止用户输入非数字导致报错,确保只有输入有效范围内的数值才会退出。
- 移除了无意义的
break语句,修复了语法错误。
内容的提问来源于stack exchange,提问作者Fatimah Humaira Khalid
相关产品推荐
相关产品推荐

