Sección 3. Capítulo 5
single
Challenge: Modifying Enclosing Scope Variables
Desliza para mostrar el menú
Tarea
Desliza para comenzar a programar
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
nonlocalkeyword to access and modifybalance. - Subtracts
amountfrombalanceonly if enough funds are available. - Returns the new balance if withdrawal is successful, or a message like
'Insufficient funds'if not.
- Uses the
- Call the inner function with various amounts and print the result after each call.
- The
balancevariable must not be accessible or modifiable from outside the outer function.
Solución
¿Todo estuvo claro?
¡Gracias por tus comentarios!
Sección 3. Capítulo 5
single
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla