473,414 Members | 1,677 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,414 software developers and data experts.

ten small Python programs

I've always thought that the best way to introduce new
programmers to Python is to show them small code
examples.

When you go to the tutorial, though, you have to wade
through quite a bit of English before seeing any
Python examples.

Below is my attempt at generating ten fairly simple,
representative Python programs that expose new users
to most basic concepts, as well as the overall syntax.

It was an interesting exercise. I constrained myself
to ten lines or less, and it was pretty easy to
incorporate loops, conditionals, print, open(), lists,
tuples, dictionaries, and imported modules.

It was harder to show classes, and my ShoppingCart
class is nothing more than an encapsulation of a list,
which has dubious value (although it's the start of
something more useful).

Anyway, here goes:

------
print 'hello world'

------
for name in ('peter', 'paul', 'mary'):
print name

------
# This is a Python comment. \n is a newline
name = raw_input('What is your name?\n')
print 'Hi', name

------
parentRabbits, babyRabbits = (1, 1)
while babyRabbits < 100:
print 'This generation has %d rabbits' %
babyRabbits
parentRabbits, babyRabbits = (babyRabbits,
parentRabbits + babyRabbits)
------
# def defines a method in Python
def tax(itemCharge, taxRate = 0.05):
return itemCharge * taxRate
print '%.2f' % tax(11.35)
print '%.2f' % tax(40.00, 0.08)
------
import re
for test_string in [ '555-1212', 'ILL-EGAL']:
if re.match('\d\d\d-\d\d\d\d$', test_string):
print test_string, 'is a valid US local
phone number'
else:
print test_string, 'rejected'

------
prices = {'apple': 0.40, 'banana': 0.50}
myPurchase = {
'apple': 1,
'banana': 6}
groceryBill = sum([prices[fruit] *
myPurchase[fruit]
for fruit in myPurchase])
print 'I owe the grocer $%.2f' % groceryBill
------
class ShoppingCart:
def __init__(self): self.items = []
def buy(self, item): self.items.append(item)
def boughtItems(self): return self.items
myCart = ShoppingCart()
myCart.buy('apple')
myCart.buy('banana')
print myCart.boughtItems()
------
# indent your Python code to put into an email
import glob
pythonFiles = glob.glob('*.py')
pythonFiles.sort()
for fn in pythonFiles:
print ' ------'
for line in open(fn):
print ' ' + line.rstrip()
print

------
import time
now = time.localtime()
hour = now.tm_hour
if hour < 8: print 'sleeping'
elif hour < 9: print 'commuting'
elif hour < 17: print 'working'
elif hour < 18: print 'commuting'
elif hour < 20: print 'eating'
elif hour < 22: print 'resting'
else: print 'sleeping'

__________________________________________________ __________________________________
Expecting? Get great news right away with email Auto-Check.
Try the Yahoo! Mail Beta.
http://advision.webevents.yahoo.com/...ail_tools.html
May 26 '07 #1
12 2724
Steve Howell wrote:
I've always thought that the best way to introduce new
programmers to Python is to show them small code
examples.

When you go to the tutorial, though, you have to wade
through quite a bit of English before seeing any
Python examples.

Below is my attempt at generating ten fairly simple,
representative Python programs that expose new users
to most basic concepts, as well as the overall syntax.

Very cool! Do you mind putting this up on the Wiki somewhere so that we
can link to it more easily? Maybe something like:

http://wiki.python.org/moin/SimplePrograms

<nitpick>
Though the code should probably follow PEP 8 guidelines, e.g.
under_scores instead of camelCase for object and method names:

http://www.python.org/dev/peps/pep-0008/
</nitpick>
class ShoppingCart:
def __init__(self): self.items = []
def buy(self, item): self.items.append(item)
def boughtItems(self): return self.items
myCart = ShoppingCart()
myCart.buy('apple')
myCart.buy('banana')
print myCart.boughtItems()
I think boughtItems() is probably not a good example of Python code
since in this case, you should probably just write ``my_cart.items``.
Maybe it should define ``__len__`` instead? Or maybe something like::

def select_items(self, prefix):
return [item for item in self.items if item.startswith(prefix)]
STeVe
May 26 '07 #2
I ***love*** this "10 Little Programs" idea! As soon as I get a
breathing space, I'm going to add a "10 Little Parsers" page to the
pyparsing wiki!

On May 26, 2:38 pm, Steven Bethard <steven.beth...@gmail.comwrote:
<nitpick>
Though the code should probably follow PEP 8 guidelines, e.g.
under_scores instead of camelCase for object and method names:

http://www.python.org/dev/peps/pep-0008/
</nitpick>
Really? Underscore-separated words preferred over camel case? What
is the rationale for this? This style is so retro/80's/C-ish. It
seems more like a Java backlash to me than anything else. If we (or
Guido) don't like changing case to indicate word breaks, why are class
names to be UpperCamelCase, and not Capitalized_with_underscores? If
there is a casing convention nit to pick, I'd focus on UpperCamelCase
for class names, lower case (either with underscores or mixed case)
for attributes and method names, and UNDERSCORE_SEPARATED_ALL_CAPS for
constants.

If we want to just say "well, PEP-8 says such and such," I think this
is an area where the thinking has possibly evolved since 2001. Also,
I think the PEP would benefit from explicitly discouraging some
practices, such as Hungarian notation.
>
class ShoppingCart:
def __init__(self): self.items = []
def buy(self, item): self.items.append(item)
def boughtItems(self): return self.items
myCart = ShoppingCart()
myCart.buy('apple')
myCart.buy('banana')
print myCart.boughtItems()
If you want to nitpick, I'd rather go after the one-liner methods with
the body on the same line as the def statement.

How's this for a better non-trivial method example:

MAX_ITEMS_FOR_EXPRESS_LANE = 10
def canUseExpressLane(self):
return (len(self.items) <= MAX_ITEMS_FOR_EXPRESS_LANE)

or call it "can_use_express_lane" if you must.

I guess pyparsing with its mixedCase functions and attributes is
doomed for the Dunce Corner. Too bad for BeautifulSoup, cElementTree,
and wxPython that are also at variance with this canon of Python
coding style. ("Modules should have short, all-lowercase names. ...
Python packages should also have short, all-lowercase names, although
the use of underscores is discouraged.")

-- Paul

May 27 '07 #3
Paul McGuire wrote:
[...].
>
I guess pyparsing with its mixedCase functions and attributes is
doomed for the Dunce Corner. Too bad for BeautifulSoup, cElementTree,
and wxPython that are also at variance with this canon of Python
coding style. ("Modules should have short, all-lowercase names. ...
Python packages should also have short, all-lowercase names, although
the use of underscores is discouraged.")
Although the names in wxPython are indeed contrary to PEP 8 (because
they are the same as the names used in wxWidgets) I should point out
that nowadays the name you import is "wx".

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
------------------ Asciimercial ---------------------
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.com squidoo.com/pythonology
tagged items: del.icio.us/steve.holden/python
All these services currently offer free registration!
-------------- Thank You for Reading ----------------

May 27 '07 #4
On May 26, 8:48 pm, Steve Howell <showel...@yahoo.comwrote:
>
I'm thinking you could actually have a progression
from a 1 line program up to a 50-line program. The
number 50 is kind of arbitrary, but my gut says that
by a 50-line program, you will have demonstrated
almost every useful concept.
If there is anything arbitrary here, I'd say it is your "increment
each example by one source line" constraint. This can force you to
use some bad coding practices to meet your target line count for a
given example.

Maybe try this approach: pick your top 10/20/50 language features and
develop concise examples. Then order the examples by length as a first
cut (longer examples probably *are* more complex), and then reorder a
bit to handle pre-requisites (introduce a minimum of new features,
preferably 1, per example). Overall, I'd have a tough time picking
just 10 language features to illustrate, but there are probably 10-20
basic features that will get new people onto fairly productive
ground. Pick 20 as your example count (50 sounds a bit long), and
stick to it, and then later add "20 More Little Programs" for the next
wave of examples in increasing complexity.

One other nit to pick: have your example classes inherit from object,
to get new people using new-style classes from the get-go.

-- Paul

May 27 '07 #5
Paul McGuire wrote:
I ***love*** this "10 Little Programs" idea! As soon as I get a
breathing space, I'm going to add a "10 Little Parsers" page to the
pyparsing wiki!

On May 26, 2:38 pm, Steven Bethard <steven.beth...@gmail.comwrote:
><nitpick>
Though the code should probably follow PEP 8 guidelines, e.g.
under_scores instead of camelCase for object and method names:

http://www.python.org/dev/peps/pep-0008/
</nitpick>

Really? Underscore-separated words preferred over camel case? What
is the rationale for this?
Rationale? It's a style guide. There is no rationale. ;-)
If we want to just say "well, PEP-8 says such and such," I think this
is an area where the thinking has possibly evolved since 2001.
I really don't think so. If anything, it's gotten more strict. PEP 8
used to allow either camelCase or under_scores. Now it only allows the
latter.
I guess pyparsing with its mixedCase functions and attributes is
doomed for the Dunce Corner. Too bad for BeautifulSoup, cElementTree,
and wxPython that are also at variance with this canon of Python
coding style.
Many (if not all) of these modules were written before the most recent
incarnation of PEP 8. Thus, they fall under the second good reason "to
break a particular rule":

(2) To be consistent with surrounding code that also breaks it

Of course, for new code, such as that in this thread, there's no reason
to break from the PEP 8 guidelines.
STeVe
May 27 '07 #6
Out of curiosity, how does this style jibe with the latest embracing
of Unicode identifiers? Ever tried to type an underscore on a non-US
keyboard? I have a heck of a time finding/typing the '_' character
when I visit our clients in Germany, but this may just be my own
personal Amerocentric issue (I also get messed up by the transposition
of Y and Z on German keyboards, but my German colleagues
understandably are not bothered by it). For someone already familiar
with that keyboard layout, is typing an underscore any more difficult
than my pressing Shift-_ on my US keyboard?

-- Paul

May 27 '07 #7
On May 26, 9:58 pm, Paul McGuire <p...@austin.rr.comwrote:
Out of curiosity, how does this style jibe with the latest embracing
of Unicode identifiers? Ever tried to type an underscore on a non-US
keyboard? I have a heck of a time finding/typing the '_' character
when I visit our clients in Germany, but this may just be my own
personal Amerocentric issue (I also get messed up by the transposition
of Y and Z on German keyboards, but my German colleagues
understandably are not bothered by it). For someone already familiar
with that keyboard layout, is typing an underscore any more difficult
than my pressing Shift-_ on my US keyboard?

-- Paul
Steve, sorry for going so far off-topic. I've started a new thread on
my questions about this aspect of PEP-8, and if there's more to say
about this, people should post it there.

-- Paul

May 27 '07 #8
On May 26, 1:43 pm, Steve Howell <showel...@yahoo.comwrote:
------
parentRabbits, babyRabbits = (1, 1)
while babyRabbits < 100:
print 'This generation has %d rabbits' %
babyRabbits
parentRabbits, babyRabbits = (babyRabbits,
parentRabbits + babyRabbits)

------
# def defines a method in Python
def tax(itemCharge, taxRate = 0.05):
return itemCharge * taxRate
print '%.2f' % tax(11.35)
print '%.2f' % tax(40.00, 0.08)
For the person new to programming (doesn't come from C or other
languages), I think you need to add a separate explanation of string
formatting and how it works, or at least add a comment that tells them
you are using string formatting so that they can search and find out
how it works. If your aim is to teach simple programming concepts, why
confuse them so early on with fancy interpolation?

Something like

# uses Python string formatting
# http://docs.python.org/lib/typesseq-strings.html

but really I think it will just be a distraction

rd
May 27 '07 #9
Steve Howell wrote:
I've always thought that the best way to introduce new
programmers to Python is to show them small code
examples.
<snip>

You could try this wiki page:

http://rosettacode.org/wiki/Main_Page

It has a fair amount of Python examples as well as many more other
languages (doing the same algorithm).

Hope this helps.

Adonis
May 27 '07 #10
>
You could try this wiki page:

http://rosettacode.org/wiki/Main_Page

It has a fair amount of Python examples as well as many more other
languages (doing the same algorithm).

Hope this helps.

Adonis

THIS IS GREAT :) Thanx!

May 28 '07 #11
Steve Howell wrote:
I've always thought that the best way to introduce new
programmers to Python is to show them small code
examples.
This is really a nice piece of missing Python.

Sorry I didn't follow this thread accurately,
but have you considered to produce an example environment like in wxPython ?

The wxPython demo program is written as an interactive tutorial,
with a few hundred examples, nicely ordered in groups.
The user can view the demo, the code and the help text.
The user can also change the code and see the results right away.

It would even be nicer, if everybody could drop her/his examples
in a standard way, so they would be automatically incorporated in
something like the wxPython interactive demo.

cheers,
Stef Mientki
May 28 '07 #12
In article <ma***************************************@python. org>,
Steve Howell <sh*******@yahoo.comwrote:
>I've always thought that the best way to introduce new
programmers to Python is to show them small code
examples.
Something like this:

http://www.lava.se/sam/

Jacob Hallén

--
Jun 8 '07 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

38
by: kbass | last post by:
In different articles that I have read, persons have constantly eluded to the productivity gains of Python. One person stated that Python's productivity gain was 5 to 10 times over Java in some in...
145
by: David MacQuigg | last post by:
Playing with Prothon today, I am fascinated by the idea of eliminating classes in Python. I'm trying to figure out what fundamental benefit there is to having classes. Is all this complexity...
7
by: Kamilche | last post by:
Man, I've been banging my head against a C program for a while now. I'm embarrassed to admit how long. I really want to use Python, as I mentioned in a prior post, but the speed hit is such that...
3
by: Nickolay | last post by:
it's easy to create small executable from python code, when using assembler compilers. I ask you if need it?
68
by: Lad | last post by:
Is anyone capable of providing Python advantages over PHP if there are any? Cheers, L.
2
by: Kenneth McDonald | last post by:
I'm not trying to persuade my company to offer Python as a scripting language for their product, but I am trying to give them examples of things that Python can do easily that cannot be done easily...
0
by: Fuzzyman | last post by:
It's finally happened, `Movable Python <http://www.voidspace.org.uk/python/movpy/>`_ is finally released. Versions for Python 2.3 & 2.4 are available from `The Movable Python Shop...
852
by: Mark Tarver | last post by:
How do you compare Python to Lisp? What specific advantages do you think that one has over the other? Note I'm not a Python person and I have no axes to grind here. This is just a question for...
17
by: Brian Blais | last post by:
Hello, I have a couple of classes where I teach introductory programming using Python. What I would love to have is for the students to go through a lot of very small programs, to learn the...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.