Python Forum

Full Version: Variable info from a FOR loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,
I have this FOR loop reading 8 channels from 3008 adc.
It runs eight times and thus i want 8 different values (ADC) as a result.

def read_tmp36(sensorid):
        adc = (8+sensorid)
        return adc

offset = 0
for offset in range(0,8):

      adc = read_tmp36(offset)

      print(adc)
      offset +=1
      
Never mind the code shown for it is only for experimenting but how can i get the 8 different values for the 8
channels out of this loop.
Or... should i use a totally different approach?
def read_tmp36(sensorid):
    adc = (8+sensorid)
    return adc
 
for offset in range(0,8):
    adc = read_tmp36(offset)
    print(adc)
Never mind people,
i licked the problem myself.
I used a indexed list.
def read_tmp36(sensorid):
        adc = (8+sensorid)
        return adc

lijst=[0,0,0,0,0,0,0,0]
for offset in range(0,8):
    adc = read_tmp36(offset)
    print(adc)
    lijst[offset]=adc
    offset +=1

print (lijst)
    
'lijst' neatly gives me the eight values.
Now i have to find out how to break down the list into individual numbers.
To get a list you could have append the result in a list from @buran solution.
def read_tmp36(sensorid):
    adc = (8+sensorid)
    return adc

lst = []
for offset in range(0,8):
    adc = read_tmp36(offset)
    lst.append(adc)

print(lst)
Output:
[8, 9, 10, 11, 12, 13, 14, 15]
Or list comprehension.
def read_tmp36(sensorid):
    adc = (8+sensorid)
    return adc

print([read_tmp36(offset) for offset in range(0,8)])
Output:
[8, 9, 10, 11, 12, 13, 14, 15]
As generator:

# dummy function to run the code
# this function should simulate the adc
read_adc = lambda x: (x + 2.6) * 1.8

def read_tmp(sensorid):
    return read_adc(8 + sensorid)
 
def read_all():
    for channel in range(8):
        yield read_tmp(channel)

# you define outside of the function which
# container object you create
all_sensor_data = list(read_all())
# the generator read_all() iterates until it's exhausted
# it's consumed by list
print(all_sensor_data)