python - 为什么我的冒泡排序代码的循环外循环以及如何解决问题/为什么冒泡排序(未定义)
问题描述
`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)
请检查代码的所有部分并确保它们对齐。
推荐阅读
- regex - 正则表达式程序查找带有空格和反斜杠的数字
- ruby-on-rails - 用于复制对象的 Rails 按钮
- c++ - 在脚本调用的 C++ 函数中调用 QJSEngine::newQObject() 是否有效?
- makefile - 制定运行规则,但目标比 prereq 更新
- django - 键必须是 str、int、float、bool 或 None,而不是 builtin_function_or_method
- python - 如何计算一个实体与另一个实体一起出现的次数
- reactjs - 尽管使用 React.FC,但在访问子组件时出现打字稿错误
- angular - 在 mat-select 中选择一个值会导致尝试“diff”时出错
- laravel - ReflectionException (-1) 类 App\Http\Controllers\IndexController 不存在
- c# - 如果值为 null,则在我的视图中显示值会引发 ToString 错误