0

我目前正在尝试设置此代码,以便在这种情况下button1连接到 RPi GPIO 的按钮运行该功能c1并继续循环该功能,直到按下另一个按钮button2,然后它运行该功能c2继续在该功能中循环。

    #Import RPi GPIO module
    from gpiozero import Button

    #Assign name to buttons GPIO pins
    button1 = Button(2)
    button2 = Button(4)

    def c1():
        while True:
            print('c1')
            grade = float(input('Select grade: '))
            if grade < 10:
            print('Less than 10')
        else:
            print ('invalid input')

   def c2():
       while True:
            print('c2')
            grade = float(input('Select grade: '))
            if grade < 10:
                print('Less than 10')
            else:
                print ('invalid input')

我遇到了破坏功能的麻烦c1,我试图breakwhile按下另一个按钮时添加一个,如下所示,因为代码没有停止,所以没有任何运气。

    def c1():
        while True:
            print('c1')
            grade = float(input('Select grade: '))
        if grade < 10:
            print('Less than 10')
        elif button2.is_pressed:
            break

我也试过这个来打破循环,但我什至不确定这是一个正确的方法,无论如何它没有工作。

    def c1():
        while True:
            print('c1')
            grade = float(input('Select grade: '))
            if grade < 10:
                print('Less than 10')
            elif button2.is_pressed:
                c1() == False
                break

我不确定是否正确,但我有一种感觉必须改变函数让我们假设c1打破False循环。我希望通过在按下新按钮后告诉代码停止循环将起作用,但它没有成功。

我在这里想念什么?

4

2 回答 2

1

你调试过你的程序吗?你检查过那个break叫吗?

它可能会帮助您找到问题所在。

您还可以打印:button2.is_pressed以了解正在发生的事情。

于 2021-12-26T00:22:56.493 回答
1

如果这是确切的代码,那么您可能会注意到它在循环break之外。while

def c1():
    while True:
        print('c1')
        grade = float(input('Select grade: '))
    if grade < 10:
        print('Less than 10')
    elif button2.is_pressed:
        break

同时,在此代码中,您需要boolean在循环之前设置变量while,然后将其设置为 false。如果您正在使用此方法,则不需要,因为一旦变量设置为 false,break该函数将中断循环。while

def c1():
    while True:
        print('c1')
        grade = float(input('Select grade: '))
        if grade < 10:
            print('Less than 10')
        elif button2.is_pressed:
            c1() == False
            break

试试这个:

def c1():
    flag = True
    while flag == True:
        print('c1')
        grade = float(input('Select grade: '))
        if grade < 10:
            print('Less than 10')
        elif button2.is_pressed: #try using if here instead of elif
            flag = False

或这个:

def c1():
    while True:
        print('c1')
        grade = float(input('Select grade: '))
        if grade < 10:
            print('Less than 10')
        elif button2.is_pressed: #try using if here instead of elif
            break

编辑:也许你错过了,如果这不起作用,请elif尝试使用。if

编辑2:进一步的问题。

def c1():
    while True:
        print('c1')
        if button2.is_pressed:
            break
        grade = float(input('Select grade: '))
        if grade < 10:
            print('Less than 10')
于 2021-12-26T00:24:02.973 回答