2 Replies - 7441 Views - Last Post: 01 February 2015 - 06:47 PM Rate Topic: -----

#1 PlzHalpCode   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 29-January 15

Optional argument in function help?

Posted 01 February 2015 - 01:08 AM

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.


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


I can't make the last print statement ignore the pennies argument!

here's the error
506
Traceback (most recent call last):
  File "main.py", line 12, in 
    print(number_of_pennies(4))    # Should print 400
TypeError: number_of_pennies() missing 1 required positional argument: 'pennies'


Is This A Good Question/Topic? 0
  • +

Replies To: Optional argument in function help?

#2 andrewsw   User is offline

  • no more Mr Potato Head
  • member icon

Reputation: 6957
  • View blog
  • Posts: 28,696
  • Joined: 12-December 12

Re: Optional argument in function help?

Posted 01 February 2015 - 02:24 AM

You included the term "optional argument" in your title, did you try searching this term?

Using Optional and Named Arguments
def number_of_pennies(dollars, pennies=0):

This post has been edited by andrewsw: 01 February 2015 - 02:24 AM

Was This Post Helpful? 0
  • +
  • -

#3 CreamDelight   User is offline

  • D.I.C Head

Reputation: 32
  • View blog
  • Posts: 131
  • Joined: 04-July 11

Re: Optional argument in function help?

Posted 01 February 2015 - 06:47 PM

In addition to the answer above, you may also try to use ternary operator (or so called ternary operator, read it here: https://www.python.o.../peps/pep-0308/) to reduce your code to make it look more like a python.

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


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1