Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: Modifying Enclosing Scope Variables | Variable Scope, Nested Functions, and Closures
Functional Programming Concepts in Python
Seksjon 3. Kapittel 5
single

single

Challenge: Modifying Enclosing Scope Variables

Sveip for å vise menyen

Oppgave

Sveip for å begynne å kode

Create a function that protects a bank balance variable. The balance should be modifiable through an inner function that allows withdrawing money. Use the nonlocal keyword to modify the balance from within the inner function.

  • Inside the outer function, define an inner function withdraw(amount) that:
    • Uses the nonlocal keyword to access and modify balance.
    • Subtracts amount from balance only if enough funds are available.
    • Returns the new balance if withdrawal is successful, or a message like 'Insufficient funds' if not.
  • Call the inner function with various amounts and print the result after each call.
  • The balance variable must not be accessible or modifiable from outside the outer function.

Løsning

Switch to desktopBytt til skrivebordet for virkelighetspraksisFortsett der du er med et av alternativene nedenfor
Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 5
single

single

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

some-alt