Ask your own question, for FREE!
Computer Science 17 Online
OpenStudy (anonymous):

Python 3 Help Current code posted inside along with my .txt file to go with it. My problem is that when it prints out the information from the text file, It currently prints out for 'region' as 'region: LA 150 120 105' but i need it to print for 'region' as just 'region: LA' and the other three values are three different value types.

OpenStudy (anonymous):

Current Code: ``` def get_input_filename(): filename = input("Enter your input file name: ") return filename def print_report_header(header1,header2): #header1 = print(format( 'Basic','>20s'),format('Educational','>20s'),format('Annual','>14s')) #header2 = print(format('Region','10s'), format('Subscriptions','4s'), format('Supplement','>15s'), format('Update','>15s')) return header1,header2 def read_data(in_file): region = (in_file.readline()).strip() subscription = (in_file.readline()).strip() supplement = (in_file.readline()).strip() update = (in_file.readline()).strip() return region,subscription,supplement,update #def total(in_file): def main(): filename = get_input_filename() in_file = open(filename,'r') print('------------------------------------------------------------') print('Company XYZ') print('Monthly Sales Report') print('------------------------------------------------------------') header1 = print(format('Basic','>20s'),format('Educational','>20s'),format('Annual','>14s')) header2 = print(format('Region','10s'), format('Subscriptions','4s'), format('Supplement','>15s'), format('Update','>15s')) header = print_report_header(header1,header2) print('------------------------------------------------------------') region = read_data(in_file) subscription = read_data(in_file) supplement = read_data(in_file) update = read_data(in_file) print(region) for line in in_file.readlines(): return filename #while(region != 'XX'): main() ``` Text File: ``` LA 150 120 105 MI 200 50 80 FL 250 180 170 XX 0 0 0 ```

OpenStudy (anonymous):

This is my current output ``` Enter your input file name: pa6.sales ------------------------------------------------------------ Company XYZ Monthly Sales Report ------------------------------------------------------------ Basic Educational Annual Region Subscriptions Supplement Update ------------------------------------------------------------ ('LA', '150', '120', '105') ('MI', '200', '50', '80') ('FL', '250', '180', '170') ('XX', '0', '0', '0') ```

OpenStudy (anonymous):

I know i need a while loop to stop when it comes to 'XX' as a region which i think i can figure out but im stuck with the issue i noted above.

OpenStudy (e.mccormick):

``` def read_data(in_file): region = (in_file.readline()).strip() subscription = (in_file.readline()).strip() supplement = (in_file.readline()).strip() update = (in_file.readline()).strip() return region,subscription,supplement,update ``` Does all 4 at once. ``` region = read_data(in_file) ``` Expects only 1. You have a conceptiual difference there.

OpenStudy (anonymous):

ooh ok let me try that out

OpenStudy (e.mccormick):

You probably want to return a dict, list, or set for each region. Then you can more easily deal with it. A dict might work really well. Then you have a list of the dicts.

OpenStudy (anonymous):

what is a dict?

OpenStudy (e.mccormick):

Dictionary: http://www.tutorialspoint.com/python/python_dictionary.htm It is a way to do multiple key value pairs.

OpenStudy (anonymous):

ooh wait, the part you said about the region above, i have that in the main function already

OpenStudy (e.mccormick):

Yes, I am saying it is wrong because you return all 4 at once.

OpenStudy (anonymous):

oooh! i see now, can i return 4 different values in one singlue function?

OpenStudy (e.mccormick):

``` def read_data(in_file): region = (in_file.readline()).strip() subscription = (in_file.readline()).strip() supplement = (in_file.readline()).strip() update = (in_file.readline()).strip() return region,subscription,supplement,update ``` That returns a tuple. You could use it that way if you want.

OpenStudy (anonymous):

i think its closer to following our guidelines for the assignment if i do them one at a time like you suggested the first time. I got it working but might have another question, gonna try working with it and figuring it out but idk how to get it to print the data for the next region.

OpenStudy (anonymous):

wait nvm i think i know how to do it

OpenStudy (e.mccormick):

http://www.tutorialspoint.com/python/python_tuples.htm So lets say you reuse region as the thing it gets returned to. region = read_data(in_file) Then region[0] is LA, region[1] is 150, and so on.

OpenStudy (e.mccormick):

You would loop until you hit region[0] == XX, printig a line of formatted output each time.

OpenStudy (anonymous):

alright so i have to start the loop now, wasnt sure what i was supposed to put in it. thank you

OpenStudy (anonymous):

the while loop would be the last thing in the main function correct?

OpenStudy (e.mccormick):

Well, you would basically do a flag vallue, say, "readFile = true" and while (readFile) go through it. Then, use an if/else to say if region[0] == XX readFile = false, else print the formatted stuff.

OpenStudy (anonymous):

How bout this for my while loop? I'm sure its not the best way to do it but im bad with loops. ``` while(region != 'XX'): if(region != 'XX'): region = eval(in_file.readline()).strip subscription = eval(in_file.readline()) supplement = eval(in_file.readline()) update = eval(in_file.readline()) print(region,subscription,supplement,update) elif(region == 'XX'): print('------------------------------------------------------------') break ```

OpenStudy (e.mccormick):

You don't have region until you read it and you are only going to use one var inside the loop.

OpenStudy (anonymous):

alright lemme try again

OpenStudy (e.mccormick):

You could make it as the temp thing outside the loop.

OpenStudy (e.mccormick):

While loops in general: ``` some_trigger = true while (some_trigger) { do this; and this; etc; if condition met some_trigger = false; } ``` or ``` key_item = (dummy data) while (key_item != exit_condition){ key_item = do_this_function; print key_item; } ``` Either of those generic ways work. You could also read it in from the file first, then start with the loop that prints.

OpenStudy (e.mccormick):

``` region = read_data(in_file) while(region[0] != 'XX'): print(region[0],region[1],region[2],region[3]) region = read_data(in_file) print('------------------------------------------------------------') ```

OpenStudy (anonymous):

``` read_data == True while(read_data): if(region != 'XX'): print(format(region,'10s'),format(subscription,'>4s'),format(supplement,'>15s'),format(update,'>15s')) elif(region == 'XX'): break ``` this look any better?

OpenStudy (anonymous):

hmm you have region 1 2 etc, the program has to be able to run no matter how many regions are in the txt file, will that stop at just 4?

OpenStudy (e.mccormick):

Your function is returning a tuple. The 0 to 3 are the parts of the tuple.

OpenStudy (e.mccormick):

And you can use them that way to pass to the... oooh, I think format can take the tuple directly. Hmmm.

OpenStudy (e.mccormick):

Ah, would not work because you would still need to key it... so you still need to set and test.

OpenStudy (anonymous):

oh goodness, python is a pain.

OpenStudy (e.mccormick):

Just thining out loud, and no, returning a tuple is great. It makes it easier to deal with. It is like a super easy array to make with variable size. Makes Python powerful.

OpenStudy (e.mccormick):

If we take a bit of yours and a bit of mine: ``` region = read_data(in_file) while(region[0] != 'XX'): print(format(region[0],'10s'),format(region[1],'>4s'),format(region[2],'>15s'),format(region[3],'>15s')) region = read_data(in_file) print('------------------------------------------------------------') ``` See, what you got earlier is the 4 tuples printing. You just need to parse one tuple at a time.

OpenStudy (anonymous):

hm yeah i think i see where your goin with that

OpenStudy (e.mccormick):

Now the region variable is a tuple with all the data for one reagon in it. Then you loop to print it and load the next one. It is basically the same as a do while loop.

OpenStudy (anonymous):

so does that mean i need to change something here ``` def read_data(in_file): region = (in_file.readline()).strip() return region subscription = (in_file.readline()).strip() return subscription supplement = (in_file.readline()).strip() return supplement update = (in_file.readline()).strip() return update ```

OpenStudy (e.mccormick):

That won't work. Never could. It hits the first return and dies. The earlier version would work. ``` def read_data(in_file): region = (in_file.readline()).strip() subscription = (in_file.readline()).strip() supplement = (in_file.readline()).strip() update = (in_file.readline()).strip() return region,subscription,supplement,update ``` Due to scope, the regions do not overlap. For clarity, you might use something like regoinCode: ``` def read_data(in_file): regionCode = (in_file.readline()).strip() subscription = (in_file.readline()).strip() supplement = (in_file.readline()).strip() update = (in_file.readline()).strip() return regionCode,subscription,supplement,update ``` Then saying: `region = read_data(in_file)` is conceptually easier to swallow, even though both ways would work.

OpenStudy (anonymous):

does that mean i need to use regionCode instead of region later in the while loop?

OpenStudy (anonymous):

i keep getting a crazy infinite loop, it doesnt print anything the curser just jumps around in the empty print space

OpenStudy (e.mccormick):

No. That is why I made it different. To show why the concept is harder to grasp when the word used is the same. region would be a tuple with all the regon data in it. regionCode is one of 4 pieces of data that read_data returns as a tuple.

OpenStudy (anonymous):

oooh ok i see whatcha mean now.

OpenStudy (e.mccormick):

Yah, so the thing is to have read_data return a tuple and the loop work based on evaluating that tuple and printing its contents. That is what I did in the last bit. It would be basically the same as a do while loop, but I think this is cleaner this way.

OpenStudy (e.mccormick):

One mistake I have seen you make a few times is multiple returns when you wanted all the returns to work. That is what has broken a few things you made. return means this: STOP processing this function/method. Now send back this value. So that kills the function and sends things back. It never goes on to get to the next return statment. The only time to have more than one return is if there are conditional statments. Like an if/else: ``` def evenOddTest(x): if x % 2 == 0: return 'Even' return 'Odd' ``` That function has two returns but because of the if it only returns one of the values. If it divides by 2 without a remainder it returns the string Even. Otherwise, it returns the string Odd. It never does both.

OpenStudy (e.mccormick):

Now let me contrast your function: ``` def read_data(in_file): region = (in_file.readline()).strip() return region subscription = (in_file.readline()).strip() return subscription supplement = (in_file.readline()).strip() return supplement update = (in_file.readline()).strip() return update ``` Every time this is called it does this: ``` Get called with a string and set it to the variable 'in_file'. Set the variable 'region' to the next line of the file 'in_file' but strip off any extra junk. Return the value of the variable 'region' ``` That is it. If you deleted everything after ` return region ` it would still work the exact same way.

OpenStudy (anonymous):

ooh wow yeah not i see. i had that in my notes, i just didnt quite understand it

OpenStudy (e.mccormick):

Well, hopefully you get the difference this time. Now you see why I was happy to work with a retured tuple. It was everything in a useable order.

OpenStudy (anonymous):

yeah seriously, haha. thank you. i think ill be able to finish now

OpenStudy (e.mccormick):

Just a comment on the power of languages: In c++ they have structures and vectors to let you build custom data types. It takes a bit of work. In Python, they have ways to make custom types, but the basic things like tuples and lists and a list of tuples let you do all sorts of custom things without needing to define something special in advance. Pyton is taking advantage of being younger than c++ and aiming to be more programmer friendly. On the down side, it does not compile into a portable program so it runs slower. Thus, Python is programmer friendly but machine intensive. For small utility programs that have limited use on huge tasks (they are not built to tackle the world, just a small bite) Python is good. But if you need to tackle the whole elephant at once, c++ is harder to program but gets the job done quicker.

OpenStudy (e.mccormick):

I am gonna head home now, but I think you have enough info here to get it all done... especially seeing as you have already said just that! If you get confused on the tuple part, look at that tutorialspoint link I pasted in. It has some short code samples on tuples. In other languages, they might call that an array. (Or a final/static array because it is not mutable.) This is on c++ http://www.cplusplus.com/doc/tutorial/arrays/ If you scroll down just a little to "Initializing arrays" you will see it looks a heck of a lot like the stuff you were printing out when you printed the tuple. I don't mean to confuse you with the c++ stuff. I just want to show you that what you learn in Python does have conceptual parallels in other languages. That means what you learn now will make you more ready for other languages later.

OpenStudy (anonymous):

oh yes i can manage it from here i think thanks again for thenhelp! always so helpful

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!