Loop Statements in Python

While Loops

while expression:
→Body of while

How a While Loop works :

  1. The expression is the first thing that is checked
  2. The body of the loop is executed only if the expression evaluates to True
  3. After one iteration, the expression is checked again
  4. This process continues until the expression evaluates to False

Example of code :

start=1while (start<=1000):
→ print(start)
→ start=start+1
print(“While Loop Finished”)
start=1while (start<=1000):
→print(start)
print(“While Loop Finished”)

Making shapes using a While Loop :

import turtlemy_turtle=turtle.Turtle()my_turtle.speed(1)a=1while a<=4:→my_turtle.forward(100)→my_turtle.right(90)a=a+1
import turtleangle=91a=0turtle.speed(15)while a<100:→turtle.circle(a)→turtle.left(angle)a=a+1

For Loops

for var in sequence:
→Body of for
num = [ 5, 6, 3, 4, 8, 4, 11, 2, 5]
sum = 0
for value in num:
→sum = sum+value
→print(sum)
print(“The sum is”, sum)

Range Function :

Syntax of Range :

print(range(1,10))
print(list(range(10)))

Example of Code using Range :

for x in range(10):→print(“The Number is”,x)print(“For Loop Ended”)

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Create a test data generator using Kafka Connect

Helidon.io, Oracle Wercker and Oracle Kubernetes Engine working together. Part 1 of 2.

Port 443 is already in use — Wondering what to do?

Deploy Asp.Net Core Web Api on IIS

Managing distributed transactions in OfferUp’s shipping feature

Object-Oriented Programming (OOP) in Python

Journey from being Homeless to a Software Developer back to Homelessness

Towards Sentient Systems…one step at a time!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Navya Gunda

Navya Gunda

More from Medium

Operators In Python

String Manipulation Python

Introduction to Python Programming? What is Python Programming?

Introduction to Python Programming Manglastubh by ankit akolkar

Python vs Other Programming Languages.