[英]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. 我目前正在编写一个计算不同学生的GPA的程序。 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. 如果我总共有10门课程,这就是方程式,但是我希望用户可以选择更改他们能够进行的输入数量(而不是10)。每次用户输入时,都会有一个新变量添加或删除旧的变量。 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. 真正的问题是,您认为需要n个用户输入的名称。 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. 您可以只将输入存储在容器中(列表,字典,元组等),也可以在输入时对其进行处理。例如,收集所有值后无需计算
y1 + ... + y10
,您可以初始化变量sum_y = 0
并继续添加y
值。
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.
为了了解为什么您不想要想要的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.