In Python, and many other programming languages, you will need to loop commands several times, or until a condition is fulfilled. It is easy, and the loop itself only needs a few lines of code.

Steps

  1. 1
    Open up your shell or program. This may be IDLE, or Stani's Python Editor (SPE). Make sure all subprograms are off if using IDLE.
  2. 2
    If you need to loop a definite amount of times, you need a for loop. This is the structure for a for loop:
    • for i in range (0, 10):
    • print "Hello World"
  3. 3
    If you need something to loop forever, or until a condition is met, you need a while loop. A method for both is shown.
    • while True:
    • print "Hello World"
  4. 4
    This will loop forever, or until the program ends. (True will always be True).
    • while answer == "Yes" and grade == "6":
    • As long as the variables answer and grade are Yes and 6,
  5. 5
    If you need to stop a loop, use Ctrl-C. You can always kill the loop in task manager as well.

Community Q&A

  • Question
    How do you do a nested loop?
    Adam Blalock
    Adam Blalock
    Community Answer
    Here is a loop within a loop in Python: x = [0,1,2,3,4], y= [10,11,12,13]. For i in x: For ii in y: print i + ii. (Make sure to do it as a single tab before the second "For" and two tabs for the "print" statement.)
  • Question
    What about web development?
    Community Answer
    Community Answer
    You need to learn about Django, the Python framework for web development.
  • Question
    How do you use a while loop to repeat a calculator program?
    Community Answer
    Community Answer
    First create a function. For example, if you wanted to square numbers 1 through 100 and print the results to the screen, I would write: def square(x): return x*x for i in range(1, 101): # stop = 101 because the stop value is not included. This will go from 1-100. print(square(i)).

About This Article

wikiHow is a “wiki,” similar to Wikipedia, which means that many of our articles are co-written by multiple authors. To create this article, 14 people, some anonymous, worked to edit and improve it over time. This article has been viewed 49,729 times.
How helpful is this?
Co-authors: 14
Updated: November 5, 2020
Views: 49,729
Categories: Python