Functions!

Posted 21 November 2012 - 06:50 PM

I want my program to to have a main function that opens and read a file(which I have running properly), then calls the build_dictionary function(not quite sure how), which takes the file reads the last names and count how times they occur(which I also have running). The build_dictionary function ignores blank lines and any lines that do not contain a person’s name,(not sure if I did that correctly.) Functions aren't my favourite thing, can some help me with this.

Replies To: Functions!

Re: Functions!

Posted 21 November 2012 - 10:25 PM

What does the input data look like? The check for a blank line is
len(line.strip()) > 0
You have a lot of unnecessary code in your function. Start by printing each line as it is read, split it and print that and then figure out how to determine where the last name is or if there is no last name. Post back with some updated code to do this much at least.

Re: Functions!

Posted 22 November 2012 - 09:35 AM

I tried the first half of the code and it works much nicer and its easier, but when you put everything together it doesn't work I get error in code, I've tried inputting many files that i have but i keep getting the same thing

Re: Functions!

Posted 22 November 2012 - 10:03 AM

Yeah. Okay. So you're clearly using Python 2.

In Python 2, input() tries to evaluate whatever you type in as Python code. You should use raw_input() instead, which returns the input as a string. Or you could use Python 3, where input() does as raw_input() in Python 2, returning a string.

Re: Functions!

Posted 22 November 2012 - 10:15 AM

You're catching the error that tells you what the problem is. You'll get "Error in code" instead of a pretty stack trace, use that to find out what your errors are.

As a rule of thumb, you should only catch things that are beyond your control, not the result of a programming bug. Check if the file exists first, and the program is logically correct instead of leaving it to chance and giving a vague error message.

Re: Functions!

Posted 22 November 2012 - 11:22 AM

Take the try-except block out for a minute. What does it do then? I am guessing it will probably help you pinpoint the error by printing a stack trace of the Python program, and what caused an error to be caught.