Python

Помогите исправить код

 def calculate_budget():
total_budget = 0
while True:
amount_str = input("Amount needed(0 - stop): ")
if amount_str == 'stop':
break

amount = int(amount_str)
if amount
ммм балдежный код в цикле

 def calculate_budget(): 
total_budget = 0
while True:
amount_str = input("Amount needed(0 - stop): ")
if amount_str == 'stop' or amount_str == "0": break
if (amount_str.isnumeric()):
amount = int(amount_str)
if amount
Сергей Профотаев
Сергей Профотаев
7 589
Лучший ответ
Императивный подход сдаёт позиции. Пиши по-питоньему:
 def calculate_budget():
MSGS = ("Amount below average.", "Optimal amount.", "Approval required!")
amts = (int(s) for s in iter(input, 'stop'))
amtsp = (print(MSGS[max(3, min(a // 2000, 5)) - 3]) or a for a in amts)
print(sum(amtsp))

calculate_budget()
Пример:
 12000
Approval required!
10000
Approval required!
9999
Optimal amount.
8001
Optimal amount.
7999
Amount below average.
1
Amount below average.
stop
48000

1) Никакого дублирования кода.
2) Никакой вереницы else-if-ов.
3) Ввод семантически отделён от вывода и подсчёта суммы, но хронологически всё это выполняется именно так, как у тебя в программе (если в ней поправить отступы). Питоновские итераторы - мощная штука.
4) И всё это записано в 2 раза меньшим количеством лексических единиц, чем у тебя.

Правда, не выводится промпт. Для этого нужны дополнительные определения:
 def calculate_budget():
MSGS = ("Amount below average.", "Optimal amount.", "Approval required!")
amts = (int(s) for s in iter(lambda: input('Amount needed (or stop): '), 'stop'))
amtsp = (print(MSGS[max(3, min(a // 2000, 5)) - 3]) or a for a in amts)
print(sum(amtsp))

calculate_budget()
 def calculate_budget(): 
total_budget = 0
while True:
amount_str = input("Amount needed(0 - stop): ")
if amount_str == 'stop':
break

amount = int(amount_str) # unindent this line
if amount