"def sleeper" 上的语法无效

Invalid Syntax on "def sleeper"

我正在做一个涉及 Raspberry Pi 伺服系统的小项目。 我想让舵机 运行 持续 x 时间然后停止。正在尝试我的代码,目前在 "def sleeper" 上收到无效语法并且不知道为什么。

我也是 Whosebug 的新手,我在缩进代码时遇到了一些问题,我深表歉意!

import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BOARD)

GPIO.setup(7,GPIO.OUT)

try:
                while True:
                        GPIO.output(7,1)
                        time.sleep(0.0015)
                        GPIO.output(7,0)




def sleeper():
    while True:

        num = input('How long to wait: ')

        try:
            num = float(num)
        except ValueError:
            print('Please enter in a number.\n')
            continue

        print('Before: %s' % time.ctime())
        time.sleep(num)
        print('After: %s\n' % time.ctime())


try:
    sleeper()
except KeyboardInterrupt:
    print('\n\nKeyboard exception received. Exiting.')
    exit()

那是因为你没有为第一个 try ... except 对写任何 except 块:

这可能会如您所愿:

import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BOARD)

GPIO.setup(7,GPIO.OUT)

try:
    while True:
        GPIO.output(7,1)
        time.sleep(0.0015)
        GPIO.output(7,0)
except:
    pass

def sleeper():
    while True:
        num = input('How long to wait: ')
        try:
            num = float(num)
        except ValueError:
            print('Please enter in a number.\n')
            continue

    print('Before: %s' % time.ctime())
    time.sleep(num)
    print('After: %s\n' % time.ctime())

try:
    sleeper()
except KeyboardInterrupt:
    print('\n\nKeyboard exception received. Exiting.')
    exit()

请检查缩进。