Home > database >  How to store values of x in a tuple after performing a loop in python?
How to store values of x in a tuple after performing a loop in python?

Time:09-08

So I am a beginner in python and was given an exercise to find the mean of 6 randomly generated 6-digit numbers. I applied a logic that I can run it through a while loop and get 6 random variables and then get them in a tuple and then find its mean. but I cant get them in a tuple. I don't know what is wrong. PLS HELP!!

and the error its giving me is given after the code that I wrote

    import random as r
import statistics as s
i=1
tup=()
while i<=6:
    x=r.randrange(100000,999999,500)
    tup()==(tup,x)
    i=i 1
    print(x)
    y=s.mean(tup())
    print(y)

Error:-

Traceback (most recent call last):
  File "D:/personal/python programs/siuuu.py", line 85, in <module>
    tup()==(tup,x)
TypeError: 'tuple' object is not callable

CodePudding user response:

tuples aren't editable once created. Use a list instead.

import random as r
import statistics as s
i=1
my_numbers=[]
while i<=6:
    x=r.randrange(100000,999999,500)
    my_numbers.append(x)
    i=i 1
    print(x)

y=s.mean(my_numbers)
print(f"My average is {y}")

CodePudding user response:

import random as r
import statistics as s
from typing import List


num = 6
ll: List[float] = [r.randrange(100000,999999,500) for x in range(num)]
res: float = s.fmean(ll)

CodePudding user response:

You are trying use tuples like list. I suggest you use something like this:

import random as r
import statistics as s

i = 1
my_list = []
while i<=6:
    x=r.randrange(100000,999999,500)
    my_list.append(x)
    print(x)
    y=s.mean(my_list)
    print(y)
    i  = 1

If you want, the list can be tuple-converted after process then it will be immutable.

my_tuple = tuple(my_list)

If you want the result only at the end of the process:

import random as r
import statistics as s
y = s.mean((r.randrange(100000, 999999, 500) for i in range(0,6)))
print(y)

Or

import random as r
import statistics as s

i = 1
my_list = []

while i<=6:
    x=r.randrange(100000,999999,500)
    my_list.append(x)
    print(x)
    i  = 1

my_tuple = tuple(my_list)
y=s.mean(my_tuple)
print(y)

Hope this helps you.

  • Related