Here is my code for part of a connect 4 program:
def place_piece(n,column):
col=int(column)
boardlist=[['.'*42]]
for l in range(7):
if boardlist[col+42-7l]=='.':
if n%2==0:
piece=X
else:
piece=O
boardlist[col+7(6-l)]=piece
break
return boardlist
print(place_piece(1,3))
When I run it, line 5 if boardlist[col+42-7l]=='.': has an index out of range error. Why? And how could I fix this?
An index out of range error means that the index of the array you are referring to doesn't exist. This is how you declared boardlist:
boardlist=[['.'*42]]
In this case, boardlist itself only contains one element, which happens to be another array. Thus, the only viable index would be boardlist[0]. Based on the code you posted, I would suggest changing it to this:
boardlist=['.']*42
Your col+42-7l is more than len(boardlist) - 1 at some point in your loop. As simple as that.
Related
def count4(lst):
count = 0
for i in range(lst[0],lst[-1]+1):
print(i)
print(count4([1,2,3,4,5,6,4,5,4,4]))
Here the output is showing just "1234" and not the whole list pls tell me how to iterate this list using range function.
The reason you are getting output as "1234"
The below statement
for i in range(last[0], last[-1]+1):
is interpreted as
for i in range(1, 4 + 1):
i.e
for i in range(1,5):
Solution: Use this
for i in lst:
You were trying to iterate in the range of values stored in the list at starting and end position that was passed, which is logically incorrect.
The other suggested methods are also correct since you specifically said to use the range function so think this might be the answer you were looking for
def count4(lst):
for i in range(len(lst)):
print(lst[i])
print(count4([1,2,3,4,5,6,4,5,4,4]))
i just can't figure it out.
I got a string with some lines.
qual=[abcdefg\nabcedfg\nabcdefg]
I want to convert my characters to the ascii value and saves those values in an other list for each line.
value=[[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6]
But my codes saves them all in one list.
values=[1,2,3,4,5,6,1,2,3,4,5,6,1,2,3,4,5,6]
First of all my code:
for element in qual:
qs = ord(element)
quality_code.append(qs)
I also tried to split() the string but the result is still the same
qual=line#[:-100]
qually=qual.split()
for list in qually:
for element in list:
qs = ord(element)
quality.append(qs)
My next attempt was:
for element in qual:
qs = ord(element)
quality_code.append(qs)
for position in range(0, len(quality_code)):
qual_liste[position].append(quality_code[position])
With this code an IndexError(list index out of range) occurs.
There is probably a way with try and except but i dont get it.
for element in qual:
qs = ord(element)
quality_code.append(qs)
for position in range(0, len(quality_code)):
try:
qual_liste[position].append(quality_code[position])
except IndexError:
pass
With this code the qual_lists stays empty, probably because of the pass
but i dont know what to insert instead of pass.
Thanks a lot for help. I hope my bad english is excusable .D
Here you go, this should do the trick:
qual="abcdefg\nabcedfg\nabcdefg"
print([[ord(ii) for ii in i] for i in qual.split('\n')])
List comprehension is always the answer.
Good afternoon! I am relatively new to Python - and am working on an assignment for a class.
The goal of this code is to download a file, add a line of data to the file, then create a while loop that iterates through each line of data, and prints out the city name and the highest average temp from the data for that city.
My code is below - I have the output working, no problem. The only issue I am running into is an IndexError: list index out of range - at the end.
I have searched on StackOverflow - as well as digging into the range() function documentation online with Python. I think I just need to figure to the range() properly, and I'd be done with it.
If I take out the range, I get the same error - so I tried to change the for/in to - for city in mean_temps:
The result of that was that the output only showed 4 of the 7 cities - skipping every other city.
Any advice would be greatly appreciated!
here is my code - the screenshot link below shows output and the error as well:
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/world_temp_mean.csv -o mean_temp.txt
mean_temps = open('mean_temp.txt', 'a+')
mean_temps.write("Rio de Janeiro,Brazil,30.0,18.0")
mean_temps.seek(0)
headings = mean_temps.readline().split(',')
print(headings)
while mean_temps:
range(len(city_temp))
for city in mean_temps:
city_temp = mean_temps.readline().split(',')
print(headings[0].capitalize(),"of", city_temp[0],headings[2], "is", city_temp[2], "Celsius")
mean_temps.close()
You have used a while loop, when you actually want to use a for loop. You have no condition on your while loop, therefore, it will evaluate to True, and run forever. You should use a for loop in the pattern
for x in x:
do stuff
In your case, you will want to use
for x in range(len(city_temp)):
for city in means_temp:
EDIT:
If you have to use a while loop, you could have variable, x, that is incremented by the while loop. The while loop could run while x is less than range(len(city_temp)).
A basic example is
text = "hi"
counter = 0
while counter < 10:
print(text)
counter += 1
EDIT 2:
You also said that they expected you to get out of a while loop. If you want a while loop to run forever unless a condition is met later, you can use the break command to stop a while or for loop.
I've been stuck with this as well with the index error. My original code was:
city_temp = mean_temp.readline().strip(" \n").split(",")
while city_temp:
print("City of",city_temp[0],headings[2],city_temp[2],"Celcius")
city_temp = mean_temp.readline().split(",")
So I read the line then, in the loop, print the line, create the list from reading the line and if the list is empty, or false, break. Problem is I was getting the same error as yourself and this is because city_temp is still true after reading the last line. If you add..
print(city_temp)
to your code you will see that city_temp returns as "" and even though it's an empty string the list has content so will return true. My best guess (and it is a guess) it looks for the split condition and returns back nothing which then populates the list as an empty string.
The solution I found was to readline into a string first (or at the end of the whole loop) before creating the list:
city_temp = mean_temp.readline()
while city_temp:
city_temp = city_temp.split(',')
print(headings[0].capitalize(),"of",city_temp[0],headings[2],"is",city_temp[2],"Celcius")
city_temp = mean_temp.readline()
This time city_temp is checked by the while loop as a string and now returns false. Hope this helps from someone else who struggled with this
I am trying to use two while loops with variables a,b. but typeerror is shown. not sure why it is showing this error. Shouldn't i be able to do this?
a,b=0
while a<2:
a=a+1
while b<3:
b=b+1
As previously mentioned, the error can be fixed with either a=b=0 or a,b=0,0
The number of values to be referenced to has to be equal to the number of variables when using the (x,y=a,b) format. But it's more convenient to use the a = b = 0 method when you're trying to give multiple variables just one value.
this seems to work. A simple change.
a=0
while a<2:
a=a+1
b=0
while b<3:
b=b+1
a = 0;b = 0
while a<2:
a=a+1
while b<3:
b=b+1
def unZip(master3):
c = len(master3)
sub1=''
sub2=''
for i in range(1,c,2):
sub1+=master3[i]
sub2+=master3[i+1]
print(sub1,",",sub2)
Error is following on Python 3.4.3:
string index out of range
well you have i iterating to then length of master3 and then in the loop you are referencing master3[i+1]. So yes, that will be beyond the end of master3. Since you are starting a 1 instead of 0 do you perhaps mean to use [i-1] and [i]?