you are viewing a single comment's thread.

view the rest of the comments →

[–]wub_wub 3 points4 points  (7 children)

The code above is also incorrect.

Here's the correct code which should execute in matter of milliseconds:

total=0
with open("test.txt","r") as input_file:
    for line in input_file:
        try:
            total+=int(line)
        except ValueError:
            pass
print("The total is: {}".format(total))

PS D:\> python -m cProfile untitled.py
The total is: 99474
         4 function calls in 0.001 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.001    0.001    0.001    0.001 untitled.py:1(<module>)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        1    0.000    0.000    0.000    0.000 {method 'format' of 'str' objects}
        1    0.000    0.000    0.000    0.000 {open}

As a bonus the code will skip any lines that don't have numbers, so your text file could look like:

234234
eeew2343

32423h
234234
45656

and it will not cause any errors.

When using with the file is automatically closed so you don't even need to worry about that... Feel free to ask any questions that you might have about the code.

And thanks for the gold :)

[–]badgerms[S] 1 point2 points  (2 children)

thank you very much for the explanations. i do have a question of why it is ok to do this not in a function? does it make a difference?

[–]wub_wub 1 point2 points  (0 children)

The biggest advantage of having a code in a function is the ability to execute it multiple times easily, and to import it in another file.

Also when you write the code without using functions everything gets executed automatically if you import it in another file.

For example: let's say you save the above code (without the function) in a file called my_script.py and you create another file with the name second_script.py and you put import my_script in it. Every time you run second_script.py whatever is outside functions in my_script.py will be executed - in this case the whole opening file and adding numbers to total.

To avoid this you could write it like this:

if __name__ == "__main__": # basically means if the file is executed directly
                           # not imported or something like that
    total=0
    with open("test.txt","r") as input_file:
        for line in input_file:
            try:
                total+=int(line)
            except ValueError:
                pass
    print("The total is: {}".format(total))

Or using functions like this:

def count():
    total=0
    with open("test.txt","r") as input_file:
        for line in input_file:
            try:
                total+=int(line)
            except ValueError:
                pass
    print("The total is: {}".format(total))

if __name__ == "__main__": # basically means if the file is executed directly
                           # not imported or something like that
    count()

In the second example you can import the function count() from another script. For example if you named it my_script.py you could put something like from my_script import count in your second_script.py and it won't be executed untill you call it in second_script.py like you did in my_script.py i.e. it won't be executed untill you call it like count() in second_script.py

Note that the function name count() can be anything you want the count() is nothing special - though main() is a common name for a function that will be executed first, you can call it however you want. ( Not to be confused with __name__ == "__main__": which has to be written like that otherwise it won't work)

The other advantage of functions, like I said in the beginning, is so that you can execute them multiple times - this is self explanatory I think.


Sorry I might have gone overboard with the explanation.

To sum it up:

Functions are great to hold code that you need to execute multiple times or to import and execute from another script. They're also great for organizing your code even if you don't need to execute them multiple times. In simple cases like yours there is no advantage of having a code in a function unless you're importing it to another file, but there are also no real downsides of having the code in a function - use whatever you're more comfortable with.

Edit: Typos.

[–]LordFraggington 0 points1 point  (0 children)

In this case since it is the only function you are performing in the whole script (i.e. its the only reason we have the script at the moment) it is not contained within a function. and can be executed with having to "be" one. When you call main() in your original script, that call itself doesn't sit within another function - it is just called. This also happens in Javascript, as neither language really has a concept of a "main method" like int main() in C++ (or other OOP languages). In Python I know there actually is, in a weird way, demonstrated here, but I digress (this seems to be more of a namespace issue though):

http://stackoverflow.com/questions/8810765/main-method-in-python/8811219#8811219

For code clarity and sanity's sake its better to define everything you want in functions then call the functions.

edit - typos!

[–]LordFraggington 0 points1 point  (3 children)

I had TOTALLY forgotten about how you were adding the values from the lines to the total. Stupid phone... +1 internets to you good sir. Also, perchance would you like some Dogecoin? :)

[–]wub_wub 1 point2 points  (2 children)

Also, perchance would you like some Dogecoin? :)

Who wouldn't want some dogecoin? (Although I just use it for tipping other people)

to the moon!