Я создал программу отслеживания расходов на Python, и для проверки входных данных, чтобы убедиться, что они соответствуют указанному типу, я создал эту рекурсивную функцию:
def input_validate(type, prompt): # validates inputs
value = input(prompt)
try:
type(value)
except:
print('Invalid input.')
input_validate(type, prompt)
else:
return type(value)
Эта функция передается в виде переменной суммы:
amount = input_validate(float, 'Enter the amount: ')
При запуске и отладке я получаю следующий результат:
Expense Tracker
1. Add an expense
2. List all expenses
3. Show total expenses
4. Filter expenses by category
5. Exit
Enter your choice: 1
Enter the amount: invalid
Invalid input.
Enter the amount: 100
Enter category: test
Expense Tracker
1. Add an expense
2. List all expenses
3. Show total expenses
4. Filter expenses by category
5. Exit
Enter your choice: 2
All Expenses:
Amount: None, Category: test
Expense Tracker
1. Add an expense
2. List all expenses
3. Show total expenses
4. Filter expenses by category
5. Exit
Enter your choice:
Подробнее здесь: https://stackoverflow.com/questions/789 ... rted-float