【问题标题】:Syntax error and is there a better way to write this?, with if - else conditional语法错误,有没有更好的方法来写这个?,if - else 有条件
【发布时间】:2013-11-01 01:48:24
【问题描述】:

我刚刚开始学习 Python,我正在尝试自学它,这样我就可以测试计算机编程,进入 java,这是我真正想学习的。我知道这不是最简单的方法,但这是我想出的。当我运行它时,有一个语法错误,但我并没有真正看到它。我很确定我有很多问题。

有人可以帮我解决一下我的语法吗?

另外,如果有人可以建议一些学习 Python 的方法,或者他们是如何学习它的,因为我可能会得到一本关于它的书或其他东西。

文件“Triangletest.py”,第 8 行 else tyy == 0
^ SyntaxError: 无效语法

T1 = input("First side of triangle:  ")
T2 = input("Second side of triangle:  ")
addi = T1 + T2
suub = T1 - T2
T3 = input("Third side of triangle:  ")
    tyy = 1
else tyy == 0
    if T3 < suub:
pss == 1
    else pss = 0
if tyy + pss == 2:
print("The triangle is not possible")

【问题讨论】:

  • 嗯,这段代码存在很多问题——我真的不知道你在做什么。不过不要气馁——上网,查找一些代码示例,将它们与您在此处所做的比较,看看可能有什么问题。另请查看diveintopython.netlearnpythonthehardway.org
  • 将 tyy == 0 更改为 tyy = 0

标签: python if-statement conditional


【解决方案1】:

评论:

T1 = input("First side of triangle:  ")
T2 = input("Second side of triangle:  ")
addi = T1 + T2
suub = T1 - T2
T3 = input("Third side of triangle:  ")
    tyy = 1 \ Identation does not work
else tyy == 0 # else requires a : at the end of the line and an if before it it never has a condition. use elif instead of else: if ...:
    if T3 < suub:
pss == 1 # you mus ident behind every :
    else pss = 0 # this is ok but : missing
if tyy + pss == 2: # there mus be something behind it.

语法没问题:

T1 = input("First side of triangle:  ")
T2 = input("Second side of triangle:  ")
addi = T1 + T2
suub = T1 - T2
T3 = input("Third side of triangle:  ")
tyy = 1
if False: pass # if before else
elif tyy == 0:
    if T3 < suub:
        # should it be pss = 1 ?
        pss == 1 # this is in the if clause
    else: pss = 0
if tyy + pss == 2:
    pass # do something

【讨论】:

    【解决方案2】:

    您似乎正在尝试解决这个问题:用户输入边,程序回答是否可能有这些边的三角形。如果你对你的边进行排序,它会简单得多。

    sides = [float(input(ord + ' side of a triangle: '))
                 for ord in 'First Second Third'.split()]
    a, b, c = sorted(sides)
    if c < a + b: print('Triangle is possible')
    else: print('Triangle is impossible')
    

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多