如何解决为什么我的气泡排序代码会继续循环退出,以及如何解决问题/为什么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)
请检查代码的所有部分,并确保它们对齐。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。