title: Having trouble with code that works out the closest number from a list
body: <p>I am making some code that allows me to choose the closest number from a list, I have managed to do that. However when the closest number is found and its over 'myNumber' I want python to print out the number in the list  before it.</p>
  
  <p>For example;</p>
  
  <p>if i were to have a list;</p>
  
  <pre><code>TwoN = [1,2,4,8,16,32,64,128,256,512, 1024, 2048, 4096, 8192]
  </code></pre>
  
  <p>and </p>
  
  <pre><code>myNumber = 30
  </code></pre>
  
  <p>I want python to print 16 not 32 </p>
  
  <p>This is the code i've done so far...</p>
  
  <pre><code>TwoN = []
  for i in range(12):
      TwoN.append(2**i)
  print(TwoN)
  
  myNumber = 30
  closest = TwoN[0]
  for i in range(1, len(TwoN)):
      if abs(TwoN[i] - myNumber) &lt; abs(closest - myNumber):
          closest = TwoN[i];
  
  
  Sum = myNumber - closest
  if Sum &lt; 0:
      closest = TwoN[(i-1)]
      print(closest)
  else:
      print(closest)
  </code></pre>
  
  <p>When myNumber = 30 , the program will output 1024 when i want it to output 16..</p>
  
  <p>any help is appreciated thanks</p>