Difference between revisions of "Convert a for loop to a while loop"

From CompSciWiki
Jump to: navigation, search
 
Line 2: Line 2:
 
|Chapter_TOC=[[Extra Labs]]
 
|Chapter_TOC=[[Extra Labs]]
 
|Introduction=In this program, you will be learn how to use while and for loop control structures in Python.  
 
|Introduction=In this program, you will be learn how to use while and for loop control structures in Python.  
===[[while and for loops syntax in Python:]]===
+
<li>while and for loops syntax in Python:
  
 
while (expression):
 
while (expression):
Line 14: Line 14:
 
|Body=
 
|Body=
  
===[[for loop]]===
+
<li>'''for loop:'''
 
  The program below shows how to print out alphabets in a for loop:
 
  The program below shows how to print out alphabets in a for loop:
 
{{CodeBlock
 
{{CodeBlock
Line 26: Line 26:
 
}}
 
}}
  
===[[while loop example]]===
+
<li>while loop example
 
The program below illustrates how to use while loop
 
The program below illustrates how to use while loop
  

Latest revision as of 23:26, 3 April 2012

COMP 1010 Home > Back to Extra Labs

Introduction

In this program, you will be learn how to use while and for loop control structures in Python.

  • while and for loops syntax in Python: while (expression): Statement(s) for iterating_var in sequence: Statements(s) The program below shows how to print out alphabets in a for loop
  • Contents

  • for loop: The program below shows how to print out alphabets in a for loop:
     ####################################
    #Prints out all lower case alphabets
    
    letter = 'a'
    for i in range (0,26):
        print letter
        letter  = chr(ord(letter) + 1) 
  • while loop example The program below illustrates how to use while loop
     ############################################
    # Ensures that the user enters either of the 
    # characters (a, b or c)
    
    ## Gets input from th user
    message = raw_input("Please enter a, b, or c: ")
    
    while(message != "a" and message != "b" and message != "c"):
        message = raw_input("Please enter a, b, or c:")
    print "You entered: " + message