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

Python代码第8行报‘V未定义’错误,已输入V仍报错求排查

问题分析与解决

核心问题:变量未完成赋值

你代码的第2、4、6行仅将输入转换为float类型,但没有把转换结果赋值给C、V、M变量,导致后续代码调用这些变量时,Python判定它们从未被定义,这就是"V未定义"错误的根源。

其他需要修正的问题

  • Python中幂运算用**,而非^(^是按位异或运算符)
  • 赋值操作使用单等号=,双等号==是比较运算符,不能用来给变量赋值
  • 变量名不一致:代码里定义的是Gam2,但打印的是Gam,属于笔误

修正后的完整代码

import math 
# C = "speed of light" in m/s
C = float(input("Enter speed of light (m/s): "))
# V = "speed of mobile" in m/s
V = float(input("Enter speed of mobile (m/s): "))
# M = "mass of mobile" in Kg
M = float(input("Enter mass of mobile (Kg): "))

# 计算洛伦兹因子
Gam = 1 / math.sqrt(1 - (V/C)**2)
print(Gam)

# 计算动量相关值
p = M * V
q = M * V * Gam

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 19:15:34