Tutorials
Hands-On Python
Hands-On Python
  • Hands-On Python Tutorial For Real-World Business Analytics Problems
  • Preface
    • Section I. A Note From The Author
    • Section II. Tutorial Overview
    • Section III. What Is The Preflight Checklist?
    • Section IV. Supplimentery Material
  • Preflight Checklist
    • Section V. Select Your Difficulty Setting
    • Section VI. Download Anaconda
    • Section VII. Download PyCharm (Optional)
    • Section VIII. Download SQL Server Developer Edition
    • Section IX. Configure Database Environment
    • Section X. Download The Source Code
    • Section XI. Starting JupyterLab
    • Section XII. How To Get Help With This Tutorial
  • Language Basics
    • Lesson 1. Obligatory Hello World
    • Lesson 2. Code Comments
    • Lesson 3. Data Types
    • Lesson 4. Variables
    • Lesson 5. String Concatenation
    • Lesson 6. Arithmetic Operators
    • Lesson 7. Making Decisions
    • Lesson 8. Control Flow With if-elif-else
    • Lesson 9. Control Flow With while
    • Lesson 10. Data Structures Part I: List
    • Lesson 11. Data Structures Part II: Tuples
    • Lesson 12. Data Structures Part III: Dictionaries
    • Lesson 13. Looping With for
    • Lesson 14. Functions
    • Lesson 15. Importing Modules
    • Lesson 16. Python Programming Standards
  • Advanced Topics
    • Lesson 17. Functional Programing With map
    • Lesson 18. Generators
    • Lesson 19. Comprehensions
    • Lesson 20. Basic File Operations
    • Lesson 21. Working With Data In Numpy
    • Lesson 22. Working With Data In Pandas
    • Lesson 23. Working With JSON
    • Lesson 24. Making File Request Over HTTP And SFTP
    • Lesson 25. Interacting With Databases
    • Lesson 26. Saving Objects With Pickle
    • Lesson 27. Error Handling
    • Lesson 28. Bringing It All Together
  • Solutions To Real World Problems
    • Lesson 29. Download A Zip File Over HTTP
    • Lesson 30. Looping Over Files In A Directory
    • Lesson 31. Convert Comma Delmited Files To Pipe Delimited
    • Lesson 32. Combining Multiple CSVs Into One File
    • Lesson 33. Load Large CSVs Into Data Warehouse Staging Tables
    • Lesson 34. Efficiently Write Large Database Query Results To Disk
    • Lesson 35. Working With SFTP In The Real World
    • Lesson 36. Executing Python From SQL Server Agent
Powered by GitBook
On this page
  • for Syntax
  • Examples
  • Now you try it!
  1. Language Basics

Lesson 13. Looping With for

We're gonna loop back to talking about loops (see what I did there?).

The reason for the step back is because there are objects in Python that work with for loops in ways that make iterating through complex objects really easy. List, tuples, and dictionaries are three of those objects. I had to introduce them first before I showed you how to loop through them with for.

For loops are another basic concept in computer science and you will find the for construct in most programming languages. For is my preferred way of looping.

Technically, the for loop construct in Python is not like the for found in other programming languages. In other languages, you usually define a condition that is checked against an incrementing value like we saw back when we were talking about while.

In Python, the for loop is for iterating over sequences. Those sequences can be the three complex data types that we are already familiar with. Later, we will see that sequences can include things like file names which comes in handy when you need to do work on a bunch of files in a folder.

Just like in while, for can be used with break and continue to control the flow of the execution.

for Syntax

for [variable_name] in [object]:
    #do stuff

Examples

Example #1 Looping Over A List

The variable that you use in your for loop can be referred to in the code block. It represents the current value of the object you are iterating through.

You can define the variable yourself, however, in certain use cases, the variable needs to be a Python reserved word. We will take a look at that when we get to looking at looping over files in a directory.

fighters = ['Eagle', 'Falcon', 'Tomcat']

for birds in fighters:
    print(birds)

Example #2 Looping Over A Tuple

lat_long = (38.9984961,-104.8540895)

for x in lat_long:
    print(x)

Example #3 Looping Over A Dictionary

paygrade_translation = {'O1':'2nd Lt','O2':'1st Lt','O3':'Capt'}

#Just the keys
for description in paygrade_translation.keys():
    print(description)
#The full key value pair
#Notice how we add a second variable that can be referenced in the loop?

for paygrade, description in paygrade_translation.items():
    print('A paygrade of ' + paygrade + ' is a ' + description)

Example #4 Looping Over A Predefined Range

You can use for like you would in other languages using the range() method. The range method lets you define a range of values to loop over. The method has three parameters that define the range of values. The method can be called with one to three parameters.

It is important to remember that the upward bound of the range is NOT inclusive. In other words, if you set an upward bound of 5, the stopping value will be 4.

#Start at zero and you provide the maximum value.

for x in range(5):
    print(x)
#You provide the minimum and maximum value.

for x in range(15,20):
    print(x)
#You provide the minimum, maximum,and increment value.

for x in range(1,10,2):
    print(x)

Now you try it!

Don't copy and past. Type the code yourself!

PreviousLesson 12. Data Structures Part III: DictionariesNextLesson 14. Functions

Last updated 3 years ago