Index Error Problems - python-3.x

So I'm making a calculator that takes in a string and checks to see if it has certain words like add or subtract and then finding integers. However, in my current code, I run it and get this error message:
Traceback (most recent call last):
File "python", line 1, in <module>
File "python", line 7, in calculator
IndexError: string index out of range
The code is typed out below.
def calculator(string):
if "add" in string or "Add" in string:
total = 0
for i in range(len(string)): #loop for length of string
try:
if type(int(string[i])) == int: #checks to see if there is a number in the string
try:
if type(int(string[i+1])): #checks to see if the number is 2 digits
number_1 = int(string[i])*10
except ValueError:
number_1 = int(string[i])
total = total + number_1 #adds all the numbers to a total variable
except ValueError:
pass
print (total)
If someone could help me out that would be great! Thanks so much!

I believe your problem is with type(int(string[i+1]))
as you have a for loop, i can already be pointing to the last index of string. When you add 1 to that, you get an IndexError
Example:
s = 'blabla'
for i in range(len(s)):
print(s[i])
Output:
b
l
a
b
l
a
Example:
s = 'blabla'
for i in range(len(s)):
print(s[i+1])
Output:
l
a
b
l
a
File "C:\Users\python\scratch\untitled-1.py", line 3, in <module>
print(s[i+1])
builtins.IndexError: string index out of range

Sat down with my friend(#Kay Ace Elits) and realised a bunch of things were amiss but we pieced this together
def calculator(string):
if "add" in string:
total = 0
first_string = "" # before a in add
second_string = "" # after d in add
value_list = string.split('add')
for number in value_list:
total += int(number)
print(total)
elif "Add" in string:
total = 0
first_string = ""
second_string = ""
value_list = string.split('Add')
for number in value_list:
total += int(number)
print(total)
### our test your can modify for other factors
### like spellings and different operations
string = "22add43"
calculator(string)

Related

Unsupported operand type for sum() function

I was working on a simple project to get me more acquainted with Python since it's been a while and the new semester has started.
import math
count = input('Please enter the number of grades: ')
grade_list = []
while count != 0:
grade = input('What was the grade for the first test?: ')
grade_list.append(grade)
count = int(count) - 1
def mean(x):
grade_total = int(sum(x))
grade_count = int(len(x))
mean = int(grade_total) / int(grade_count)
return mean
print(mean(grade_list))
Here's the error I keep running into:
Traceback (most recent call last):
File "C:\Users\hattd\Documents\Python Projects\miniproject1.py", line 17, in <module>
print(mean(grade_list))
File "C:\Users\hattd\Documents\Python Projects\miniproject1.py", line 12, in mean
grade_total = int(sum(x))
TypeError: unsupported operand type(s) for +: 'int' and 'str'
I thought that turning the variables into integers would stop this from happening? What am I missing here?
You never "turn the variables into integers". You read a string from the user and append that to grade_list, and then you pass grade_list (a list of strings) to your mean function, where you eventually pass it to sum by calling int(sum(x)).
You can convert user input to integers by writing grade_list.append(int(grade)):
grade_list = []
count = int(input('Please enter the number of grades: '))
for _ in range(count):
grade = input('What was the grade for the first test?: ')
grade_list.append(int(grade))
This gives us a list of integers instead of a list of strings.
I've applied the same logic to the count variable as well; this simplifies the code in the while loop since we don't need to repeatedly cast count to an integer.
If you enter something that isn't an integer at either of these prompts, your code will fail with a ValueError exception:
Traceback (most recent call last):
File "/home/lars/tmp/python/grades.py", line 15, in <module>
count = int(input("Please enter the number of grades: "))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'a'
If you'd like a friendlier response, you can write a function to read an integer from the user that will re-prompt if they enter an invalid value. Something like:
def get_int_with_prompt(prompt):
while True:
try:
val = int(input(prompt))
return val
except ValueError:
print("Please enter a valid integer.")
You would use it like:
count = get_int_with_prompt("Please enter the number of grades: ")
Note that with these changes, you have a bunch of calls to int in your mean function that are no longer necessary. A cleaned up version of your code might look like:
grade_list = []
count = int(input("Please enter the number of grades: "))
for _ in range(count):
grade = input("What was the grade for the first test?: ")
grade_list.append(int(grade))
def mean(x):
grade_total = sum(x)
grade_count = len(x)
mean = grade_total / grade_count
return mean
print(mean(grade_list))
Of course, there is a statistics.mean function, as well:
import statistics
grade_list = []
count = int(input("Please enter the number of grades: "))
for _ in range(count):
grade = input("What was the grade for the first test?: ")
grade_list.append(int(grade))
print(statistics.mean(grade_list))
And consider some of the answers here if you'd like to ask for something other than "the first test" every time.

How can i adjust this code to python 3 for palindrome numbers?

# Python program to count and
# print all palindrome numbers in a list.
def palindromeNumbers(list_a):
c = 0
# loop till list is not empty
for i in list_a:
# Find reverse of current number
t = i
rev = 0
while t > 0:
rev = rev * 10 + t % 10
t = t / 10
# compare rev with the current number
if rev == i:
print (i),
c = c + 1
print
print ("Total palindrome nos. are" + str(c))
print
def main():
list_a = [10, 121, 133, 155, 141, 252]
palindromeNumbers(list_a)
list_b = [ 111, 220, 784, 565, 498, 787, 363]
palindromeNumbers(list_b)
if __name__ == "__main__":
main() # main function call
This code, obtained from
https://www.geeksforgeeks.org/all-palindrome-numbers-in-a-list/, has been written in Python 2.
When I run this program in Python 3.6 it returns the value as 0 for both lists.
Can someone tell me how to change it to be compatible with Python 3?
One of the important changes between Python2 and Python3 is integer division, that in Python2 returns a truncated, integer result while in Python3 returns a floating point number. To have a real integer division you have to use a double slash, "//".
In summary, change the line t = t/10 to t = t//10.
Ok, so I have changed the code a bit using a different method to check if the number is the same reversed... I tried not to change too much of your code...
The function reverse() just returns the string given to it reversed...
If I'm not mistaken the function makes a list out of the str by split function then [::-1] gives the list reversed...
def reverse(str):
return str[::-1]
def palindromeNumbers(list_a):
c = 0
# loop till list is not empty
for i in list_a:
# Find reverse of current number
t = i
t = int(reverse((str(t))))
if t == i:
c += 1
print ("Total palindrome nos. are " + str(c))
def main():
list_a = [10, 121, 133, 155, 141, 252]
palindromeNumbers(list_a)
list_b = [ 111, 220, 784, 565, 498, 787, 363]
palindromeNumbers(list_b)
if __name__ == "__main__":
main() # main function call
Try it out! I hope you find this helpful...
I first converted the number to an iterable string str(i). Then I shortened the for loop by only comparing the first half of the number t[a] to the second half of the number t[~a], and then using all() to check that all of the comparisons were true. (using Python 3.6.8)
for i in list_a:
# convert interger to iterable string
t = str(i)
# compare first half of the number to second half of the number
if all([t[a]==t[~a] for a in range(len(t)//2)]):
print (i),
c = c + 1

input error in Python3.6

t = int(input())
while t:
qu , pt = input().split(' ')
qu = int(qu)
pt = int(pt)
sd = []
for i in range(0,qu):
x = int(input()) # I think I am getting problem in this part of
sd.append(x)
hd , cw = 0 , 0
diff = pt / 10
cwk = pt / 2
for i in range(0,qu):
if sd[i] <= diff:
hd += 1
else:
if sd[i] >= cwk:
cw += 1
if hd == 2 and cw == 1:
print ('yes')
else:
print('no')
t -= 1
When I try to give input like '1 2 3' I get an an error like this
Traceback (most recent call last):
File "C:/Users/Matrix/Desktop/test.py", line 8, in <module>
x = int(input())
ValueError: invalid literal for int() with base 10: '1 2 3'
Why am I seeing this problem ? How do I rectify this ?
The issue is that you're passing it a string rather than an integer. When you typed "1 2 3," you left spaces, which are considered characters. Spaces cannot be cast as integers. If your set on having the input as number space number space number space, then I suggest you split the sentence at the whitespace into a list.
def setence_splitter(user_input):
# splits the input
words = text.split()
Now you have the list, words, which will have each individual number. You can call each individual number using its index in words. The first number will be words[0] and so on.

Python 'list out of index error'

I had written a code to read data from file for interpolation but when i run the program is saying list out of index error at "pointsx.append(float(words[0])):
with open("points.dat","r") as f:
data = f.readlines()
pointsx = []
pointsy = []
for line in data:
words=(line.split())
pointsx.append(float(words[0]))
pointsy.append(float(words[1]))
x = float(input('Enter the value of X:\n'))
i=0
lenx=len(pointsx)
if x<pointsx[0]:\n
print("this Particular value of X is lower than the range of interpolation \n")
elif x>pointsx[lenx-1]:
print("This particular value of x is higher than the range of interpolation\n")
else:
for i in range(lenx-1):
if(x<=pointsx[i]):
break;
y=pointsy[i-1]+((pointsy[i]-pointsy[i-1])/(pointsx[i]-pointsx[i-1]))*(x-pointsx[i-1])
print("The required value of y is ",y,"\n")
f.close()
Concluding from your comment, words=(line.split()) fills words with []. Therefore, pointsx.append(float(words[0])) tries to reach the first element of words which throws the exception.
Check the size of words before that line.

Cumulative total from user's input string

I have tried to write a function that takes sequence of integers as input from the user and returns cumulative totals. For example, if the input is 1 7 2 9, the function should print 1 8 10 19. My program isn't working. Here is the code:
x=input("ENTER NUMBERS: ")
total = 0
for v in x:
total = total + v
print(total)
and here is the output:
ENTER NUMBERS: 1 2 3 4
Traceback (most recent call last):
File "C:\Users\MANI\Desktop\cumulative total.py", line 4, in <module>
total = total + v
TypeError: unsupported operand type(s) for +: 'int' and 'str'
I don't know what this error means. Please help me to debug my code.
This code will work. Remember: read the code and learn how it works.
x = input("Enter numbers: ") #Take input from the user
list = x.split(" ") #Split it into a list, where
#a space is the separator
total = 0 #Set total to 0
for v in list: #For each list item
total += int(v) #See below for explanation
print(total) #Print the total so far
There are two new things in this code:
x.split(y) splits x up into a list of smaller strings, using y as the separator. For example, "1 7 2 9".split(" ") returns ["1", "7", "2", "9"].
total += int(v) is more complicated. I'll break it down more:
The split() function gave us an array of strings, but we want numbers. The int() function (among other things) converts a string to a number. That way, we can add it.
The += operator means "increment by". Writing x += y is the same as writing x = x + y but takes less time to type.
There is another problem with the code: You say you need a function, but this is not a function. A function might look like this:
function cumulative(list):
total = 0
outlist = []
for v in list:
total += int(v)
outlist.append(total)
return outlist
and to use it:
x = input("Enter numbers: ").split(" ")
output = cumulative(x)
print(output)
but the program will work just fine.
Cumulative totals
input_set = []
input_num = 0
while (input_num >= 0):
input_num = int(input("Please enter a number or -1 to finish"))
if (input_num < 0):
break
input_set.append(input_num)
print(input_set)
sum = 0
new_list=[]
for i in range(len(input_set)):
sum = sum + input_set[i]
new_list.append(sum)
print(new_list)

Resources