简体   繁体   中英

Unpacking a python tuple in a python function

Using Visual Studio & http://pythontutor.com/visualize I am unable to get the result for filesize function because of the following Error: TypeError: file_size() takes 1 positional argument but 3 were given. Code below.

 #this function stores information about a file, its name, its type and its size in bytes. def file_size(file_info): name, file_type, size = file_info return("{:.2f}".format(size/1024)) print(file_size('Class Assignment','docx', 17875)) #Should print 17.46 print(file_size('Notes','txt', 496)) #Should print 0.48 print(file_size('Program','py', 1239)) #Should print 1.21

I though unpacking (file_info) within the function will override the 1 positional argument but 3 were given error. What am I doing wrong?

Currently you are passing three distinct arguments... pass it instead as one argument which is a tuple:

print(file_size( ('Class Assignment','docx', 17875) ))

Alternatively, you could alter your function declaration to capture distinct arguments into a tuple when called:

def file_size(*file_info):
    ...

Then calling it as you are is valid.

Put the values into a tuple like this:

print(file_size(('Class Assignment','docx', 17875)))
print(file_size(('Notes','txt', 496)))
print(file_size(('Program','py', 1239)))

This way you are passing one variable

If you want to keep the function with one parameter, try assigning the tuple to a variable and pass it in:

file_size(*varname)

Please try this:

def file_size(file_info):
    name, type, size= file_info
    return("{:.2f}".format(size / 1024))

Please try this.

def file_size(file_info):

    (name,file_type,size)  = file_info
    return("{:.2f}".format( size/ 1024))

You need to pass file_info in a tuple in python.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM