0

Suppose Now there is a file named main.py, which has many variables. We want to find the average of all the variables by adding all of the variable and dividing them by the number of varibles. If there are less variables, like -

a= 100
b = 200
average = a+b / 2
print(average)

This is how we code if there are less variables. But what to do if there are a thousand variables? We can't write every single variable. So how should we write the code in that case?

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Boolean
  • 25
  • 7
  • Does this answer your question? [Print all variables and their values](https://stackoverflow.com/questions/46516177/print-all-variables-and-their-values) – whackamadoodle3000 Jan 15 '21 at 19:25
  • This is a fundamental failure of program design. You should be keeping your objects in some *container* like a `list` or a `dict`, to be able to operate on the items in the container. "We can't write every single variable" well, you *can*. – juanpa.arrivillaga Jan 15 '21 at 19:26

2 Answers2

1

In this case, you should use a data structure like a list. For example you could use the following code:

numbers = [100,200]
average = sum(numbers)/len(numbers)
print(average)
whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44
1

You don't. You should use a better structure, like a list or dictionary. With a list, it would look like this:

in_nums = [12, 3, 6, 2, 9]
out_num = sum(in_nums)/len(in_nums)

With a dictionary, it might look like this:

in_nums = {
    x = 12
    y = 3
    z = 6
    w = 2
    q = 9
}     # these are arbitrary names
for num in in_nums:
    out_nums += num
out_nums = out_nums/len(in_nums)

You might use a dictionary so you can still have names for your variables.

CATboardBETA
  • 418
  • 6
  • 29