首页 > 解决方案 > 为什么我的冒泡排序代码的循环外循环以及如何解决问题/为什么冒泡排序(未定义)

问题描述

`def bubble_sort(numbers):
# We set swapped to True so the loop looks runs at least once
swapped = True
while swapped:
    swapped = False
    for i in range(len(numbers) - 1):
        if numbers[i] > numbers[i + 1]:
            # Swap the elements
            numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i]
            # Set the flag to True so we'll loop again
            swapped = True

      results = bubble_sort(numbers)
      UserInput = input("Please enter ten integer numbers with a space 
      in between, or 'Quit' to exit: ")
      numbers = UserInput.split()
      print(UserInput)
      while True:
        if UserInput.lower() == 'quit':

        break

       if not UserInput.isdigit():
         print("Invalid input.")

      continue

      else:
        print(results)`

在我的代码中,bubble_sort(numbers) 收到一个错误,指出它未定义。这是什么原因?任何数量的帮助表示赞赏。

标签: pythonbreakcontinue

解决方案


您的代码中有许多部分未正确对齐。我给你举一个例子。

这部分代码没有对齐。

if not UserInput.isdigit():
  print("Invalid input.")

    continue #should be aligned to print statement

 else: #not aligned. Should be aligned to if statement
  print(results)

上面的代码应该如下:

if not UserInput.isdigit():
   print("Invalid input.")

   continue

else:
   print(results)

请检查代码的所有部分并确保它们对齐。


推荐阅读