Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Ændring af Funktioner | Funktioner
Introduktion til Python

book
Ændring af Funktioner

I programmering er funktioner dynamiske værktøjer, der kan tilpasses forskellige situationer og behov. De er ikke blot faste kodeblokke. Du kan forbedre funktioner for at gøre dem mere alsidige og brugervenlige i forskellige sammenhænge.

I dette kapitel vil vi undersøge nogle vigtige teknikker til at ændre funktioner, såsom brug af standardargumenter og nøgleordsargumenter.

Lad os begynde med et enkelt eksempel på ændring af funktioner for at øge deres anvendelighed i vores dagligvarebutiksstyringssystem:

Standardargumenter

Standardargumenter er en nyttig funktion i Python, der gør det muligt at angive standardværdier for funktionsparametre.

I funktionen apply_discount() er parameteren discount sat til 0.10 som standard. Det betyder, at funktionen automatisk anvender en 10% rabat, medmindre andet er angivet. Som det ses i variablen default_discount_price, kan vi kalde funktionen med kun parameteren price.

Hvis det er nødvendigt, kan vi dog overskrive standardværdien ved at angive både price og en brugerdefineret discount (f.eks. 0.20 for 20%) som vist med variablen custom_discount_price.

# Define a function with a default `discount` argument
def apply_discount(price, discount=0.10):
discounted_price = price * (1 - discount)
return discounted_price

# Call the function without providing a `discount`, using the default value
default_discount_price = apply_discount(100)
print(f"Price after applying the default discount: ${default_discount_price}")

# Call the function with a custom `discount` value
custom_discount_price = apply_discount(100, 0.20)
print(f"Price after applying a custom discount: ${custom_discount_price}")
123456789101112
# Define a function with a default `discount` argument def apply_discount(price, discount=0.10): discounted_price = price * (1 - discount) return discounted_price # Call the function without providing a `discount`, using the default value default_discount_price = apply_discount(100) print(f"Price after applying the default discount: ${default_discount_price}") # Call the function with a custom `discount` value custom_discount_price = apply_discount(100, 0.20) print(f"Price after applying a custom discount: ${custom_discount_price}")
copy

Nøgleordsargumenter

Nøgleordsargumenter i Python gør det muligt at videregive argumenter ved eksplicit at navngive hver parameter, hvilket gør funktionskald mere læselige og fleksible. Dette er særligt nyttigt, når en funktion har flere parametre, eller når rækkefølgen af argumenter kan være forvirrende.

I følgende eksempel er både price og discount angivet, mens parameteren tax forbliver på sin standardværdi, hvilket giver fleksibilitet uden at gå på kompromis med klarheden.

# Function where `tax` has a default value
def calculate_total(price, discount, tax=0.05):
total = price * (1 + tax) * (1 - discount)
return total

# Calling the function using keyword arguments
total_cost = calculate_total(price=100, discount=0.15)
print(f"Total cost after applying discount: ${total_cost}")
12345678
# Function where `tax` has a default value def calculate_total(price, discount, tax=0.05): total = price * (1 + tax) * (1 - discount) return total # Calling the function using keyword arguments total_cost = calculate_total(price=100, discount=0.15) print(f"Total cost after applying discount: ${total_cost}")
copy

Bemærk

Rækkefølgen af parametre er ikke vigtig, når de videregives ved brug af nøgleordsargumenter.

Opgave

Swipe to start coding

Opret funktioner til at beregne den samlede pris på et produkt ved at anvende rabat og moms, ved brug af nøgleordsargumenter og standardværdier for fleksibilitet.

  • Definér apply_discount(price, discount=0.05)
    → Returnerer prisen efter rabatten er fratrukket.
  • Definér apply_tax(price, tax=0.07)
    → Returnerer prisen efter momsen er lagt til.
  • Definér calculate_total(price, discount=0.05, tax=0.07)
    → Anvender apply_discount() og apply_tax() til at returnere den samlede pris med både rabat og moms anvendt.
  • Kald calculate_total(120) med standardrabat og -moms.
  • Kald calculate_total(100, discount=0.10, tax=0.08) med brugerdefinerede værdier via nøgleordsargumenter.

Outputkrav

  • Udskriv resultatet med standardværdier:
    Total cost with default discount and tax: $<total_price_default>
  • Udskriv resultatet med brugerdefinerede værdier:
    Total cost with custom discount and tax: $<total_price_custom>

Bemærk

Når funktioner defineres, skal påkrævede parametre placeres først, efterfulgt af parametre med standardværdier.

Ved kald af funktioner med nøgleordsargumenter skal positionelle argumenter komme før nøgleordsargumenter.

Løsning

# Task 1: Define a function to apply a discount with a default discount value of 5%
def apply_discount(price, discount=0.05):
# Calculate and return the discounted price
return price * (1 - discount)

# Task 2: Define a function to apply tax with a default tax rate of 7%
def apply_tax(price, tax=0.07):
# Calculate and return the price with tax
return price * (1 + tax)

# Task 3: Define a function to calculate the total price by applying both discount and tax
def calculate_total(price, discount=0.05, tax=0.07):
# Apply the discount first
discounted_price = apply_discount(price, discount)
# Apply tax on the discounted price
final_price = apply_tax(discounted_price, tax)
# Return the final total price
return final_price

# Task 4: Call `calculate_total` using only the default discount and tax values
total_price_default = calculate_total(120)
print(f"Total cost with default discount and tax: ${total_price_default}")

# Task 5: Call `calculate_total` with a custom discount of 10% and a custom tax of 8%
total_price_custom = calculate_total(100, discount=0.10, tax=0.08)
print(f"Total cost with custom discount and tax: ${total_price_custom}")
Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 6. Kapitel 6
single

single


Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

We use cookies to make your experience better!
some-alt