samedi 23 mars 2019

How exactly if statements and their accompanying return statements roll through memory? details below

This is a general question. If I write if(word in txt_file): return word, would the program go through txt_file twice? Once to see if the word is there, and again from the beginning to retrieve it? Or would the cursor stay where the if statement left off? An idea I had to be sure it only went through once is by using try: try(return word), except exception (print word not found) which works, because this way it should only go through once.

I understand how to write and use if statements, but my question is more about how the computer uses them to go through the memory.

Here I have two items that do the same thing: search txt_file for an input word, if it's not found print(not found), otherwise return the word. The program may seem silly "why search a file for a word to just return the same word?" but the question is just to help me understand whether or not if statements go through data twice - once to check if true/false, and again to actually return the item if found (or if the program remembers at what index the if statement left off). This should help you visualize my thought process, or not, I don't know. I have to include this haha.

'''

if word in txt_file:
    return word
else:
    print("Sorry word not found bud")


   OR


try:
    return txt_file[word]
except Exception:
    print("Sorry bud word's not here")

'''

I expect the if statement to go through the data file once looking for the desired element, and then the return statement goes through the data again to retrieve the desired element

Aucun commentaire:

Enregistrer un commentaire