Python loop to pull items from a list one by one and run them through a block of code

Viewed 41

I am wondering how I would create a loop to pull a tracking numbers from a list one by one and run it through this block of code. The code currently works so there are no issues there. Just don't want to have to copy and paste every single tracking number one by one manually. I think I know how to do this with a for loop, but the if/else statement is confusing me on how I would use the loop.

from usps import USPSApi
from pprint import pprint as pp

userID = ''
usps = USPSApi(userID)

trackingNumber1 = ''

trackingStatus = usps.track(trackingNumber1).result
trackingResponse = trackingStatus.get('TrackResponse')
trackingInfo = trackingResponse.get('TrackInfo')
trackingError = trackingInfo.get('Error')
trackingId = trackingInfo.get('@ID')

if trackingError is None:
  trackingSummary = trackingInfo.get('TrackSummary')
  trackingDetail = trackingInfo.get('TrackDetail')
  print('Tracking Number {0}'.format(trackingId))
  print('Tracking Summary {0}'.format(trackingSummary))
  print('Tracking Detail:')
  pp(trackingDetail)
else:
  trackingHelp = trackingError.get('HelpFile')
  print('Tracking Number {0}'.format(trackingId))
  print('Tracking Error Description: {0}'.format(trackingError.get('Description')))
  print('Tracking Help: {0}'.format(trackingHelp))
1 Answers

If you wish to apply formating to all the elements in a list:

collection = ['a', 'b', 'c']

for item in collection:

    # Example formatting rule
    print(item.upper())

If your values are in a file:

with open("myfile.txt" 'r') as file_handle:

    for line in file_handle:

        # Example formatting rule
        print(line.upper())

Example with control flow logic:

collection = ['a', 'b', 'c']

for item in collection:

    if isinstance(item, str):

        print(item.upper())
Related