Flexible und Standardargumente

Einführung in Funktionen in Python

Hugo Bowne-Anderson

Instructor

Du lernst:

  • Funktionen mit Standardargumenten zu schreiben

  • Flexible Argumente zu verwenden

    • Beliebig viele Argumente an eine Funktion zu übergeben
Einführung in Funktionen in Python

Hinzufügen eines Standardarguments

def power(number, pow=1):
   """Raise number to the power of pow."""
   new_value = number ** pow
   return new_value

power(9, 2)
81
power(9, 1)
9
power(9)
9
Einführung in Funktionen in Python

Flexible Argumente: *args (1)

def add_all(*args):
    """Sum all values in *args together."""

    # Initialize sum
    sum_all = 0

    # Accumulate the sum
    for num in args:
        sum_all += num

    return sum_all
Einführung in Funktionen in Python

Flexible Argumente: *args (2)

add_all(1)
1
add_all(1, 2)
3
add_all(5, 10, 15, 20)
50
Einführung in Funktionen in Python

Flexible Argumente: **kwargs

print_all(name="Hugo Bowne-Anderson", employer="DataCamp")
name: Hugo Bowne-Anderson
employer: DataCamp
Einführung in Funktionen in Python

Flexible Argumente: **kwargs

def print_all(**kwargs):
    """Print out key-value pairs in **kwargs."""

    # Print out the key-value pairs
    for key, value in kwargs.items():
        print(key + ": " + value)
print_all(name="dumbledore", job="headmaster")
job: headmaster
name: dumbledore
Einführung in Funktionen in Python

Lass uns üben!

Einführung in Funktionen in Python

Preparing Video For Download...