[Tutor] Draw table and compare random input
Cameron Simpson
cs at cskk.id.au
Mon Aug 3 19:04:19 EDT 2020
On 30Jul2020 22:35, Phaik Huen Tan <ptan1 at capellauniversity.edu> wrote:
>I am supposed to draw a table for my random input (12 months of
>expenses)
>and compared it against the monthly target. I am able to get input from
>the user but I am not able to compare each input and display each input by
>month individually. Can you please provide guidance on where I did wrong on
>my code?
I know this post is nearly a week old, but nobody seems to have replied
and I've only just noticed it myself.
You basic difficulty or missing code is storing the expenditures in
order to print them in the table later.
Since there are to be exactly 12 months you don't need anything special,
just a list of 12 values. For example:
expenditures = [0] * 12
which will produce a 12 element list filled with zeroes. Remember that
lists count from 0 in Python (and most programming languages), so these
elements are indexed 0 through 11 inclusively.
Having prepared the list, you would modify your while loop to store each
expenditure in the appropriate element of the list. You could set:
month_index = 0 # start at January
before the loop begins, and store month_exp as the loop goes on:
expenditures[month_index] = month_exp
month_index += 1
Then down the bottom where you print your table, do the tests in a loop.
After the headings are printed, write something like:
# count from 0 to 11 using the range() function
for month_index in range(12):
month_exp = expenditures[month_index]
if month_exp >= monthly_target:
... etc etc ...
Cheers,
Cameron Simpson <cs at cskk.id.au>
>Below is my code:
>
># This program calculates monthly expenses.
># Create a variable to control the loop.
>keep_going = 'Y'
>#Calculate monthly target for each of the 12 months using annual IT
>expenses of $42500
>monthly_target = 42500/12
>print('Monthly target expenditure is $', format(monthly_target,'.2f'))
>
>
>
>while keep_going == 'Y' or keep_going == 'y':
> # Initialize an accumulator for site expenditure
> total = 0
> # Get the site expenditure
> month_exp = int(input('Please enter month expenditure: '))
> if month_exp < 0:
> print('Value must be greater than 0')
> month_exp = int(input('Enter the correct site expenditure: '))
> # See if the user wants to do enter another one.
> keep_going = input('Do you want to enter another ' +
> 'month expenditure (Enter Y or y for yes): ')
>#Print the table headings
>print()
>print('Month\t|Expense\t|Over,Under or Exact')
>print('-----------------------------------------------')
>
>if month_exp >= monthly_target:
> print("Over")
>elif month_exp <= monthly_target:
> print("Under")
>else:
> print("Exact")
More information about the Tutor
mailing list