Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the Python function not print a default value?

I am new to Python and am attempting to print a default value set for a parameter. My code is as follows;

# Functions

def shoppingcart(item='computer', *price):
    print item
    for i in price:
        print i

shoppingcart(100,200,300)

When I run the code, all I get are the values 100,200,300. I was expecting computer,100,200,300. What am I doing wrong?

EDIT

How do I achieve this in Python 2.7?

EDIT

I updated my code to

def shoppingcart(item='computer', *price):
    print item
    for i in price:
        print i

shoppingcart(item='laptop', 100,200,300)

however get the error

enter image description here

like image 449
PeanutsMonkey Avatar asked Jan 22 '26 10:01

PeanutsMonkey


1 Answers

Simply put, default values are only used if there is no other way. Here you have item=100 and the other 2 values go into *price.

In Python3 you can write:

def shoppingcart(*prices, item='computer'): 
    print(item)
    print(prices)

shoppingcart(100,200,300)
shoppingcart(100,200,300, item='moon')

In Python2 you cannot have default arguments after *args so you have to find another way to call your functions.

like image 65
Jochen Ritzel Avatar answered Jan 24 '26 23:01

Jochen Ritzel



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!