Question to solution

Hi community,

i have a question because i don’t understand a solution.
At the Data Analyst In Python in Mission Functions Intermediate, Mission 5 (Multiple Return Statements) we get the following solution:

# INITIAL CODE
def open_dataset(file_name='AppleStore.csv', **header=True**):
    opened_file = open(file_name)
    from csv import reader
    read_file = reader(opened_file)
    data = list(read_file)
    
    if header:
        return data[1:]
        
    else:
        return data
    
    return data


apps_data = open_dataset()

Everything is clear for me exapt the parameter header=True? What is Python checking here? I mean we don’t have any row with this name. What is Python checking in the IF-Statement? Sure, it returns witthout the header if a header existis [1:]. But if we write IF header, what is here variable Python is checking?

Thanks for any explaination.

Hi @Simo

the function is written here for easy reading from the file. the headers variable should specify. Whether the header is in the file or not. And if it is, you should skip it while reading.

if headers checks the specified flag. If the user has passed that the header exists, then the condition if == True. After that the code will skip the header when reading it. If the user has passed that the header doesn’t exist (that is, False), the condition if == False, which means that the code will go to the branch else and read it without missing 1 line.

Hi @Simo, welcome back to the community. The header parameter (or variable) as used in the open_dataset () function is to indicate whether the data we want to read from a file (in this case “AppleStore.csv”) has a header (header=True) or not (header=False).

If the data has a header we want to read the data without the header. The if header: statement is used for this conditional check. Since header is set to True in the function definition, if header: simply means that the data has a header, therefore, the function returns data without the header (i.e., data[1:]).

Hope this helps!

Thanks for the fast explanation!:slight_smile:
In this case, the function should return the else part if i set header=False?
But this doesn’t happen. And i have the else statement in the body of the function.
Is here something wrong?

Thanks.

Yes, if header = False, this code block will be executed.

    else:
        return data

If you don’t think this is happening, double-check the file. Or do a simple check of what exactly is going on in your code. For example.

    if header:
        data = data[1:]
        print('if block - first row:', data[0])
        return data
        
    else:
        print('else block - first row:', data[0])
        return data

This way you can learn how your function and results change when passing different header True or False flags.

Thanks, now it’s clear for me :slight_smile:
You helped me a lot guys!

1 Like