Python 第二个功能程序。一些询问
我的书要求我使用函数制作另一个程序,关键是这次我需要让它变得更复杂一点,所以我不去做简单的加法,而是尝试用用户给我的值来解决一个非常简单的物理问题,使用两个函数(速度和加速度) 这是程序的目标(sampledoc)Python 第二个功能程序。一些询问,python,Python,我的书要求我使用函数制作另一个程序,关键是这次我需要让它变得更复杂一点,所以我不去做简单的加法,而是尝试用用户给我的值来解决一个非常简单的物理问题,使用两个函数(速度和加速度) 这是程序的目标(sampledoc) 创建一个程序来读取和打印此txt文档 介绍程序和脚本的名称 使用函数解决问题,使函数更复杂 用户给出距离(x)和时间(t) 程序计算速度和加速度 创建新的txt文档并在其中写入结果 直接从新文档打印问题的结果 代码如下: from sys import argv script,
- 用户给出距离(x)和时间(t)
- 程序计算速度和加速度
from sys import argv
script, textf = argv; sampledoc = open(textf)
def velocity (x, t):
vel = (float(x)) / (float(t))
return float(vel)
def acceleration (v, t):
accel = (float(v)) / (float(t))
return float(accel)
print "Hello my name is TAR or as my creator called me %s" % script; print sampledoc.read(); sampledoc.close()
print "Results will be printed on a new text document, thanks for your preference"
x = float(raw_input("Please introduce the Distance")); t = float(raw_input("Please introduce the time:... "))
vel = velocity(x, t)
accel = acceleration (velocity, t)
results = 'ResultsP.txt'
new_file = open(results, 'w')
new_file.write(str(vel)); new_file.write(str(accel))
new_file.close()
new_file.open(results, 'r')
print new_file.read()
new_file.close()
我知道这里某个地方出了点问题,但我的大脑现在不工作,我想这与我试图解决这个问题的方式或我在函数中使用的“浮动”有关,因为我得到了这个错误:
File "ex21Study.py", line 20, in <module>
accel = acceleration (velocity, t)
File "ex21Study.py", line 10, in acceleration
accel = (float(v)) / (float(t))
TypeError: float() argument must be a string or a number
文件“ex21Study.py”,第20行,在
加速度=加速度(速度,t)
文件“ex21Study.py”,第10行,加速度
加速度=(浮动(v))/(浮动(t))
TypeError:float()参数必须是字符串或数字
我在谷歌上搜索了一下,找到了一些关于将结果转换为float或str的其他类似问题的答案,但是,我尝试了这两种方法,但都没有结果。您在这里传递了一个函数:
velocity
不是浮点值;它是一个函数对象。您可能打算在此处使用vel
,这是您在前一行中计算的:
vel = velocity(x, t)
accel = acceleration(vel, t)
您看到的错误的完整回溯是什么?样式提示:不要使用
。这会使您的代码难以阅读,而且调整/维护起来也很麻烦。唯一可以接受的时间是交互式解释器中的快速片段。
vel = velocity(x, t)
accel = acceleration(vel, t)