Python Type error! - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Python Type error! (/thread-24444.html) |
Python Type error! - SamAnw - Feb-14-2020 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 += 1My 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? RE: Python Type error! - buran - Feb-14-2020 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
RE: Python Type error! - SamAnw - Feb-14-2020 (Feb-14-2020, 02:13 PM)buran Wrote: what do you think lines 5 and 6 are doing? You assign When I take out the lines 5 and 6, I have another type error: Thank you!
RE: Python Type error! - stullis - Feb-14-2020 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 += 1Now, 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. RE: Python Type error! - buran - Feb-14-2020 When you read from file you get str , you cannot compare (greater than/less than) str and intyou need to convert what you read from file to a numeric type |