简体   繁体   中英

Mixing keyword and default arguments in python 3.5.1

I'm a newbie and taking an online python class through an online workbook. I can't seem to figure out how to get the output to display like the example shown:

Problem instructions: Write a function number_of_pennies() that returns the total number of pennies given a number of dollars and (optionally) a number of pennies. Ex: 5 dollars and 6 pennies returns 506.

Here is what I have:

def number_of_pennies(dollars = (),pennies=())

    return number_of_pennies
print(number_of_pennies(5, 6)) # Should print 506
print(number_of_pennies(4))    # Should print 400

Thanks to your help I just changed it to this:

def number_of_pennies(dollars = 0,pennies=0):
    number_of_pennies= (dollars * 100) + pennies
    return number_of_pennies
print(number_of_pennies(5, 6)) # Should print 506
print(number_of_pennies(4))    # Should print 400

Default arguments are used when the caller doesn't supply a value. So, what should be the default? In your case, if the user doesn't supply dollars, zero dollars seems like a reasonable choice. Same with pennies. Since number_of_pennies(4) should be 400 you know that they want dollars to be the first parameter. The remainder is just the math.

number_of_pennies is just the name of the function which would be an odd thing to return. In fact, when you try it you get something like <function number_of_pennies at 0x7ff4e962d488> which means that the function returned its own function object. Instead return the data you calculate... that's much more useful!

>>> def number_of_pennies(dollars=0, pennies=0):
...     return dollars * 100 + pennies
... 
>>> print(number_of_pennies(5,6))
506
>>> print(number_of_pennies(4))
400
def number_of_pennies(dollars = 0, pennies = 0): return dollars * 100 + pennies print(number_of_pennies(int(input()), int(input()))) # Both dollars and pennies print(number_of_pennies(int(input()))) # Dollars only
def number_of_pennies(n,x=0):
    return n*100+x

I did the same workbork. This is what I came up with:

def number_of_pennies(dollars=0, pennies=0):
    dollars = dollars * 100
    pennies = pennies
    total = dollars + pennies
    return total

print(number_of_pennies(int(input()), int(input()))) # Both dollars and pennies
print(number_of_pennies(int(input())))               # Dollars only

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