2016-12-31 1 views
-3

Мне удалось запустить код успешно, но надеялся на него навсегда. Его первая попытка в Python, любая помощь была бы оценена. То, что я сделал, помещено над «Истиной:» поверх кода, но я все время получаю сообщение об ошибке «Извиняемая ошибка отступа: ожидаемая отступная строка блока 3», но без нее она работает нормально, но работает только один раз. Итак, мой вопрос в том, как я могу зациклиться навсегда, не получив ошибку? Почему я не могу написать «While True:» в качестве первой строки?Noob запрос для Python (Raspberry Pi)

While True: 
# Open the file that we viewed earlier so that python can see what is in it. Replace the serial number as before. 
tfile = open("/sys/bus/w1/devices/10-000802824e58/w1_slave") 
# Read all of the text in the file. 
text = tfile.read() 
# Close the file now that the text has been read. 
tfile.close() 
# Split the text with new lines (\n) and select the second line. 
secondline = text.split("\n")[1] 
# Split the line into words, referring to the spaces, and select the 10th word (counting from 0). 
temperaturedata = secondline.split(" ")[9] 
# The first two characters are "t=", so get rid of those and convert the temperature from a string to a number. 
temperature = float(temperaturedata[2:]) 
# Put the decimal point in the right place and display it. 
temperature = temperature/1000 
import time 
print temperature 
time.sleep(5) 
+3

Похоже, вам нужно прочитать Python учебник, было бы объяснить основы синтаксиса, как это. Программу нельзя программировать на Python, не зная, какую роль играет отступ. – Barmar

+1

и 'w'' 'должны быть строчными –

ответ

1

Вам нужно добавить четыре пространства для всего кода ниже while True: заявления. Python работает в блоках, инструкция while запускает блок, что означает, что весь код после этого блока имеет еще 4 пробела. Также оператор import должен быть наверху, потому что Python нужно только один раз импортировать код, а не несколько раз, чтобы он знал код. Код должен выглядеть следующим образом:

import time 

while True: 
    # Open the file that we viewed earlier so that python can see what is in it. Replace the serial number as before. 
    tfile = open("/sys/bus/w1/devices/10-000802824e58/w1_slave") 
    # Read all of the text in the file. 
    text = tfile.read() 
    # Close the file now that the text has been read. 
    tfile.close() 
    # Split the text with new lines (\n) and select the second line. 
    secondline = text.split("\n")[1] 
    # Split the line into words, referring to the spaces, and select the 10th word (counting from 0). 
    temperaturedata = secondline.split(" ")[9] 
    # The first two characters are "t=", so get rid of those and convert the temperature from a string to a number. 
    temperature = float(temperaturedata[2:]) 
    # Put the decimal point in the right place and display it. 
    temperature = temperature/1000 
    print temperature 
    time.sleep(5) 
+0

Это вызовет' SyntaxError' –

+0

@ juanpa.arrivillaga Что такое синтаксическая ошибка? Просто отошел от компьютера. –

+2

'Хотя True:' недействителен Python –

0
  1. В питона вам нужно indent код (как правило, используют 2 или 4 пробела).
  2. Пока петли в питоне начинаются с строчной буквы w.
  3. Поместите свои операторы импорта в начало файла.

Как так:

import time 

while True: 
    # Open the file that we viewed earlier so that python can see what is in it. Replace the serial number as before. 
    tfile = open("/sys/bus/w1/devices/10-000802824e58/w1_slave") 
    # Read all of the text in the file. 
    text = tfile.read() 
    # Close the file now that the text has been read. 
    tfile.close() 
    # Split the text with new lines (\n) and select the second line. 
    secondline = text.split("\n")[1] 
    # Split the line into words, referring to the spaces, and select the 10th word (counting from 0). 
    temperaturedata = secondline.split(" ")[9] 
    # The first two characters are "t=", so get rid of those and convert the temperature from a string to a number. 
    temperature = float(temperaturedata[2:]) 
    # Put the decimal point in the right place and display it. 
    temperature = temperature/1000 
    print temperature 
    time.sleep(5)