我如何才能正确地将此代码设置为 运行?我对 if 和 else 语句有疑问,显然它没有正确缩进

How can I get this code to run properly? I'm having issues with the if and else statements and apparently it's not indented correctly

我正在尝试创建一个程序来计算汽车的停止距离,并且我想这样做,如果用户输入的减速度大于 0,那么程序将打印 Cannot use positive integers .此外,该程序在 else 语句中存在缩进错误。

我已经尝试过缩进,但没有解决任何问题。

a = raw_input("How quickly is the vehicle decelerating? ")
if a > 0:
        print "cannot be a positive integer"

else a < 0: 
    s1 = (0 - float(u)**2)
    s2 = (2*float(a))
    s = s1/s2
 print "The vehicle will travel %s meters before coming to a complete stop" % (s)

确实缩进不正确。您的最后一个打印函数应该退格一次,以便在 else 之外。其次,else 不接收条件,,如果您键入:

   if a > 5: 
    print(True) 
   else a < 5: 
    print(False)    

您将收到以下消息:

SyntaxError: invalid syntax

两种解决方案:

   if a > 5: 
    print(True) 
   else: 
    print(False) 

   if a > 5: 
    print(True) 
   elif a < 5: 
    print(False)    

第三,由于你的对象a是一个字符串,第一个条件a > 0会失败,一旦完成这样的比较a 必须是 intfloat;

最后,raw_input 不是 Python 3.x 中的有效函数。如果您转到更新版本的 Python,您应该将其替换为 input ()。考虑到这一点,您的代码应如下所示:

a = input("How quickly is the vehicle decelerating? ")
a = int(a)
if a > 0:
    print ("cannot be a positive integer")

else: 
    s1 = (0 - float(u)**2)
    s2 = (2*float(a))
    s = s1/s2
print ("The vehicle will travel %i meters per second before coming to a complete stop" % (s))

希望对您有所帮助

这是解决代码问题的良好开端。正确的缩进如下:

a = raw_input("How quickly is the vehicle decelerating? ")
if a > 0:
    print("cannot be a positive integer")
elif a < 0: 
    s1 = (0 - float(u)**2)
    s2 = (2*float(a))
    s = s1/s2
    print("The vehicle will travel %s meters per second before coming to a complete stop" % (s))

注意我在 print() 模块中添加了括号。另外,我用 elif 交换了你的 else,因为如果你想调整它,另一个 if 是必需的。

这里有一些其他提示需要考虑: 1) 尝试使用 post 复制并粘贴错误消息。你会发现学会阅读错误会让你受益匪浅。请随意评论他们对此答案以获得进一步的指导。 2) 如果您使用 python 3.*,则 raw_input() 已折旧。 freecodecamp.com 有一个很棒的蒙特拉:"Read-Search-Ask" 按此顺序排列。 3) raw_input(),或者至少我使用的 python3 版本,会给你一个字符 return.

祝你好运!