Difference between revisions of "How to use while & for loops"

From CompSciWiki
Jump to: navigation, search
m (couple changes to wording of intro)
 
(4 intermediate revisions by 2 users not shown)
Line 1: Line 1:
 
{{Template:1010ExtraLabs
 
{{Template:1010ExtraLabs
 
|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 learn how to use the while and for loop control structures in Python.  
 
==while and for loops syntax in Python:==
 
==while and for loops syntax in Python:==
  
Line 10: Line 10:
 
   Statement(s)
 
   Statement(s)
  
The two sample programs shown below does the following shows
+
The two sample programs below are examples of what typical while and for loops look like.
  
 
|Body=
 
|Body=
  
 
== Sample programs==
 
== Sample programs==
<li>for loop example
+
* for loop example
 
{{CodeBlock
 
{{CodeBlock
|Code=####################################
+
|Code=###############################
 
#Prints out all lower case alphabets
 
#Prints out all lower case alphabets
  
Line 26: Line 26:
 
}}
 
}}
  
<li>while loop example
+
* while loop example
The program below illustrates how to use while loop
+
 
+
 
{{CodeBlock
 
{{CodeBlock
|Code=############################################
+
|Code=###################################################
# Ensures that the user enters either of the  
+
# This program ensures that the user enters either of the  
 
# characters (a, b or c)
 
# characters (a, b or c)
  

Latest revision as of 21:26, 4 April 2012

COMP 1010 Home > Back to Extra Labs

Introduction

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

while and for loops syntax in Python:

while (expression):

  Statement(s)

for iterating_var in sequence:

  Statement(s)

The two sample programs below are examples of what typical while and for loops look like.

Sample programs

  • for loop example
 ###############################
#Prints out all lower case alphabets

letter = 'a'
for i in range (0,26):
    print letter
    letter  = chr(ord(letter) + 1) 
  • while loop example
 ###################################################
# This program 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