Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a function in python and assigning integers

Tags:

python

I'm doing exercise 20 in LPTHW and I'm working my wall through the study drill.I have a question regarding one line of code. For your reference, I print out the code:

from sys import argv

script, input_file = argv

def print_all(f):
    print(f.read())

def rewind(f):
    f.seek(0)

def print_a_line(line_count, f):
    print(line_count, f.readline())

current_file = open(input_file)

print("First let's print the whole file:\n")

print_all(current_file)

print("Now let's rewind, kind of like a tape.")

rewind(current_file)

print("Let's print three lines:")

current_line = 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

My issue is, how does the below function, know to reference current_line as the integer?

def print_a_line(line_count, f): 
    print(line_count, f.readline())

Really struggling here...sorry if it is a silly question!

like image 739
Jimmy K Avatar asked Jun 03 '26 15:06

Jimmy K


1 Answers

When you make a function call of:

print_a_line(current_line, current_file)

you are passing the values of current_line and current_file to the print_a_line function to make the call, so the value of current_line gets assigned as an argument to the parameter line_count, and the value of current_file gets assigned as an argument to the parameter f inside the print_a_line function, so that they can be referenced as local variables there.

like image 159
blhsing Avatar answered Jun 05 '26 05:06

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!