Update:
You also need to assign the return value from the function to a variable before you can use it subsequently:
CountHands(Hands_Played)
print "Number of Hands Played: %s" % Hands_Played
Should be
Hands_Played = CountHands(Hands_Played)
print "Number of Hands Played: %s" % Hands_Played
Otherwise you never receive the count, and you just end up displaying the initial value you set at the start of the program (0
).
For that matter, unless you are maintaining a count between function calls, you don't really need a parameter for this function. Just create the Hand_Played variable locally inside, at the start of the function, and return it as you do now. You can remove the parameter from your function header and your call and you should be all set.
--- previous, still applies.
Instead of:
if "starts." in Hand_History_File:
you probably want
if "starts." in line:
Also, don't forget to explicitly close the file when you are done with it. I.e., make a call Hand_History_File.close()
before you return from the function.
Better yet, consider using the with
construct to manage you files. It will close your files for you automagically at the end of the block when you are done with it, or you encounter an exception. And you could also process your file line-by-line and simplify your code some more. I.e., a streamlined version, close to your original design of your function/code:
def CountHands():
Hands_Played = 0
with open(r"C:\xxxxx\blah_blah.txt") as Hand_History_File:
for line in Hand_History_File: # process file line-by-line
if "starts." in line:
Hands_Played += 1
return Hands_Played
Hands_Played = CountHands()
print "Number of Hands Played: %s" % Hands_Played
Notes:
I use a "raw" string (with the 'r
' in front of your path) to prevent Python from interpreting certain characters combinations the string. I don't use "r" in the open
call as it's the default when opening files. I use the +=
operator to shorten your increment. And your file is closed when you leave the block started with with
.