简体   繁体   中英

How do I create variables as they are being assigned by the user a 'x' amount of times that the user chooses to input?

I'm currently writing a program that calculates the gpa of different students. If I want to let the user input their course's credit worth and their grade value in percentages; is it any possibility that I could aske the # of courses the students are currently participating in and assigned each of the values to a new variable everytime the user inputs a value for it. For each of the new inputs, how can I add them into the equation everytime they are created? for example:

def gpa1():
    return ((x1*y1)+(x2*y2)+(x3*y3)+(x4*y4)+(x5*y5)+(x6*y6)+(x7*y7)+(x8*y8)+(x9*y9)+(x10*y10))/((y1+y2+y3+y4+y5+y6+y7+y8+y9+y10))

This is what the equation looks like if I would have 10 course intotal, but instead I want the user to have a choice to alter the # of inputs they are able to make instead of 10. Everytime the user inputs, a new varible my be added or an old varible may be deleted. How can I possibly achieve all this? I would very much appreciated anyone who attempts to help me at this.

The real issue here is that you think you need n names for n user inputs. That's not necessary at all.

You can just store the inputs in a container (list, dictionary, tuple, ...) or process them as they come in. For example, you don't need to compute y1 + ... + y10 after collecting all the values, you can initialize a variable sum_y = 0 and keep adding the y values.

One minimalistic way of reading user input until a sentinel value is seen goes like this:

>>> inputs = list(iter(input, 'q'))
1
2
3
q
>>> inputs
['1', '2', '3']

If you want to catch invalid inputs, the question Asking the user for input until they give a valid response is very relevant.

You should also read the answers to How do I create a variable number of variables? in order to learn why you should not want what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM