0
python for loop
I want to order the numbers of list from the lowest to highest but the program occurs with error that ((Traceback (most recent call last): File "C:/Users/PycharmProjects/untitled2/3.py", line 10, in <module> if b[i] > b[i + 1]: IndexError: list index out of range)) how can i fix this problem??!! what is the wrong with it print("please enter 5 numbers : ") b = [] for i in range(5): a = input() a = int(a) b.append(a) for i in range(0, 5): for j in range(0, 5): if b[i] > b[i + 1]: temp = b[i] b[i] = b[i + 1] b[i + 1] = temp
3 odpowiedzi
+ 1
Your sorting "algorithm" is wrong and will not sort...try:-
for i in range(len(b)-1, 0, -1):
for j in range(i):
if b[j] > b[j + 1]:
b[j], b[j + 1] = b[j + 1], b[j]
+ 2
Hi. Error message has already said enough. Just look at this i+1, at the point when i is 4 this expression gives 5, but the last item of array from 5 elements has index 4.
So you should run second loop one less time
0
Tnx very much thats true