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

在Codecademy使用input()函数时遭遇EOFError,该如何修复?

问题解决:EOFError及代码逻辑修正

一、EOFError的原因与修复

EOFError: EOF when reading a line 意味着代码调用input()时,没有读取到任何输入就遇到了文件结束符。常见触发场景:

  • 在部分在线代码编辑器运行时,未提前配置或提供输入内容;
  • 终端运行时,意外按下Ctrl+D(Linux/macOS)或Ctrl+Z(Windows)提前终止输入。

修复方式:

  • 本地终端运行:将代码保存为.py文件,打开终端进入文件所在目录,执行python space.py,终端会正常提示输入内容;
  • 在线编辑器操作:若使用Codecademy环境,确保运行前按提示正确填写测试输入值(部分在线环境需预先配置输入内容)。

二、代码中的其他逻辑错误

除EOFError外,代码还有两个关键问题会导致功能失效:

  1. 字符串与整数比较不匹配:input()返回字符串类型,直接和整数1/2等比较永远为False,所有分支都会走到else;
  2. 字符串无法直接参与数值运算:weight是输入的字符串,直接乘浮点数会触发类型错误。

修正后的完整代码

print("I have information for the following planets:\n")

print("   1. Venus   2. Mars    3. Jupiter")
print("   4. Saturn  5. Uranus  6. Neptune\n")

# 转换输入为数值类型,并处理非法输入
try:
    weight = float(input("Please enter Earth weight: "))
    planet = int(input("Please enter planet number: "))

    # 修正条件判断逻辑
    if planet == 1:
        new_weight = weight * 0.91
        print(f"Your weight on Venus will be {new_weight} lb.")
    elif planet == 2:
        new_weight = weight * 0.38
        print(f"Your weight on Mars will be {new_weight} lb.")
    elif planet == 3:
        new_weight = weight * 2.34
        print(f"Your weight on Jupiter will be {new_weight} lb.")
    elif planet == 4:
        new_weight = weight * 1.06
        print(f"Your weight on Saturn will be {new_weight} lb.")
    elif planet == 5:
        new_weight = weight * 0.92
        print(f"Your weight on Uranus will be {new_weight} lb.")
    elif planet == 6:
        new_weight = weight * 1.19
        print(f"Your weight on Neptune will be {new_weight} lb.")
    else:
        print("Unknown planet")
except ValueError:
    print("请输入有效内容:体重输入数字,行星输入1-6的整数")

修正说明

  • 用float()和int()将输入转为对应数值类型,解决比较和运算的类型问题;
  • 新增try-except块处理用户输入非数字的情况,避免程序直接崩溃;
  • 使用f-string格式化输出,比字符串拼接更简洁易读;
  • 用new_weight存储计算结果,避免修改原始输入的weight变量(优化可读性)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 04:06:07