- 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')

25th Feb 2020, 2:46 AM
Tauhid Anwar
Tauhid Anwar - avatar
4 Antworten
+ 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/
25th Feb 2020, 4:12 AM
Hrvoje
Hrvoje - avatar
+ 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.
25th Feb 2020, 4:07 AM
ChaoticDawg
ChaoticDawg - avatar
0
Thanks alot @Hrvoje
25th Feb 2020, 5:14 PM
Tauhid Anwar
Tauhid Anwar - avatar
0
You're welcome.
25th Feb 2020, 5:37 PM
Hrvoje
Hrvoje - avatar