# A first look at the while loop
i = 1
while i < 11:
print "This is line number %d"%i
i += 1 # Python doesn't support "++" or "--" shorthand expressions
# Countdown to blastoff
i = 10
print "Countdown"
while i >= 0 :
print "%d"%i
i -= 1
print "\n\nBlastoff!"
# Hailstones
counter = 0;
print "Enter a positive integer:",
n = 51
print n
nsave = n
while n > 1:
if n % 2 : # if (n % 2) is non-zero, n is not divisible by 2 and is therefore odd
n = n * 3 + 1
else :
n /= 2
counter += 1
print "Step %4d: n = %4d"%(counter,n)
print "\n\n%d went to 1 in %d steps."%(nsave,counter)
# Computing the factorial
print "Type in a positive integer:",
n = 6
print n
nsave = n
factorial = 1
while n > 1 :
factorial *= n
n -= 1
print "Factorial of %d = %d"%(nsave,factorial)
# Computing the factorial (shorter version)
print "Type in a positive integer: ",
n = 6
print n
nsave = n
factorial = 1
while n > 1 :
factorial *= n # Since python doesn't support '--' expression, the given program cannot be shortened
n -= 1
print "Factorial of %d = %d"%(nsave,factorial)
# Illustration of do..while loops
# This program reads in an integer, adds up the values of each of its individual digits, and prints out the sum.
sum = 0
print "Type in an integer:",
n = 1776
print n
# There is no do...while loop in python
# An equivalent while loop can work
while n > 0 :
rightmost_digit = n % 10 # Extract rightmost digit
sum += rightmost_digit
n /= 10 # Move next digit into rightmost position
print "The sum of the digits is %d"%sum
import sys
# This program reads in an integer and prints it out backwards
print "Type in an integer: ",
n = 5746
print n
print "%d backwards is "%n,
while n > 0 :
rightmost_digit = n % 10
sys.stdout.write("%d"%rightmost_digit) # For printing in the same line without implicit whitespaces
n /= 10
print # For the new line
# A program to read in numbers and print out their squares
print "Enter an integer (negative to quit):",
n = 5
print n
while n > 0 :
print "%d squared is %d"%(n,n*n)
print "\nEnter an integer (negative to quit):",
n = -1
print n
# A program to read in radius values and print out the circumference and area
pi = 3.1416
print "Enter radius (negative to quit):",
radius = 4.5
print radius
while radius >= 0.0 :
print "The circumference is %f"%(2.0 * pi * radius)
print "The area is %f"%(pi * radius * radius)
print "\nEnter radius (negative to quit):",
radius = -1.0
print radius
# A program to read in length and width and print out the perimeter and area
print "Enter length and width"
print " (one or both negative to quit):",
length = 4
width = 5
print length,width
while length > 0 and width > 0 :
print "The perimeter is %d"%(2*(length+width))
print "The area is %d"%(length*width)
print "\nEnter length and width"
print " (one or both negative to quit):",
length = -1
width = 0
print length,width