Note that there are some explanatory texts on larger screens.

plurals
  1. POIssue reguarding python objects and nested lists
    primarykey
    data
    text
    <p>Okay i will try to provide as much information as i can to make this easier for whoever has the time to give me some advice, hopefully one of you fine people will be able to help me.</p> <p>I'm writing an arithmetic training sort of program. The idea of the program is that the user creates a 'session', they specify the math operation they want(/,*,-,+), the amount of equations, the range for the number generator(2 numbers, for example if they specify 1 and 5, all the numbers for the equations that get randomized will be in this range.).</p> <p>Then the session is generated and the user completes the equations, at the end the user can check his answers and is presented with accuracy percentage, time taken to complete the session and the exact date and time the session was created.</p> <p>The program is written in object orientated programming, with each session being an object. These objects are contained within a list which is pickled. The idea being that the user can go back over previous sessions and track their improvement or whatever.</p> <p>The problem: I'm having an impossible time iterating over each object and printing out all it's data.</p> <p>The code for my program is as follows:</p> <pre><code>import pickle,time,random class Session: def __init__(self,amount,operation,numgen_range): start_time = [int(time.strftime('%M', time.gmtime())),int(time.strftime('%S', time.gmtime()))] ID = main.get_id() + 1 accuracy = 0 rights = 0 equations_data = [] duration = [0,0] datetime = time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime()) self.session_data = [ID,amount,operation,numgen_range,datetime,accuracy,rights,equations_data,duration] main.save_id() if self.session_data[2] == '+': for i in range(self.session_data[1]): a = random.randint(self.session_data[3][0],self.session_data[3][1]) b = random.randint(self.session_data[3][0],self.session_data[3][1]) answer = a + b user_answer = int(input('{0} + {1} = '.format(a,b))) if answer == user_answer: rightwrong = True self.session_data[6] += 1 else: rightwrong = False eq_data = [a,self.session_data[2],b,answer,user_answer,rightwrong] self.session_data[7].append(eq_data) elif self.session_data[2] == '*': for i in range(self.session_data[1]): a = random.randint(self.session_data[3][0],self.session_data[3][1]) b = random.randint(self.session_data[3][0],self.session_data[3][1]) answer = a * b user_answer = int(input('{0} * {1} = '.format(a,b))) if answer == user_answer: rightwrong = True self.session_data[6] += 1 else: rightwrong = False eq_data = [a,self.session_data[2],b,answer,user_answer,rightwrong] self.session_data[7].append(eq_data) elif self.session_data[2] == '-': for i in range(self.session_data[1]): a = random.randint(self.session_data[3][0],self.session_data[3][1]) b = random.randint(self.session_data[3][0],self.session_data[3][1]) answer = a - b user_answer = int(input('{0} - {1} = '.format(a,b))) if answer == user_answer: rightwrong = True self.session_data[6] += 1 else: rightwrong = False eq_data = [a,self.session_data[2],b,answer,user_answer,rightwrong] self.session_data[7].append(eq_data) elif self.session_data[2] == '/': for i in range(self.session_data[1]): a = random.randint(self.session_data[3][0],self.session_data[3][1]) b = random.randint(self.session_data[3][0],self.session_data[3][1]) answer = a / b user_answer = int(input('{0} / {1} = '.format(a,b))) if answer == user_answer: rightwrong = True self.session_data[6] += 1 else: rightwrong = False eq_data = [a,self.session_data[2],b,answer,user_answer,rightwrong] self.session_data[7].append(eq_data) end_time = [int(time.strftime('%M', time.gmtime())),int(time.strftime('%S', time.gmtime()))] if start_time[0] &gt;= end_time[0]: self.session_data[8][0] = start_time[0] - end_time[0] else: self.session_data[8][0] = end_time[0] - start_time[0] if start_time[1] &gt;= end_time[1]: self.session_data[8][1] = start_time[1] - end_time[1] else: self.session_data[8][1] = end_time[1] - start_time[1] self.session_data[5] = (self.session_data[6] / self.session_data[1]) * 100 print('You got {0} problems correct out of {1}, your accuracy percentage was {2}%.\nYou took {3} minutes and {4} seconds to complete the session.'.format(self.session_data[6],self.session_data[1],int(self.session_data[5]),self.session_data[8][0],self.session_data[8][1])) while True: try: i = int(input('Enter 1 to check answers or 2 to return to the menu: ')) if i == 1: main.util = True for i in self.session_data[7]: if i[5]: rw = 'CORRECT' else: rw = 'INCORRECT' print('{0} {1} {2} = {3} Your Answer: {4} - {5}\n'.format(i[0],i[1],i[2],i[3],i[4],rw)) elif i == 2: main.util = False pass else: raise ValueError break except ValueError: print(main.input_error_msg) continue with open('data/saved_sessions.txt','rb') as file: saved_sessions = pickle.load(file) class main: util = None input_error_msg = 'You entered an invalid input, try again.' def create(): print('Create Session.') while True: try: amount = int(input('Enter the amount of equations you want: ')) if amount &lt; 1: raise ValueError if amount &gt; 50: print('Sorry, the limit for equation amounts is 50, try again.') continue break except ValueError: print(main.input_error_msg) continue while True: try: operation = input('Enter operation: ') if operation == '': print('You must specify an operation for the session!') continue if len(operation) != 1: print(main.input_error_msg) continue if "+" not in operation: if "-" not in operation: if "*" not in operation: if "/" not in operation: print("You failed to enter a valid equation type. Please try again.") continue break except ValueError: print(main.input_error_msg) continue numgen_range = [0,0] while True: try: numgen_range[0] = int(input('Enter base range number: ')) if numgen_range[0] &lt; 0: raise ValueError break except ValueError: print(main.input_error_msg) continue while True: try: numgen_range[1] = int(input('Enter ceiling range number: ')) if numgen_range[1] &lt; numgen_range[0]: print('Sorry the ceiling range number cannot be larger than the base range number.') continue break except ValueError: print(main.input_error_msg) continue while True: try: i = int(input('Enter 1 to generate this session or 2 to enter new specifications: ')) if i == 1: saved_sessions.append(Session(amount,operation,numgen_range)) main.pickle_sessions() if main.util: main.menu() else: main.menu(rmenu=True) elif i == 2: main.create() else: raise ValueError break except ValueError: print(main.input_error_msg) continue def get_id(): try: with open('data/id_count.txt','rb') as file: count = pickle.load(file) except IOError: pass else: return count def save_id(): try: with open('data/id_count.txt','wb') as file: pickle.dump(ID,file) except IOError: pass else: print('id count pickled.') def view_archive(): print('View Session Archive') #view archive code to go here. def menu(rmenu=False): if rmenu: while True: try: i = int(input('Enter 1 to return to the menu: ')) if i == 1: main.menu() else: raise ValueError break except ValueError: print(main.input_error_msg) continue else: print('Menu -[1]Create Session.[2]View Session Archive.[3]Exit.') while True: try: i = int(input('Enter choice: ')) if i == 1: main.create() elif i == 2: main.view_archive() elif i == 3: quit() else: raise ValueError break except ValueError: print(main.input_error_msg) continue def pickle_sessions(): try: with open('data/saved_sessions.txt','wb') as file: pickle.dump(saved_sessions,file) except IOError: pass else: print('Sessions have been pickled.') def start(): if __name__ == '__main__': main.menu() main.start() </code></pre> <p>Now what i want to do is, iterate over each object, go into it's session_data list, iterate over this and print out each bit of data, then iterate over the equations_data list which is element 7 in the session_data list, keeping in mind that equations_data is populated with yet more lists which contain each individual equation's data, so i want to iterate over that.</p> <p>To sum it all up: print out all the data from each object.</p> <pre><code>I thought something like: for i in saved_sessions: for y in i.session_data: #print out elements then loop over equations_data on line below for x in i.session_data[7]: #print out elements </code></pre> <p>However this dosn't work, basically i cannot work out how to access the lists inside of the equations_data list, which is self.session_data[7], but when trying to iterate over this im returned with an index error.</p> <p>Like i said what i want to do display each session one by one like:</p> <pre><code>ID: 1 Date: some date Time: some time Operation: + Equations: 5 Right Answers: 5 Accuracy: 100% Time Taken: 15 seconds Equations: 1 + 5 = 6 Your Answer: 6 1 + 6 = 7 Your Answer: 7 1 + 7 = 8 Your Answer: 8 1 + 8 = 9 Your Answer: 9 1 + 9 = 10 Your Answer: 10 </code></pre> <p>Any help regarding this problem would be hugely appreciated. Also i'm very keen on some brutally honest feedback on every aspect of my programming. Constructive criticism is encouraged. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload