Valid order total
An order import contains N rows of quantity price_cents. Accept a row only if both values are integers, quantity is positive and price is non-negative. Sum quantity times price in whole cents and count rejected rows. A malformed row must not crash the report or contribute to the total.
Input
First line N; then N lines, each intended to contain quantity and unit price in cents.
Output
First line total X; second line rejected Y.
Example 1
Input
4 2 150 0 30 3 -1 4 25
Output
total 400 rejected 2
Two valid rows contribute 300 and 100 cents; zero quantity and negative price rows are rejected without altering the total.
Constraints
- 0 <= N <= 200 rows.
- Valid quantity is a positive integer and valid unit price is a non-negative integer in cents.
Hints
Hint 1 of 2
Check field count before unpacking.
Hint 2 of 2
Keep values in integer cents; catch only expected conversion and validation errors.
Solution
Show a reference solution and explanation
n = int(input())
total = 0
rejected = 0
for _ in range(n):
parts = input().split()
try:
if len(parts) != 2:
raise ValueError('two fields required')
qty, cents = map(int, parts)
if qty <= 0 or cents < 0:
raise ValueError('invalid range')
except ValueError:
rejected += 1
continue
total += qty * cents
print('total', total)
print('rejected', rejected)
Why it works
Validation is completed before changing the total, so a bad row cannot partially affect money. Whole cents avoid floating-point rounding. Count malformed shapes, non-integers and invalid ranges equally as rejected rows, while a zero-cent price remains valid.
Lesson for this exercise: Exceptions and Error Handling in Python