Problems with my code... when I execute it in Python and input a valid number, it comes up with "IndexError: list index out of range" even when its valid or invalid. I want it to print row[0] and row [1] if the number is between 0 & 9 else print out an error message.
import csv
number=input("Enter num: ")
with open("myfile.txt", "r") as file:
fileReader = csv.reader(file)
for row in fileReader:
for i in range (0,10):
if row[i] == number:
print(row [0], row [1])
else:
print ("Error")
file.close()
Thanks in advance for any help!
What you asked for was to print row[0]
and row[1]
if the input value is between 0 and 9, but what you are doing is printing row[0]
and row[1]
if the input value matches a value stored in row
between row[0]
and row[9]
. You also are assuming that row
will contain 10 items (depending on your input, maybe this is an acceptable assumption, I don't know).
This will print row[0]
and row[1]
(for every row) if the input value is between 0 and 9. It assumes that each row contains at least two items.
import csv
number=input("Enter num: ")
if number >= 0 and number <= 9:
with open("myfile.txt", "r") as file:
fileReader = csv.reader(file)
for row in fileReader:
print(row [0], row [1])
else:
print ("Error")
file.close()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.