Python 'list out of index error' - python-3.x

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.

Related

TypeError: method() takes 0 positional arguments but 1 was given

I wrote an input function python program,
But when run that code , IDE show that, "this function need to pass argument"
Even though ,I didn't declare any argument enter image description here
please help me how to solve this problem , Thank you in advance
list_number = list()
def input():
while True:
try:
number = input("Enter your number in to list = ")
if number == "Quit":
break
number = int(number)
list_number.append(number)
print(list_number)
except ValueError as e:
print(e)
def diagram():
display = ""
for i in list_number:
for j in range(i):
display = display +"#"
print(display)
display = ""
input()
diagram()
Several errors are noticed at glance:
mixture of namespace
You declared list_number as a global variable, but you cannot set value to it
directly insides a function. Instead, you can let the function return a value,
or use global statement to temporary allow a function to set a value to
a global variable temperary.
Read more on offical document, or search keyword python namespace for
relative articles.
name collision on builtin keyword
Some special word are reserved by python and could not be used as variable or
function name, input is amoung them.
BTW: The title of your question and example code layout is confusion! Follow the
tour to learn how to ask a better question and improve layout, so that people
can help you out.
Example code: though the test part has some bug I don't solved...
# remove: move it to a main progress for future design
# list_number = list()
# rename: input is a reserved name of builtins, pick another word
def myinput(*pargs):
if pargs:
for arg in pargs:
try:
yield int(arg)
except ValueError:
pass
else:
count = 0
while True:
# move out of `try` statement as it won't raise any exceptions
# imply lowercase for easier string comparison
userinput = input("Enter your number in to list: ").lower()
if userinput in ['quit', 'q']:
# for interactive, give user a response
print("Quit input procedure. Preparing Diagram...")
break
try:
number = int(userinput)
except ValueError:
# raise a error and the output will print to output by default
# there is no need to `print` an error
# and, for improve, you can raise a more specific message
# and continue your program
msg = "The program wants a number as input, please try again.\n"
msg += "Type `Quit` to exit input procedure."
print(msg)
continue
except KeyboardInterrupt:
msg = "You pressed Interrupt Keystroke, program exit."
print(msg)
return 0
# print a message and pass the value intercepted
count += 1
print("%d: number %d is added to queue." % (count, number))
yield number
def diagram(numbers):
# there is no need to iter a list by index
# and I am **not** sure what you want from your origin code
# if what you wnat is:
# join number with "#" sign
# then just use the builtins str.join method
# valid: is_list_like
if is_list_like(numbers):
numstr = map(str, numbers)
ret = "#".join(numstr)
else:
ret = "Nothing to export."
return ret
def is_list_like(obj):
"""fork from pandas.api.types.is_list_like,
search c_is_list_like as keyword"""
return (
# equiv: `isinstance(obj, abc.Iterable)`
hasattr(obj, "__iter__") and not isinstance(obj, type)
# we do not count strings/unicode/bytes as list-like
and not isinstance(obj, (str, bytes))
)
def main(*pargs):
# get a generator of user input
# if passed in values, accept parameter as user input for test
msgout = ""
if pargs:
# bug: test input not filtered by int() function
list_number = list(myinput(pargs))
print("Run builtin test module.")
else:
list_number = list(myinput())
count = len(list_number)
# process your input by whatever means you need
if count == 1:
msgout += "Received %d number from user input.\n" % count
else:
msgout += "Received %d numbers from user input.\n" % count
msgout += "The diagram is:\n%s" % diagram(list_number)
print(msgout)
def test():
"""simulate user input"""
userinputs = [
['a', 1, 5, 4, 9, 'q'],
[999, 'Quit'],
['q'],
]
for userinput in userinputs:
main(*userinput)
# test bug:
# 1. charactor is printed as output, too
if __name__ == "__main__":
# remove test() if you don't need it
test()
main()
Well I would change your function name from input to something else because you cannot have any function named anything from base python named in your function, This is probably the reason for your error.
Like the others said, input() is a builtin function in Python. Try this following code:
list_number = list()
def input_func():
while True:
try:
number = input("Enter your number in to list = ")
if number == "Quit":
break
number = int(number)
list_number.append(number)
print(list_number)
except ValueError as e:
print(e)
def diagram():
display = ""
for i in list_number:
for j in range(i):
display = display + "#"
print(display)
display = ""
input_func()
diagram()
Also, nice to note that try should be used more precisely only where the exception is expected to be thrown. You could rewrite input_func with that in mind, such as:
def input_func():
while True:
number = input("Enter your number in to list = ")
if number == "Quit":
break
try:
number = int(number)
except ValueError as e:
print(e)
else:
list_number.append(number)
print(list_number)

Create a empty list. Populate the list with couple of numbers until the input is -1

Example for above question:
Explanation:
User is giving some random input(negative and positive). i am storing all in a list and I want only positive number should be present. remove all the negative number
What i have tried:
input_1st = []
var = int(input())
for j in range (0, var):
ele = int(input())
input_1st.append(ele)
for i in input_1st:
if (i>0):
lst.append(i)
print(lst)
the error I have got:
thankyou
Just read all input and check the value.
result = []
while True:
try:
value = int(input())
if value > 0:
result.append(value)
except EOFError:
break
print(result)

Index Error Problems

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)

How to keep the ID the same for a list when appending

Trying to obtain a list without changing the ID of the original list and the list can only contain spaces between each element.
I keep getting this error and I am unable to find a way to keep its ID the same whilst having only spaces in between each element whilst printing it out.
newlist=[array[x] for x in range(len(array)) if x !=0]
array=[]
array.append(newlist)
newlist=[]
print(' '.join(array))
TypeError: sequence item 0: expected str instance, list found
The error message is for the last line
while ans:
ans=input("\nSelect an option?\n")
if ans=="A":
if len(array) < 10:
A = list(input('\nInput string: \n'))
if len(A) == 1 and str(A):
array += A
if len(array) == 10:
print( "Invalid input\n")
elif ans=="P":
print(' '.join(array))
elif ans=="N":
newlist=[array[x] for x in range(len(array)) if x !=0]
array=[]
array.append(newlist)
newlist=[]
print(' '.join(array))
elif ans=="M":
print(id(array))
This is what half the code looks like.
What I intend is that the ID should always stay the same and when N is inputted the first element of the array is removed
No use of pop, del, remove, slicing and index is allowed
What about "clear" then? :) Python 3.3 and higher
elif ans=="N":
newlist=[array[x] for x in range(len(array)) if x !=0]
array.clear()
array.extend(newlist)
print(' '.join(array))

Calculating the average by inputing values in a file, code produces wrong output

'''This simple program will calculate the average using files'''
num = 3
try: #set an exception in case of a file Error
while num >=0: '''read in values and place them in a file'''
value = int(input("Enter values: "))
my_file = open('my_data.txt', 'w+')
my_file.write(str(value))
numbers = my_file.readlines()
num -=1
my_file.close()
except IOError:
print('FILE FAILURE')
'''iterate to find the sum of the values in a file'''
total = 0
for ln in numbers:
total += int(ln)
'''Calculate the average'''
avg = total/len(numbers)
print("The average is %d"%(avg))#FIXME: does not calculate average
You are opening a file for write, then read from it, and assign it to a variable numbers. However this variable is not a list, although you treat it as a list when you do for ln in numbers.
Furthermore, you should end a line written to file with \n
Based on how I understand your code, you want to:
Get user input, and write it to file
From the file, read the numbers
From the numbers calculate the average
There is a statistics module, with the function mean, which will do the calculation part for you. The rest, you could (should) structure like the three bullet points above, something like this:
from statistics import mean
def inputnumbers(itterations, filename):
with open(filename, 'w') as openfile:
while itterations > 0:
try:
value=int(input("value->"))
except ValueError:
print('Numbers only please')
continue
openfile.write(str(value) + '\n')
itterations -= 1
def getaveragefromfile(filename):
numbers = []
with open(filename, 'r') as openfile:
for line in openfile.readlines():
numbers.append(int(line.replace('\n','')))
return mean(numbers)
def main():
filename = r'c:\testing\my_data.txt'
itterations = int(input('how many numbers:'))
inputnumbers(itterations, filename)
average = getaveragefromfile(filename)
print(average)
if __name__ == '__main__':
main()

Resources