为什么我的气泡排序代码会继续循环退出,以及如何解决问题/为什么bubble_sortundefined

问题描述

`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)得到一个错误,指出它是未定义的。这是什么原因呢?任何帮助表示赞赏。

解决方法

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

这部分代码未对齐。

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)

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