Python: Find the first negative balance
Python Programming Puzzles: Exercise-70 with Solution
Write a Python program to find the first negative balance from a given list of numbers that represent bank deposits and withdrawals.
Input: [[12, -7, 3, -89, 14, 88, -78], [-1, 2, 7]] Output: [-81, -1] Input: [[1200, 100, -900], [100, 100, -2400]] Output: [None, -2200]
Pictorial Presentation:

Sample Solution:
Python Code:
#License: https://bit.ly/3oLErEI
def test(balances):
firsts = []
for bals in balances:
total = 0
for b in bals:
total += b
if total < 0:
firsts.append(total)
break
else:
firsts.append(None)
return firsts
balances = [[12, -7, 3, -89, 14, 88, -78], [-1, 2, 7]]
print("Bank deposits and withdrawals:")
print(balances)
print("\nFirst negative balance of deposits and withdrawals:")
print(test(balances))
balances = [[1200, 100, -900], [100, 100, -2400]]
print("Bank deposits and withdrawals:")
print(balances)
print("\nFirst negative balance of deposits and withdrawals:")
print(test(balances))
Sample Output:
Bank deposits and withdrawals: [[12, -7, 3, -89, 14, 88, -78], [-1, 2, 7]] First negative balance of deposits and withdrawals: [-81, -1] Bank deposits and withdrawals: [[1200, 100, -900], [100, 100, -2400]] First negative balance of deposits and withdrawals: [None, -2200]
Flowchart:

Python Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Create a new string by taking s, and word by word rearranging its characters in ASCII order.
Next: Inject a number in between each pair of adjacent numbers in a list of numbers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join