不了解有关找到的多个语句的此SyntaxError的原因

2024-10-01 15:38:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我上周刚开始学习python,我有一个家庭作业,要求我设计输出正确答案的代码:

A cyclist peddling on a level road increases from 3 mph to 15 mph in 0.5 hours.

The equation below can be used to determine the rate of acceleration, where A is acceleration, t is time interval in hours, iV is initial velocity, and fV is final velocity.

A = (fV – iV)/t

Determine the rate of acceleration for the cyclist (in miles/hr^2) assuming that the cyclist continues to accelerate a constant rate for the first 0.5 hours.

起初,我不知道如何解决这个问题,但后来我在方程中输入值,得到 A=(15-3)/0.5=24

我不确定24的单位是多少,我想是每分钟英里或者别的什么。我知道我有一些单位转换的问题,但现在这个稍微不正确的数学解释是我正在处理的

我的代码如下:

def main():
    InitialVelocity = 15
    FinalVelocity = 3
    TimeIntervalInHours = 0.5
    RateofAcceleration = (FinalVelocity-InitialVelocity)/TimeIntervalInHours
    print(RateofAcceleration)

这个什么也印不出来

我开发的另一个代码如下:

InitialVelocity = 15
FinalVelocity = 3
TimeIntervalInHours = 0.5
NewVelocity = FinalVelocity - InitialVelocity
RateofAcceleration = NewVelocity/TimeIntervalInHours
print(RateofAcceleration)

错误消息:

SyntaxError: multiple statements found while compiling a single statement

我可以做些什么来改变我的代码来正确地建模这个数学问题并输出答案


Tags: theto答案代码inrateishours
1条回答
网友
1楼 · 发布于 2024-10-01 15:38:07

程序1失败:您的程序在main方法中,从未调用该方法。尝试最初在全局范围内的函数之后调用main(),它应该会做一些事情。此外,您的速度变量被翻转

程序2失败:不知道。除了方程式中的速度顺序错误外,在我的车上运行良好。它可能与程序的另一个组件有关。您是否使用python3(终端中的Python-V,或者如果您在没有许多特殊配置的Mac上,则使用python3的等效版本)进行编译


由于您是新来的,下面是我如何实现此程序以使其更具可读性。(虽然我有一个不同的命名约定,为了简洁起见,我可能只会用更少的行来命名)

转换为变量:在平坦道路上兜售自行车的人增加 在0.5分钟内从3英里/小时加速到15英里/小时:

iV = 3      # Initial velocity, mph
fV = 15     # Final velocity, mph, after 0.5 minutes
t  = 0.5    # Time, hours

实施方程:A=(fV–iV)/t。对于机组运行(mi/h-mi/h)/h为m/h^2,如下所示

A = (fV – iV)/t     # Implementing formula
print(A)            # 24, as you guessed

接近方程的更长方法

dV = (fV - iV)      # Delta V (change in velocity)
A  = dV/t

请注意,通过使用更短的变量名和统一的间距,代码更易于阅读。试试看。此外,在编写代码时,也要采用某种编码风格。就我个人而言,我会使用ivfvtdva作为单值元素,以获得良好的风格。只要谷歌好的Python编码风格、命名约定等等

另外,欢迎来到StackOverflow!并避免把问家庭作业问题作为一般的经验法则:在网上找到答案是微不足道的

相关问题 更多 >

    热门问题