Tuesday, 14 April 2015

Course Work Practice #3


For this piece of coursework practice, we were asked to create a program that asks students in a class how much money they spent on 1) Clothes: , 2) CDs: , and 3) Food:. The students have a budget for 2000dhs to spend. 
The best way to store this data would be to use a list, and so at the beginning, we create 3 empty lists of the items that they would spend their money on:




For this program, it would be best to use a "for" loop since it executes the same command for as many times as you like. Here, we're only going to ask three students, so the command would be executed only three times.
(note that anything indented in line with the loop becomes part of it and therefore is executed three times)



The next step would be to make sure that each answer is appointed to the correct list in order to avoid confusion, and so that everything is in its right place. To do this, we would need the input() function to take the students' answers, and assign them to a variable, while converting the input into an integer using the int() method.
for example:






Here its shown that the input for "x" stores the input for "Clothes:" and same goes for the variables "y" and "z".

Then, we would need to .append() the variables to the three lists assigned to the three items money was spent on, like so:






 The variables that are appended to the three lists contain each list's input.

We would then need to create a variable that store the sum of each list's contents, and the sum() would be used. 





So, the "clothes = []" variable now storing the students' input regarding the money spent on clothes.






Now, we insert the sum of each lists' contents using .insert(index, variable), "0" being the index, and "sumclothes" being the variable.
All thats left now is to print our lists:

Then we would need to see which item had the most money spent on it using:

These statements basically mean "if sum of clothes is greater than the sum of cd's and if sum of clothes is greater than the sum of food, print the sum of clothes and print("The most money was spent on clothes.").
And so on for the other lists.


The final result should be:















And then you'd be left with a fully functioning "Shopping list".

No comments:

Post a Comment