Reputation: 3
I'm trying to read numbers from a text file (20 numbers) and print odd numbers and multiples of 7
numbers = open('numbers' , 'r')
nums=[]
cnt=1
while cnt<20:
nums.append(numbers.readline().rstrip('\n'))
cnt += 1
print nums
oddNumbers = []
multiplesOf7 = []
for x in nums:
num = int(nums[x])
if num%2 > 0 :
oddNumbers.append(num)
elif num%7 > 0 :
multiplesOf7.append(num)
print('Odd numbers: ' , oddNumbers)
print('Multiples of 7: ' , multiplesOf7)
I'm getting
Traceback (most recent call last): ['21', '26', '27', '28', '7', '14', '36', '90', '85', '40', '60', '50', '55', '45', '78', '24', '63', '75', '12'] File "C:/Users/y0us3f/PycharmProjects/Slimanov/oddmultiples.py", line 16, in num = int(nums[x]) TypeError: list indices must be integers, not str
Process finished with exit code 1
Upvotes: 0
Views: 659
Reputation: 4862
You're already iterating over values inside nums. Don't look up the value from nums again:
# nums = ['21', '26', '27', '28', '7', '14', '36', '90', '85', '40', '60', '50', '55', '45', '78', '24', '63', '75', '12']
for x in nums:
# x is '21', '26', etc.
num = int(x)
...
You're getting an exception because you're trying to look up a value from nums using a string index: nums['21']
, but in this case you don't even need to, as you already have the value of '21' stored in x.
Upvotes: 2