i = 0
*# While loop condition.*
while i < 10:
print(*"WHILE:"*, i)
*# Add one.*
i += 1WHILE: 0
WHILE: 1
WHILE: 2
WHILE: 3
WHILE: 4
WHILE: 5
WHILE: 6
WHILE: 7
WHILE: 8
WHILE: 9

i = 10
*# While greater than or equal to zero.*
while i >= 0:
print(i)
*# End loop if evenly divisible by seven.*
if i % 7 == 0:
break
i -= 110
9
8
7

if

i = 0
*# While loop condition.*
while i > 100:
print(i)
*# Subtract two.*
i -= 2
else:
print(*"Loop not entered"*)Loop not entered

random

import random
*# A while-true loop.*
while True:
n = random.randint(0, 100)
print(n)
*# Break on even random number.*
if n % 2 == 0:
break41
13
99
18

pass

import random
def m():
*# Get random number.*
n = random.randint(0, 3)
print(n)
*# Return true if number is less than 3.*
return n <= 2
*# Call method until it returns false.*
while m():
*# Do nothing in the loop.*
pass0
2
2
3

list = [*"cat"*, *"dog"*, *"panther"*, *"parakeet"*]
i = 0
while i < len(list):
element = list[i]
i += 1
*# Test for this element.*
if element == *"panther"*:
continue
*# Display element.*
print(*"Pet"*, element)Pet cat
Pet dog
Pet parakeet

import random
while True:
*# Get random int.*
n = random.randint(0, 100)
print(*"RANDOM"*, n)
if n % 2 != 0:
print(*"ODD"*)
breakRANDOM 54
RANDOM 64
RANDOM 53
ODD

def valid_number(i): return i <= 3
def handle_number(i):
print(f*"Hello friend {i}"*)
*# Next number.*
return i + 1
i = 0
*# Use a while-True loop on one line.*
while valid_number(i): i = handle_number(i)Hello friend 0
Hello friend 1
Hello friend 2
Hello friend 3

import time
names = [*"San Jose"*, *"Denver"*, *"New York"*, *"Phoenix"*]
print(time.time())
*# Version 1: for-loop.*
i = 0
while i < 100000:
count = 0
*# Loop.*
for name in names:
count += len(name)
i = i + 1
print(time.time())
*# Version 2: while-loop.*
i = 0
while i < 100000:
count = 0
*# Loop.*
x = 0
while x < len(names):
count += len(names[x])
x = x + 1
i = i + 1
print(time.time())For-loop: 98 ms
While-loop: 219 ms

for

Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.

Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.

This page was last updated on Mar 1, 2024 (edit).