How to fix "int" is not subscriptable error? - python

I keep getting the error 'int' object is not substitutable. I know my problem is within "def filaray()" I also know making "num" a list would be more efficient. However this is an assignment and I'm pretty sure we can only use array's. Is there a way I can fix my error while not making "num" a list?

The line num = random.randint(0,9) sets num to an int, and so when fillaray returns num (assuming size > 0), it is returning an int, not a list, and this int is then passed to totalOdds and totalEvens, which try to subscript it (i.e., do num[i]) as though it were a list, which is an error. Presumably, what you want to do is to append the random ints to the list num instead of overwriting it, e.g., by doing num.append(random.randint(0,9)).

Related

Adding numbers in defined set and printing it in Python

I am trying to input the 5 numbers in defined length set and try to print out those numbers but it's giving "TypeError: 'int' object is not iterable" this error.
print("enter 5 numbers")
a=set(5)
for i in range(0,5):
a.append(int(input("enter a number")))
for i in range(0,5):
print("numbers in array are",a[i])
I think there is some confusion on what set actually does. I assume you want to make a predefined set of length 5. When doing:
set(5)
you get:
TypeError: 'int' object is not iterable
because you're trying to make a set containing only the integer 5. If you want to make a set from that, you would have to include an iterable, maybe like so:
set((5,))
Out: {5}
But what I would recommend you to do is declare
a = [] # create an empty list
and then run your code. At the end then, I would make a set by typing
a = set(a)
Hopefully that was helpful for you! Have fun coding! :)
You cannot fix the size of set while creating.
a = set(5) is the source of your error.
Also, sets do not have append method. You should use a.add("data") for adding elements to the set.
To ensure that the size of set does not exceed a particular length, you can try something like this
fixed_length = 3
a=set()
for i in range(0,5):
if len(a) == fixed_length:
break
else:
a.add(int(input("enter a number")))
for index, element in enumerate(a):
print("numbers in array are", element)

credit card function errors, python: 'list' object has no attribute keys

I am working from a file import, where the input is a list of numbers
so one function feeds into another, first printing list/reading text file, second function validating if credit card is valid/invalid acc to regex, and then creating a dictionary and printing summary.
y = {}
def credit_card_validator(numbers):
for number in numbers:
result = re.findall (insert regex, number)
if result == []:
y[xx] = 'invalid'
else:
y[xx] = 'valid'
return numbers
def print_credit_card_summary(y):
for numbers in dict_o:
print(numbers+' ' + y[numbers])
return y
But I have two errors:
Error (credit_card_validator()): 'list' object has no attribute 'keys'
and:
Error (print_credit_card_summary()): list indices must be integers or
slices, not str
How can I fix this code and what am I doing wrong?
Error 1 : Right off the bat, there is an indentation error in function credit_card_validator's for loop. Solving this might solve the problem because I see no keys used for the list object.
Error 2 : The value in numbers used to address elements from dict_o is not an integer value. Always the indices of lists must be integers. Try dict_o[whatever_array_numbers_is_linked_to.index(numbers)]? This might work.

The TypeError in python

I'm trying to make a challenge for one of the courses I'm following. I'm new to programming, but I'm eager to learn.
Can you tell me in detail why this error occurs to me and how do solve it.
default_names =['Justin', 'john','Emilee', 'jim','Ron','Sandra','veronica','Wiskley']
i=0
for i in default_names:
default_names[i]=default_names[i][0].upper()
i+=1
if i==len(default_names):
break
print default_names
the error: TypeError: list indices must be integers, not str
default_names =['Justin', 'john','Emilee', 'jim','Ron','Sandra','veronica','Wiskley']
for i in range(len(default_names)):
default_names[i]=default_names[i].upper()
print default_names
What you are looking for is :
for i,s in enumerate(default_names):
or simple:
for i in range(len(default_names)):
The mistake you are doing is that when you say for i in default_names: notice that i value is a string, not int as you are trying to use.
for i in default_names:
print(i)
Will give :
OUT: Justin
john
Emilee
jim
Ron
Sandra
veronica
Wiskley
So the actual code should be, assuming you are trying to convert each string in list to Upper case :
for i in range(len(default_names)):
default_names[i]=default_names[i].upper()
EDIT : The OP wants only First char to be Upper case, and since string are immutable, change of code to :
for i in range(len(default_names)):
default_names[i]=default_names[i][0].upper() + default_names[i][1:]
As you can see in your error: TypeError: list indices must be integers, not str. It's because to access the elements of a list, you have to use the index, which is an integer. Basing on the structure of your code, you might have come from a different language. Python's for loop is different from the other languages. It doesn't increment the variable you made over the loop, but rather it iterates over the elements and passes the value to the variable. I think it would be more suitable to use a while loop with the code you made since you have initialized your i to 0. E.g.
default_names =['Justin', 'john','Emilee', 'jim','Ron','Sandra','veronica','Wiskley']
i=0
while i < len(default_names):
default_names[i]=default_names[i].upper() #removed the [0] here
i+=1
#removed the other codes here
print default_names
As you become better in python, you can find more efficient ways to do these kinds of things. The result you wanted could be simply made through
default_names = [name.upper() for name in default_names]
which simply iterates all of the names, makes it upper case and saves it back to default_names

I'm getting a TypeError: 'int' object is unsubscriptable

I got an error message from my code which says TypeError: 'int' object is unsubscriptable. After doing some research, I understand what it means, but I can't understand why there is a problem.
I narrowed the problem down to this code:
def calcNextPos(models, xcel): # and other irrelevant parameters
for i in range(len(models)):
for j in range(3):
a = xcel[i[j]]*0.5*dt*dt
# More code after this...
I verified that xcel is a list of lists of integers when the function is called, and the indexes should not be out of bounds.
What is going wrong? How can I fix it?
xcel is a two-dimensional list. The correct syntax to access the jth element of the ith sub-list is xcel[i][j], not xcel[i[j]]. The latter attempts to get the jth element of the integer i, which leads to the error described.
In the code for i in range(len(models)):, i is an integer. That makes a loop for values of i between 0 and a less than the length of models.
In the next two lines of the code, i[j] is used to access an array element, which doesn't work. Did you perhaps mean models[j] instead of i[j], like so?
for i in range(len(models)):
for j in range(3):
a = xcel[models[j]]*0.5*dt*dt
# More code after this...

The 'int' object is unsubscriptable

I have searched for nearly an hour online, but can't find anything. But I digress, line 6 keeps on returning TypeError: 'int' object is unsubscriptable. Please help me identify what causes this.
def __reassigner__(allL, currentRow, currentSpace):
changingRow=currentRow+1
newl=[-1]*24
while changingRow<8:
distance = changingRow-currentRow
newl[8:15]=allL[changingRow[0:7]] #Line 6, this one
if newl[currentSpace]==-1:
newl[currentSpace]= currentRow
if newl[currentSpace-distance]==-1:
newl[currentSpace-distance]= currentRow
if newl[currentSpace+distance]==-1:
newl[currentSpace+distance]= currentRow
allL[changingRow[0:7]]=newl[8:15]
changingRow+=1
return(allL)
The variable changingRow is an integer, but you try to slice it with changingRow[0:7]. Since this operation is not allowed on ints, you get the error.
I don't know what your intention was with that line. Maybe allL is a list of lists and you were going for allL[changingRow][0:7]?
changingRow in your code seems to be an integer (I assume that after line saying changingRow=currentRow+1). Unfortunately, in line 6, you try to obtain: changingRow[0:7], which doesn't work, since you're trying to access your integer value as if it was an array.
changingRow is an integer value. changingRow[0:7] would extract the first 7 elements of a list-like ("subscriptable") object, but an int has no such "elements" like the ones in lists and strings have.
What are you trying to achieve with changingRow[0:7]?
changingRow is an integer, you can't take indeces 0-7 from it
You can't access write changingRow[0:7] because changingRow is an integer. If you must access it using slice notation (for the first 8 digits or something) you can do str(changingRow)[0:7], but you probably have a design problem.

Categories