【问题标题】:Python noob, i don't know why it is giving SyntaxError: Invalid syntaxPython noob,我不知道它为什么给出 SyntaxError: Invalid syntax
【发布时间】:2019-07-29 20:31:56
【问题描述】:

正如标题所说,我在

处遇到语法错误
temp_string = lines[1][equals_pos+2:] from datetime import date

我不知道如何解决它,或者出了什么问题。

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:] from datetime import date
from apscheduler.scheduler import Scheduler
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_f

【问题讨论】:

  • from datetime import date 应该在模块的顶部。至少不是内联
  • 导入语句应该是单独的一行,并且应该在文件的顶部
  • 有人将前两行代码拖到某处(或复制粘贴错误)。有两个不合适的导入语句
  • 两个from .... import ... 语句都在错误的位置,它们需要在文件的顶部,每行一个语句。也许您无意中复制/粘贴了。对于这样的错误,您必须非常仔细地阅读每一行并尝试理解 Python 抱怨的原因——它总是正确的。
  • 为了呼应其他用户的说法,here 是 python 官方风格指南中的相关部分。值得收藏和参考 PEP8 指南

标签: python syntax-error


【解决方案1】:

import 语句应该在单独的行

from datetime import date
from apscheduler.scheduler import Scheduler
def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_f

【讨论】:

    猜你喜欢
    • 2019-09-20
    • 2021-07-27
    • 2021-12-11
    • 1970-01-01
    • 2022-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-17
    相关资源
    最近更新 更多