Learning To Use while Loops

So I skipped ahead to Chapter 5 in Hetland, and learned some about conditionals and loops, and though I’m sure I’ve just stumbled onto extremely fruitful ground, the only really obvious application I saw that I could apply to the programs I’ve already written was the use of a while loop to make sure the user didn’t just press the <enter> key without typing something else first (which, to be honest, Hetland pointed out, but I tried to code it myself based on the concept alone — and apparently it’s not a very great achievement, since the code I wrote looked the same as his 😛 ). So in the spirit of a previous post, here’s a mess of updates, all with screenshots and folded source code.

Even my very first program didn’t escape! Hello World! now has a while loop to prevent blank input. I give you date.v1-1-2.py:

Hello World! v1.1.2

Hello World! v1.1.2

#!/usr/bin/env python

# hello.py v1.1.2
# Hello World!
#
# Changelog:
# v1.1.2 (09/19/2010) + Now ensures user enters a name
# v1.1.1 (09/11/2010) + Added GPLv3 license text & changelog to comments
#                     + Added user-visible program & (c) info
#                     + Re-commented program, because we were all newbs once
# v1.1 (08/08/2010) + Added "Press <enter>" prompt for terminal execution
#                   - Deleted unnecessary comments
# v1.0 (07/20/2010) - Initial release (My first program!)
#
# Copyright 2010 Benjamin Braithwaite
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# user interface 😛

print "Hello World! v1.1.2"
print "Copyright 2010 by Benjamin Braithwaite"
print
name = ""
while not name.strip():
    name = raw_input("What is your name? ")

# print user's name in a friendly greeting

print
print "Hello, " + name + "!"
print

# successful exit dialog

raw_input("Press <enter> to exit.")

You can download date.v1-1-2.py from my Dropbox.

Similar treatment for Date Translator, now updated to date.v1-1-3.py:

Date Translator v1.1.3

Date Translator v1.1.3

#!/usr/bin/python

# date.py v1.1.3
# Date Converter
#
# Changelog:
# v1.1.3 (09/19/2010) + Now ensures user enters a date
# v1.1.2 (09/11/2010) + Added GPLv3 license text & changelog to comments
#                     + Added user-visible program & (c) info
#                     + Cleaned up comments & code for consistency
# v1.1.1 (08/21/2010) * Now handles single-digit DD correctly
# v1.1 (08/08/2010) + Changed to be a MM/DD/YYYY converter
# v1.0 (08/08/2010) + Initial release (My second program!)
#                   + Convert numbers to American-style dates
#
# v1.1.1 - Correctly handles single-digit DD
# v1.1 - Convert numbers to American-style dates
# v1.0 - Convert numbers to American-style dates
#
# Copyright 2010 Benjamin Braithwaite
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# user interface 😛

print "Date Converter v1.1.3"
print "Copyright 2010 by Benjamin Braithwaite"
print
print "Convert MM/DD/YYYY dates to \"January 1st, 2010\" style."
print
mmddyyyy = ""
while not mmddyyyy.strip():
	mmddyyyy = raw_input("Enter date in MM/DD/YYYY format: ")

# MM-to-month list

mm_list = (
	"January",
	"February",
	"March",
	"April",
	"May",
	"June",
	"July",
	"August",
	"September",
	"October",
	"November",
	"December"
)

# set DD-to-day suffixes (1st, 2nd, 3rd, 4th ... 20th, 21st, etc.)

dd_suffix = ["st","nd","rd"] + 17*["th"] + ["st","nd","rd"] + 7*["th"] + ["st"]

# divides user input into separate MM, DD, and YYYY strings

mm_str = mmddyyyy[0:2]
dd_str = str(int(mmddyyyy[3:5]))
yyyy_str = mmddyyyy[6:10]

# format MM and DD strings (done separately for readability)

mm_name = mm_list[int(mm_str)-1]
dd_ordinal = dd_str + dd_suffix[int(dd_str)-1]

# print results onscreen

print
print "Your date is: " + mm_name + " " + dd_ordinal + ", " + yyyy_str
print

# successful exit dialog

raw_input("Press <enter> to exit...")

You can download date.v1-1-3.py from my Dropbox.

I also added similar functionality to Domain Name Extractor, as well as adding a function that strips any whitespace at the beginning or end of the URL. The new domainname.v1-0-2.py:

Domain Name Extractor v1.0.2

Domain Name Extractor v1.0.2

#!/usr/bin/env python

# domainname.py v1.0.2
# Domain Name Extractor
#
# Changelog:
# v1.0.2 (09/19/2010) + Now ensures user enters a URL
#                     + Strips spaces from beginning and end of URL
# v1.0.1 (09/11/2010) + Added GPLv3 license text & changelog to comments
#                     + Added user-visible program & (c) info
#                     + Added comments for readability
#                     + Changed URL stripping to require final "/"
# v1.0.0 (08/21/2010) + Initial version (Extract domain name from a URL)
#
# Copyright 2010 Benjamin Braithwaite
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# user interface 😛

print "Domain Name Extractor v1.0.2"
print "Copyright 2010 by Benjamin Braithwaite"
print
print "Strips the domain name from a full URL"
print
url = ""
while not url.strip():
    url = raw_input ("Please enter a full URL (e.g., \"http://www.yahoo.com/\"): ")

# strip domain name from url

domain = url.strip()[11:-5]

# print domain name

print
print "The domain name of the URL you entered is: " + domain
print

# successful exit dialog

raw_input ("Press <enter> to exit.")

You can download domainname.v1-0-2.py from my Dropbox as well.

And Quotation Box got the while love, too. Gape at the amazingly fresh new quotationbox.v1-1-1.py:

Quotation Box v1.1.1

Quotation Box v1.1.1

#!/usr/bin/env python

# quotationbox.py v1.1.1
# Quotation Box
#
# Changelog:
# v1.1.1 (09/19/2010) + Now ensures user enters a quotation
# v1.1.0 (09/11/2010) + Added GPLv3 license text & changelog to comments
#                     + Added user-visible program & (c) info
#                     + Cleaned up comments and code
# v1.0.0 (08/21/2010) + Initial release (Take user input and make a centered
#                         ASCII box around it)
#
# Copyright 2010 Benjamin Braithwaite
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# user interface 😛

print "Quotation Box v1.1.1"
print "Copyright 2010 by Benjamin Braithwaite"
print
quotation = ""
while not quotation.strip():
    quotation = raw_input ('Enter your quotation here: ')

# DEFAULT, assume terminal width is 80

term_width = 80

# OR, ask user for his terminal width

# term_width = int(raw_input ("What is your terminal width? (Usually 80): "))

# determine width of quotation and box accordingly

q_width = len(quotation)
margin_left = (term_width - (q_width + 4)) // 2

# print quotation in centered ASCII box

print
print " " * margin_left + "+-" + "-"*q_width + "-+"
print " " * margin_left + "| " + " "*q_width + " |"
print " " * margin_left + "| " +  quotation  + " |"
print " " * margin_left + "| " + " "*q_width + " |"
print " " * margin_left + "+-" + "-"*q_width + "-+"
print

# successful exit dialog

raw_input ("Press <enter> to exit.")

You can download quotationbox.v1-1-1.py from my Dropbox, because that’s the cool thing to do, kids.

I wanted to do something with while in dictionaries with Madlibs, but I can’t figure out a way to do it… yet. I hope I can, because I think it would greatly neaten up the code if it works.

Meanwhile, ROT13 Encoder got updated with while goodness. In its full glory, here is rot13encoder.v1-0-1.py:

ROT13 Encoder v1.0.1

ROT13 Encoder v1.0.1

#!/usr/bin/env python

# rot13encoder.py v1.0.1
# ROT13 encoder
#
# Changelog:
# v1.0.1 (09/19/2010) + Now ensures user enters text
# v1.0.0 (09/06/2010) + Initial release
#
# Copyright 2010 Benjamin Braithwaite
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# imports maketrans capability

from string import maketrans

# generate ROT13 translation table

rot13table = maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",\
"NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm")

# user interface and encoding magics

print "ROT13 Encoder v1.0.1"
print "Copyright 2010 by Benjamin Braithwaite"
print
toberotted = ""
while not toberotted.strip():
    toberotted = raw_input("Enter the text you wish to encode into ROT13: ")
print
print toberotted.translate(rot13table)
print

raw_input ('Press <enter> to exit.')

You can download rot13encoder.v1-0-1.py from my Dropbox.

Sameness done to ROT13 Decoder, so here’s rot13decoder.v1-0-1.py:

ROT13 Decoder v1.0.1

ROT13 Decoder v1.0.1

#!/usr/bin/env python

# rot13decoder.py v1.0.1
# ROT13 decoder
#
# Changelog:
# v1.0.1 (09/19/2010) + Now ensures user enters text
# v1.0.0 (09/06/2010) + Initial release
#
# Copyright 2010 Benjamin Braithwaite
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# imports maketrans capability

from string import maketrans

# generate ROT13 translation table

derot13table = maketrans("NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm",\
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")

# user interface and decoding magics

print "ROT13 Decoder v1.0.1"
print "Copyright 2010 by Benjamin Braithwaite"
print
tobederotted = ""
while not tobederotted.strip():
    tobederotted = raw_input("Enter the ROT13 text you wish to decode: ")
print
print tobederotted.translate(derot13table)
print

raw_input ('Press <enter> to exit.')

You can download rot13decoder.v1-0-1.py from my Dropbox.

E-mail Quotation Reformatter got a touch of the while, too. Behold, it is emailquotationreformatter.v1-0-2.py:

E-mail Quotation Reformatter v1.0.2

E-mail Quotation Reformatter v1.0.2

#!/usr/bin/env python

# emailquotationreformatter.py v1.0.2
# E-mail Quotation Reformatter
#
# Changelog:
# v1.0.2 (09/19/2010) + Now ensures user enters a quotation
# v1.0.1 (09/11/2010) + Cleaned up code and comments
# v1.0.0 (09/06/2010) + Initial release (Strips initial spaces and >'s from
#                         e-mail quotations)
#
# Copyright 2010 Benjamin Braithwaite
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# user interface 😛

print "E-mail Quotation Reformatter v1.0.2"
print "Copyright 2010 by Benjamin Braithwaite"
print
print "Strips initial spaces and \>\'s from e-mail quotations"
print
qtostrip = ""
while not qtostrip.strip():
    qtostrip = raw_input("Enter the e-mail quotation you wish to reformat: ")

# strip and print results

print
print qtostrip.lstrip(" >")
print

# successful exit dialog

raw_input ("Press <enter> to exit.")

You can download emailquotationreformatter.v1-0-2.py from my Dropbox. Fnord.

Phonebook and HTML Page Generator escaped this round of code revisions for much the same reasons Madlibs did — I’m not sure how to implement while and raw_input inside a dictionary string substitution.

Again, I’m sorry for the flurry of fairly trivial updates, but this round has taught me the importance of while loops, and therefore the usefulness of Booleans in code.

Advertisements

One thought on “Learning To Use while Loops

  1. Pingback: if And else Are My New Best Friends « Becoming A Glider

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s