在Python中使用break命令时出现错误

时间:2020-06-19 22:37:32

标签: python

因此,我试图在代码中使用中断来选择退出程序,但是当我运行它时,出现“在Loop外中断”的信息。有办法解决吗?我已经尝试过return命令或其他与此问题类似的其他命令,但是我没有运气。这是我指的那段代码:


list_of_dictionaries = []

a = {}
s = {}
d = {}
f = {}

list_of_dictionaries.append(a)
list_of_dictionaries.append(s)
list_of_dictionaries.append(d)
list_of_dictionaries.append(f)

3 个答案:

答案 0 :(得分:1)

您的代码未正确缩进:

v1 = []
v2 = []

while True:

    print('Welcome to vector arithmetic! Below is a list of available operations.')

    print('1. Enter values for your vectors')
    print('2. Print vectors')
    print('3. Vector dimensionality')
    print('4. Add vectors')
    print('5. Compute dot product of vectors')
    print('6. Compute magnitude of vectors')
    print('7. Quit')

    choice = int(input('Enter the number corresponding to your choice: '))

    if choice == 7:
        break
    elif choice == 1:
        pass
    elif choice == 2:
        pass
    elif choice == 3:
        pass
    elif choice == 4:
        pass
    elif choice == 5:
        pass
    elif choice == 6:
        pass
    else:
        print('Invalid choice, try again')

如您所见,python中的缩进非常重要。

答案 1 :(得分:1)

在python中,缩进和空格很重要。正如上面的评论所提到的,我只是将while语句下面的整个块移到了正确的缩进中,并且可以按预期工作。

v1 = []
v2 = []

while True:
    print('Welcome to vector arithmetic! Below is a list of available operations.')
    print('1. Enter values for your vectors')
    print('2. Print vectors')
    print('3. Vector dimensionality')
    print('4. Add vectors')
    print('5. Compute dot product of vectors')
    print('6. Compute magnitude of vectors')
    print('7. Quit')

    choice = int(input('Enter the number corresponding to your choice: '))

    if choice == 7:
        break
    elif choice == 1:
        pass
    elif choice == 2:
        pass
    elif choice == 3:
        pass
    elif choice == 4:
        pass
    elif choice == 5:
        pass
    elif choice == 6:
        pass
    else:
        print('Invalid choice, try again')

答案 2 :(得分:1)

在我看来您遇到了缩进错误,在这种情况下,您需要确保在循环功能< / strong>或 class 正确缩进。

v1 = []
v2 = []

while True:

    print('Welcome to vector arithmetic! Below is a list of available operations.')

    print('1. Enter values for your vectors')
    print('2. Print vectors')
    print('3. Vector dimensionality')
    print('4. Add vectors')
    print('5. Compute dot product of vectors')
    print('6. Compute magnitude of vectors')
    print('7. Quit')

    choice = int(input('Enter the number corresponding to your choice: '))

    if choice == 7:
        break
    elif choice == 1:
        pass
    elif choice == 2:
        pass
    elif choice == 3:
        pass
    elif choice == 4:
        pass
    elif choice == 5:
        pass
    elif choice == 6:
        pass
    else:
        print('Invalid choice, try again')

此外,我不建议您在循环中使用 break ,因为如果实施不正确,可能会出现问题。而是尝试使用退出