- 1
python code explanation needed and not getting required result
month_list = ["January", "February", "March", "April", "May"] expense_list = [2340, 2500, 2100, 3100, 2980] e = input("Enter the expense amount:") e = int(e) month = -1 for i in range(len(expense_list)): if e == expense_list[i]: month_list = i break if month != -1: print('You spent', e, 'in', month_list[month]) else: print('You didn\'t spend', e, 'in any month')
4 Respuestas
+ 2
1. It should be `month = i`, not `month_list = i`.
2. Break in 'if' doesn't help.
3. Wrong indentation (spaces at the beginning of each line) of the whole 2nd part of the code.
(4. You can make intiger out of the input in the same line, just put input into 'int': `int(input())`.)
Generally, explenation of the code is that in the for loop it just remembers (into variable "month") index of the value, and when the loop ends it checks if input exists in expenses, and if yes it uses remembered index to print out month from other list.
Here's the fixed code of yours (in the comment) and my two solutions using dictionary (although the 1st version ends up splitting dictionary into two lists): https://code.sololearn.com/ccKwR9XF0n34/
+ 2
In your if statement inside the for loop you're setting
month_list = i
instead of
month = i
Which is what i believe you intended.
0
Thanks alot @Hrvoje
0
You're welcome.