Understanding the Convenience of Functions

Asked 2 years ago, Updated 2 years ago, 31 views

We are learning about functions.
In books and videos, consumption tax calculations and BMI calculations are explained as examples.
Yes, but I don't understand it, or I can't feel the convenience
I'm in a situation.

Therefore, you can read the text and write it to a CSV file as shown below. I tried to make a program that I could write without functioning it.

Therefore, in my case, the reason why I don't understand or understand the convenience of the function is
Now I understand how to handle arguments.

Especially
I don't understand how to pass the results (return values) of other functions to other functions.

to_csv('test.csv', header_lists, data_lists)
by calling the function to be written to CSV with the code below. There is an error and I don't know what to do.
(I understand that calling to_csv('test.csv', header_lists, data_lists) within the def from_txt(f_name): function does not cause errors.)

Therefore, I would appreciate it if you could use the code below as an example or a little more chewed up.

Thank you for your cooperation.

import csv


# text file read function
def from_txt(f_name):
    with open(f_name, 'r', encoding='utf-8') asf:
        elems=f.readlines()
        # print(read)
        
        # Create Header and Data Section
        header_lists = [ ]
        data_lists = [ ]
        for elemines [2:18]:
            header=elem.split(':',1)[0].trip()
            data=elem.split(':',1)[1].trip()
            header_lists.append(header)
            data_lists.append(data)
            
    return header_lists, data_lists


# CSV write function
def to_csv(cf_name, h_list, d_list):
    with open(cf_name, 'w', encoding='shift-jis', newline=') asf:
        writer=csv.writer(f)
        writer.writerow(h_list)
        writer.writerow(d_list)

from_txt('tmp.txt')

to_csv('test.csv', header_lists, data_lists)#Exception occurred: NameError name 'header_lists' is not defined

python python3

2022-09-29 22:34

1 Answers

The current code has discarded the result of from_txt('tmp.txt'). You must keep the result of from_txt('tmp.txt') in the variable and pass it to to_csv(cf_name,h_list,d_list).

What about header_lists, data_lists=from_txt('tmp.txt')?


2022-09-29 22:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.