Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!
Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount
Πολλαπλά Ορίσματα Συνάρτησης
Κάθε συνάρτηση στην Python λαμβάνει έναν προκαθορισμένο αριθμό ορισμάτων, αν δηλωθεί κανονικά, όπως παρακάτω:
Είναι δυνατό να δηλώσουμε συναρτήσεις που λαμβάνουν μεταβλητό αριθμό ορισμάτων, χρησιμοποιώντας την παρακάτω σύνταξη:
Η μεταβλητή "therest" είναι μια λίστα μεταβλητών, η οποία λαμβάνει όλα τα ορίσματα που δόθηκαν στη συνάρτηση "foo" μετά τα πρώτα 3 ορίσματα. Έτσι, καλώντας την foo(1, 2, 3, 4, 5)
θα εκτυπωθεί:
Είναι επίσης δυνατό να στείλουμε ορίσματα συναρτήσεων με βάση το όνομα, ώστε η σειρά των ορισμάτων να μην έχει σημασία, χρησιμοποιώντας την παρακάτω σύνταξη. Ο παρακάτω κώδικας παράγει την ακόλουθη έξοδο:
The sum is: 6
Result: 1
Η συνάρτηση "bar" λαμβάνει 3 ορίσματα. Αν ληφθεί ένα επιπλέον όρισμα "action" και καθοδηγεί στο άθροισμα των αριθμών, τότε τυπώνεται το άθροισμα. Εναλλακτικά, η συνάρτηση γνωρίζει επίσης ότι πρέπει να επιστρέψει το πρώτο όρισμα, αν η τιμή της παραμέτρου "number", που μεταβιβάστηκε στη συνάρτηση, είναι ίση με "first".
Exercise
Συμπληρώστε τις συναρτήσεις foo
και bar
ώστε να μπορούν να λαμβάνουν μεταβλητό αριθμό ορισμάτων (3 ή περισσότερα). Η συνάρτηση foo
πρέπει να επιστρέφει την ποσότητα των επιπλέον ορισμάτων που έλαβε. Η bar
πρέπει να επιστρέφει True
αν το όρισμα με τη λέξη-κλειδί magicnumber
είναι ίσο με 7, και False
διαφορετικά.
# edit the functions prototype and implementation
def foo(a, b, c):
pass
def bar(a, b, c):
pass
# test code
if foo(1, 2, 3, 4) == 1:
print("Good.")
if foo(1, 2, 3, 4, 5) == 2:
print("Better.")
if bar(1, 2, 3, magicnumber=6) == False:
print("Great.")
if bar(1, 2, 3, magicnumber=7) == True:
print("Awesome!")
# edit the functions prototype and implementation
def foo(a, b, c, *args):
return len(args)
def bar(a, b, c, **kwargs):
return kwargs["magicnumber"] == 7
# test code
if foo(1, 2, 3, 4) == 1:
print("Good.")
if foo(1, 2, 3, 4, 5) == 2:
print("Better.")
if bar(1, 2, 3, magicnumber=6) == False:
print("Great.")
if bar(1, 2, 3, magicnumber=7) == True:
print("Awesome!")
test_output_contains("Good.")
test_output_contains("Better.")
test_output_contains("Great.")
test_output_contains("Awesome!")
success_msg("Great work!")
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!