Python Forum

Full Version: Python Type error!
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello!

I've been working on this program and I don't know why, but there seems to be a problem with it...

txt = "Prob05.in.txt"
msg = open(txt, "r")
msg = msg.read()
h = msg.split("\n")
h=int
g = float
first = True
unSentence = 1
countSentence = 1
while(countSentence <= h[0]):
      while (unSentence <= g[0]):
          Sentence = '\n'
          seq = input (Sentence.format (unSentence))
          print((g[i] - min(lst))/(max(lst) - min(lst))*255)
          unSentence += 1
      countSentence += 1
My file input is:

2
5
0.0
25.0
50.0
75.0
100.0
6
12.3
-67.1
122.8
428.4
-15.9
221.0


But when I try to run the program, there is an error:

Traceback (most recent call last):
File "C:/Users/admin/Desktop/Collège Sainte Marcelline Prog (8)/Problème 05.py", line 10, in <module>
while(countSentence <= h[0]):
TypeError: 'type' object is not subscriptable

Anyone has got an idea?
what do you think lines 5 and 6 are doing? You assign int to a name h, so the name h now points to the type int and when you try to subscribe it you get the error. You will get the same error later on for g
(Feb-14-2020, 02:13 PM)buran Wrote: [ -> ]what do you think lines 5 and 6 are doing? You assign int to a name h, so the name h now points to the type int and when you try to subscribe it you get the error. You will get the same error later on for g

When I take out the lines 5 and 6, I have another type error:
Error:
Traceback (most recent call last): File "C:/Users/admin/Desktop/Collège Sainte Marcelline Prog (8)/Problème 05.py", line 8, in <module> while(countSentence <= h[0]): TypeError: '<=' not supported between instances of 'int' and 'str'
Thank you!
You'll need to convert the text retrieved from the file into numbers for that comparison. In Python, we have the int() and float() functions to do this.

txt = "Prob05.in.txt"
msg = open(txt, "r")
msg = msg.read()
h = msg.split("\n")
g = 
first = True
unSentence = 1
countSentence = 1
while countSentence <= int(h[0]):
      while unSentence <= float(g[0]):
          Sentence = '\n'
          seq = input (Sentence.format (unSentence))
          print((g[i] - min(lst))/(max(lst) - min(lst))*255)
          unSentence += 1
      countSentence += 1
Now, the interpreter did not reach line 11 when you last ran it due to the error on line 10. I'm not sure what g is intended to be so I cannot provide guidance on that.
When you read from file you get str, you cannot compare (greater than/less than) str and int
you need to convert what you read from file to a numeric type