メインコンテンツにスキップ

Python Loops Tutorial

A comprehensive introductory tutorial to Python loops. Learn and practice while and for loops, nested loops, the break and continue keywords, the range function and more!
· 15 分 読む

AIで探求

range Python

Loops are important in Python or in any other programming language as they help you to execute a block of code repeatedly. You will often come face to face with situations where you would need to use a piece of code over and over but you don't want to write the same line of code multiple times.

In this Python loops tutorial you will cover the following topics :

  • The Python while loop: you'll learn how you can construct and use a while loop in data science applications. You'll do this by going over some interactive coding challenges.
  • Next, you'll move on to the for loop: once again, you'll learn how you can construct and use a for loop in a real-life context.
  • You'll also learn the difference between using a while loop and a for loop.
  • Also the topic of nested loops
  • After, you'll see how you can use the break and continue keywords.
  • The difference between the xrange() and range() functions

While Loop

The while loop is one of the first loops that you'll probably encounter when you're starting to learn how to program. It is arguably also one of the most intuitive ones to understand: if you think of the name of this loop, you will quickly understand that the word "while" has got to do something with "interval" or a "period of time". As you already know by now, the word "loop" refers to a piece of code that you execute repeatedly.

With all of this in mind, you can easily understand the following definition of the while loop:

A while loop is a programming concept that, when it's implemented, executes a piece of code over and over again while a given condition still holds true.

The above definition also highlights the three components that you need to construct the while loop in Python:

  • The while keyword;
  • A condition that transates to either True or False; And
  • A block of code that you want to execute repeatedly

That's all it takes!

How To Make A While Loop in Python

Now that you know what you need to construct a while loop, all that is left to do now is to look at a real-life example where the while loop is used before you start making exercises on your own! Consider the following example:

# Take user input
number = 2  

# Condition of the while loop
while number < 5 :  
    print("Thank you")
    # Increment the value of the variable "number by 1"
    number = number+1

# Thank you
# Thank you
# Thank you