Discuss / Python / 作业。。。又有错误

作业。。。又有错误

Topic source

 deta=b**2-4*a*c

    if deta >= 0:

        x1 = (-b+math.sqrt(deta))/(2*a)

        x2 = (-b-math.sqrt(deta))/(2*a)

        return x1 ,x2

    else:

        return '无实数根'

错误显示

 File "C:\Users\JYY\AppData\Local\Temp\learn_python_vy1yzmbf_py\test_18.py", line 11

    else:

        ^

SyntaxError: invalid character in identifier

但是注释掉else两行就没问题

deta=b**2-4*a*c

    if deta >= 0:

        x1 = (-b+math.sqrt(deta))/(2*a)

        x2 = (-b-math.sqrt(deta))/(2*a)

        return x1 ,x2

    #else:

    #   return '无实数根'

quadratic(2, 3, 1) = (-0.5, -1.0)

quadratic(1, 3, -4) = (1.0, -4.0)

测试成功

李雄Yock

#2 Created at ... [Delete] [Delete and Lock User]

这节课是要定义函数的。。。。

#!/usr/bin/env python3

# -*- coding: UTF-8 -*-

import math

a = float(input('a='))

b = float(input('b='))

c = float(input('c='))

deta=b**2-4*a*c

if deta >=0:

    x1 = (-b+math.sqrt(deta))/(2*a)

    x2 = (-b-math.sqrt(deta))/(2*a)

    print (x1,x2)

else:

    print ('无实数根')

我只粘了一部分代码,主要是为什么我的 else 部分代码有错QAQ

贴完整代码

import math

def quadratic(a, b, c):

        deta=b**2-4*a*c

        if deta >= 0:

             x1 = (-b+math.sqrt(deta))/(2*a)

            x2 = (-b-math.sqrt(deta))/(2*a)

        return x1 ,x2

        else:

        return'无实数根'

  File "C:\Users\JYY\AppData\Local\Temp\learn_python_c70i69lt_py\test_1.py", line 11

    else:

        ^

SyntaxError: invalid character in identifier

好吧因为我else那里用了中文冒号哈哈哈哈哈。。。。现在变成了

    deta=b**2-4*a*c

    if deta >= 0:

        x1 = (-b+math.sqrt(deta))/(2*a)

        x2 = (-b-math.sqrt(deta))/(2*a)

    return x1 ,x2

    else:

        return'无实数根'

File "C:\Users\JYY\AppData\Local\Temp\learn_python_c70i69lt_py\test_15.py", line 11

    else:

       ^

SyntaxError: invalid syntax

return x1,x2这行缩进有问题,if和else对齐,return应该和x2 = (-b-math.sqrt(deta))/(2*a)这一行对齐。


  • 1

Reply