ZZucker 342 Practically a Master Poster

You can loop your input until the conditions are met:

while True:
    s = raw_input("Please enter an integer: ")
    try:
        n = int(s)
        if n > 0:
            break
        else:
            print "This is not an integer greater than 0"
    except ValueError:
        pass

print n  # test
ZZucker 342 Practically a Master Poster

The largest cucumber ever harvested weighed in at 8.4 kg.

Note:
Sorry, I was wrong with the full moon. The February months of 1866, 1885, 1915, 1934, 1961 did not have a full moon.

ZZucker 342 Practically a Master Poster

Oxymoron: Microsoft Works

ZZucker 342 Practically a Master Poster

The simplest way, but maybe not the most efficient for large files, is this:

# sample text for testing
# could come from a text file read like this:
"""
infile = open("my_text.txt","r")
text = infile.read()
infile.close()
"""

text = """\
My name is Fred Flintstone and I am a famous TV
star.  I have as much authority as the Pope, I
just don't have as many people who believe it.
"""

search = "Fred"
index = text.find(search)
print search, "found at index", index

"""
my ouput (index is zero based) -->
Fred found at index 11
"""

Note that find() only finds the first occurrence of the search word!

ZZucker 342 Practically a Master Poster

Another word frequency program, but this time we want ot create a dictionary of provider:frequency pairs from a number of given email addresses:

# count the frequency of providers from a number of given emails

emails = """\
manolis@gmail.com
giannis@gmail.com
kostas@yahoo.com
eirini@yahoo.com
ssss@aol.com
wertza@yahoo.gr
xristhanthi@gmail.com
"""

# split into list of lines (individual email)
lines = emails.split()

provider_freq = {}
for item in lines:
    # split each line item at the @ character
    user, provider = item.split('@')
    #print user, provider  # test
    # build the dictionary
    count = provider_freq.get(provider, 0)
    provider_freq[provider] = count + 1
    
print provider_freq

"""
my output -->
{'yahoo.com': 2, 'aol.com': 1, 'gmail.com': 3, 'yahoo.gr': 1}
"""
vegaseat commented: very nice code +8
ZZucker 342 Practically a Master Poster

The trick is to split your email data into a list of lines first, and the split each line into user, provider at the @ character. For example:

email = """\
manolis@gmail.com
giannis@gmail.com
kostas@yahoo.com
eirini@yahoo.com
ssss@aol.com
wertza@yahoo.gr
xristhanthi@gmail.com
"""

# split into list of lines
lines = email.split()

provider_freq = {}
for item in lines:
    # split each line item at the @ character
    user, provider = item.split('@')
    #print user, provider  # test
    # build the dictionary
    count = provider_freq.get(provider, 0)
    provider_freq[provider] = count + 1
    
print provider_freq

"""
my output -->
{'yahoo.com': 2, 'aol.com': 1, 'gmail.com': 3, 'yahoo.gr': 1}
"""
ZZucker 342 Practically a Master Poster

Just another word frequency program that shows you how to sort the output by frequency:

# count words in a text and show the first ten items
# by decreasing frequency using a list of tuples

# sample text for testing (could come from a text file)
text = """\
My name is Fred Flintstone and I am a famous TV
star.  I have as much authority as the Pope, I
just don't have as many people who believe it.
"""

word_freq = {}

word_list = text.split()

for word in word_list:
    # word all lower case
    word = word.lower()
    # strip any trailing period or comma
    word = word.rstrip('.,')
    # build the dictionary
    count = word_freq.get(word, 0)
    word_freq[word] = count + 1

# create a list of (freq, word) tuples for sorting by frequency
freq_list = [(freq, word) for word, freq in word_freq.items()]

# sort the list by the first element in each tuple (default)
freq_list.sort(reverse=True)

print "The ten most frequent words are:"
for n, tup in enumerate(freq_list):
    # print the first ten items
    if n < 10:
        freq, word = tup
        print freq, word

"""
my output -->
The ten most frequent words are:
3 i
3 as
2 have
1 who
1 tv
1 the
1 star
1 pope
1 people
1 name
"""
ZZucker 342 Practically a Master Poster

There are mistakes like your last line should be i = i + 1. Also string functions are builtin since version 2.2, module re is not needed.

Here is one way to do this with version 2.5

# count words in a text and show the first ten items
# by decreasing frequency

# sample text for testing
text = """\
My name is Fred Flintstone and I am a famous TV
star.  I have as much authority as the Pope, I
just don't have as many people who believe it.
"""

word_freq = {}

word_list = text.split()

for word in word_list:
    # word all lower case
    word = word.lower()
    # strip any trailing period or comma
    word = word.rstrip('.,')
    # build the dictionary
    count = word_freq.get(word, 0)
    word_freq[word] = count + 1

# create a list of (freq, word) tuples
freq_list = [(freq, word) for word, freq in word_freq.items()]

# sort the list by the first element in each tuple (default)
freq_list.sort(reverse=True)

for n, tup in enumerate(freq_list):
    # print the first ten items
    if n < 10:
        freq, word = tup
        print freq, word
        # or
        #print word, freq

"""
my output -->
3 i
3 as
2 have
1 who
1 tv
1 the
1 star
1 pope
1 people
1 name
"""
ZZucker 342 Practically a Master Poster

February 1865 is the only month in recorded history not to have a full moon.

ZZucker 342 Practically a Master Poster

I am a mix of Irish, Italian and French and have no choice but to call myself an American.

ZZucker 342 Practically a Master Poster

Chicken fettucini (alfredo sauce) with broccoli. Leftover from last night's dinner.

ZZucker 342 Practically a Master Poster

My brother has a model of plane #20 on his bedroom dresser. He tells me it's a Grumman Bearcat. Looks sure like it.

Is plane #21 a Lufthansa plane?

ZZucker 342 Practically a Master Poster

A typical American thought:

Barack Obama is 50% black and 50% white. The media and most whites consider him a black person. How much whiteness does it take to be considered a white person?

Oh yes, there are a few folks that consider him just a good person.

ZZucker 342 Practically a Master Poster

Looks like the Demo Convention could become quite a 'hate festival'. Good for McCain!

ZZucker 342 Practically a Master Poster

Lou Dobbs (CNN) gives me the bigot willies! However I like most of the other CNN crew.

ZZucker 342 Practically a Master Poster

I don't know much about planes, but is plane #12 a Phantom fighter jet?

ZZucker 342 Practically a Master Poster

Albert Einstein was born into a Jewish family in Ulm, Germany on March 14, 1879. Note that March 14 is somehow connected to 3.14 (pi), so Albert was born on pi-day.

ZZucker 342 Practically a Master Poster

Gee vegaseat, you must like old Albert!

There is hope for the math challenged:

Do not worry about your difficulties in Mathematics. I can assure you mine are still greater.
-- Albert Einstein

Ouch:

How can I believe in God, when just last week I got my tongue caught in the roller of an electric typewriter?
-- Woody Allen

ZZucker 342 Practically a Master Poster

What you did will work if you are in IDLE's Python Shell (in the editor click on run then Python Shell), it's the one with the >>> prompt. If you are in the IDLE editor (no >>> prompts) you need to save your code first like 'linux' said. Then use key F5 to run it.

The PythonShell is for simple tests. If you have to type several lines of code, it is better to use the editor and save the code as something like mytest2.py so you can modify it easily.

Editors like IDLE are nice for beginners, since they highlight your code and help with builtin functions. For instance type int( in the editor, and a suggestion what this function expects as arguments and will return pops up.

If you instal Python from the source files, you need MS C++ on windows during installation. I recommend that on Windows you install from the ready made binary .msi file.

ZZucker 342 Practically a Master Poster

write(s) expects a string, so use str(today) for s:

import datetime

test_time = open('test.time', 'w')
test_time.write('today is\n')
test_time.close()

test_time = open('test.time', 'a')
today = datetime.date.today()
print today, type(today)  # 2008-03-09 <type 'datetime.date'>

# convert <type 'datetime.date'> to a string first
# since write() expects a string
test_time.write(str(today))

test_time.close()

# test the file's contents
for line in file('test.time'):
    print line,
ZZucker 342 Practically a Master Poster

I understand that McCain has quite a foul mouth on him. All Hillary has to do is to egg him on and he will lose it!

ZZucker 342 Practically a Master Poster

My guess would be coral too!

ZZucker 342 Practically a Master Poster

A man is playing the piano one night in a downtown bar. In walks an elephant who goes over to the pianist, and suddenly starts to cry.

“There, there”, says the pianist “Do you recognise the song?”

“No, no,” says the elephant “I recognise the keys.”

ZZucker 342 Practically a Master Poster

Ah Linux, the quoted line(s) right after the function define is called the documentation string of the function.

Example:

# a look at the documentation strings for methods/functions
# commonly in triple quotes, but can use single quotes for one liners

import math

def getDistance(x1, y1, x2, y2):
  '''
  getDistance(x1, y1, x2, y2)
  returns distance between two points using the pythagorean theorem
  the function parameters are the coordinates of the two points
  '''
  dx = x2 - x1
  dy = y2 - y1
  return math.sqrt(dx**2 + dy**2)

print "Distance between point(1,3) and point(4,7) is", getDistance(1,3,4,7)
print "Distance between point(1,3) and point(11,19) is", getDistance(1,3,11,19)

print '-'*50

print "The function's documentation string:"
# shows comment between the triple quotes
print getDistance.__doc__
ZZucker 342 Practically a Master Poster

Here is an example how to output a formatted table from a loop:

# print a table (16 columns) of ASCII characters from 1 to 127

# Bumsfeld, thanks for the dictionary
controls_dic = {
1: 'SOH', 2: 'STX', 3: 'ETX', 4: 'EOT', 5: 'ENQ', 6: 'ACK', 7: 'BEL',
8: 'BS', 9: 'HT', 10: 'LF', 11: 'VT', 12: 'FF', 13: 'CR', 14: 'SO',
15: 'SI', 16: 'DLE', 17: 'DC1', 18: 'DC2', 19: 'DC3', 20: 'DC4', 21: 'NAK',
22: 'SYN', 23: 'ETB', 24: 'CAN', 25: 'EM', 26: 'SUB', 27: 'ESC', 28: 'FS',
29: 'GS', 30: 'RS', 31: 'US'}

n = 1
for k in range(1, 128):
    if k < 32:
        s = controls_dic[k]
    else:
        s = chr(k)
    if n % 16 > 0:
        print "%4s" % s,
    else:
        print "%4s" % s
    n += 1
ZZucker 342 Practically a Master Poster

Sorry woooee, I swallowed one number, here is the correct code:

# print 0 to 127 in a table of 16 columna

n = 1
for k in range(0, 128):
    #n += 1
    if n % 16 > 0:
        print "%4d" % k,
    else:
        print "%4d" % k
    n += 1

For the ASCII table thingy see:
http://www.daniweb.com/forums/showpost.php?p=552972&postcount=119

ZZucker 342 Practically a Master Poster

Sorry!

ZZucker 342 Practically a Master Poster

Here is one example:

# print 0 to 127 in a table of 16 columna

n = 1
for k in range(0, 128):
    if n % 17:
        print "%4d" % k,
    else:
        print
    n += 1
ZZucker 342 Practically a Master Poster

I found this word wrap function somewhere:

def wrap(text, width):
    """
    A word-wrap function that preserves existing line breaks
    and most spaces in the text. Expects that existing line
    breaks are linux style newlines (\n).
    """
    def func(line, word):
        nextword = word.split("\n", 1)[0]
        n = len(line) - line.rfind('\n') - 1 + len(nextword)
        if n >= width:
            sep = "\n"
        else:
            sep = " "
        return '%s%s%s' % (line, sep, word)
    text = text.split(" ")
    while len(text) > 1:
        text[0] = func(text.pop(0), text[0])
    return text[0]


# 2 very long lines separated by a blank line
msg = """Arthur:  "The Lady of the Lake, her arm clad in the purest \
shimmering samite, held aloft Excalibur from the bosom of the water, \
signifying by Divine Providence that I, Arthur, was to carry \
Excalibur. That is why I am your king!"

Smarty:  "Listen. Strange women lying in ponds distributing swords is \
no basis for a system of government. Supreme executive power derives \
from a mandate from the masses, not from some farcical aquatic \
ceremony!\""""

# example: make it fit in 40 columns
print wrap(msg,40)

# result is below
"""
Arthur:  "The Lady of the Lake, her arm
clad in the purest shimmering samite,
held aloft Excalibur from the bosom of
the water, signifying by Divine
Providence that I, Arthur, was to carry
Excalibur. That is why I am your king!"

Smarty:  "Listen. Strange women lying in
ponds distributing swords is no basis
for a system of government. …
ZZucker 342 Practically a Master Poster

Save some Trees
Eat a Beaver

ZZucker 342 Practically a Master Poster

Must be for older guys.

ZZucker 342 Practically a Master Poster

The terminator and the chipmunk are at the same intellectual level.

ZZucker 342 Practically a Master Poster

Thank heavens, there are the Italians.

ZZucker 342 Practically a Master Poster

Also, what came first, the chicken or the egg?

ZZucker 342 Practically a Master Poster

A tall Southern Comfort.

ZZucker 342 Practically a Master Poster

I hated going to weddings. It seemed that all of my aunts and other grandmotherly types used to come up to me, poking me in the ribs and telling me, "You're next."

They stopped doing that after I started doing the same thing to them at funerals.

ZZucker 342 Practically a Master Poster

Another quote from dear Albert:

Men marry women with the hope they will never change. Women marry men with the hope they will change. Invaribly they are both disappointed.
... Albert Einstein

ZZucker 342 Practically a Master Poster

A Wendy's chicken breast sandwich, easy on the sand.

ZZucker 342 Practically a Master Poster

Over eighty percent of people will yawn within twenty seconds of seeing another person yawn.

I just yawned reading this!

ZZucker 342 Practically a Master Poster

He is poor who does not feel content.
A Japanese proverb

ZZucker 342 Practically a Master Poster

Ballooning is fun and so is sailing.

ZZucker 342 Practically a Master Poster

Standing in the middle of the road is very dangerous; you get knocked down by the traffic from both sides.

You must be referring to John McCain!

ZZucker 342 Practically a Master Poster

A Georgia State Trooper pulls over a pickemup truck on I-75.

Trooper: "Got any ID?"
Driver: " 'Bout what? "

ZZucker 342 Practically a Master Poster

Intellectuals solve problems, geniuses prevent them.
Albert Einstein

ZZucker 342 Practically a Master Poster

Israeli army never went into Iraq

How would you know? They could have sent special op units.

ZZucker 342 Practically a Master Poster

The Israeli Army is the best Army in the world! If they would have been allowed to do the Iraq thing, they would have been in and out in five days.

ZZucker 342 Practically a Master Poster

A function to allow for a relatively secure input of dates:

# a more secure way to enter a date

import datetime as dt

def enter_date():
    """
    asks to enter year, month and day and returns
    date info as <type 'datetime.datetime'>
    """
    def extract_date(s):
        try:
            # month given as a decimal number
            date = dt.datetime.strptime(s, "%d %m %Y")
        except:
            try:
                # month given as a 3 letter abreviation
                date = dt.datetime.strptime(s, "%d %b %Y")
            except:
                return None
        return date

    while True:
        year = raw_input("Enter year (eg. 1979): ")
        # you can enter number of month, full name or 3 letter abbreviation
        month = raw_input("Enter month (eg. 9 or sep): ")
        day = raw_input("Enter the day of the month: ")
        date = extract_date(day + " " + month[:3].title() + " " + year)
        if date == None:
            print "Illegal info!"
            continue
        else:
            return date


date = enter_date()

# testing ...
#print date, type(date)           # 2001-09-11 00:00:00 <type 'datetime.datetime'>
#print date.strftime("%m/%d/%Y")  # 09/11/2001
#print date.strftime("%d%b%Y")    # 11Sep2001

# do something with it ...
today = dt.datetime.today()
age = today - date
# assumes week starts with Monday
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
week_day = weekdays[dt.date.weekday(date)]
print "Today is %s" % today.strftime("%d%b%Y")
print "%s was %d days ago on a %s" % (date.strftime("%d%b%Y"), age.days, week_day)

"""
my output -->
Enter year (eg. 1979): 2001
Enter month (eg. 9 or sep): september
Enter the day of the month: 11
Today is 03Mar2008
11Sep2001 was 2365 days ago on a …
ZZucker 342 Practically a Master Poster

Jeff, thanks for the idea. I was just working on a project that needed a secure date input. This what I came up with:

# a more secure way to enter a date

import datetime as dt

def enter_date():
    """
    asks to enter year, month and day and returns
    date info as <type 'datetime.datetime'>
    """
    def extract_date(s):
        try:
            # month given as a decimal number
            date = dt.datetime.strptime(s, "%d %m %Y")
        except:
            try:
                # month given as a 3 letter abreviation
                date = dt.datetime.strptime(s, "%d %b %Y")
            except:
                return None
        return date

    while True:
        year = raw_input("Enter year (eg. 1979): ")
        # you can enter number of month, full name or 3 letter abbreviation
        month = raw_input("Enter month (eg. 9 or sep): ")
        day = raw_input("Enter the day of the month: ")
        date = extract_date(day + " " + month[:3].title() + " " + year)
        if date == None:
            print "Illegal info!"
            continue
        else:
            return date


date = enter_date()

# testing ...
#print date, type(date)           # 2001-09-11 00:00:00 <type 'datetime.datetime'>
#print date.strftime("%m/%d/%Y")  # 09/11/2001
#print date.strftime("%d%b%Y")    # 11Sep2001

# do something with it ...
today = dt.datetime.today()
age = today - date
# assumes week starts with Monday
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
week_day = weekdays[dt.date.weekday(date)]
print "Today is %s" % today.strftime("%d%b%Y")
print "%s was %d days ago on a %s" % (date.strftime("%d%b%Y"), age.days, week_day)

"""
my output -->
Enter year (eg. 1979): 2001
Enter month (eg. 9 or sep): september
Enter the day of …
ZZucker 342 Practically a Master Poster

If you want to clear the whole canvas instance of all items on it, use:
canvas.delete('all')

vegaseat commented: you are getting good with Python +7
ZZucker 342 Practically a Master Poster

Really not that much different than C:

# while statement to add spaces to string until lenght == 70

def right_just(s):
    while len(s) < 70:
        s = " " + s
    return s

s = '1234567890'
# acts as ruler
print s * 7

print right_just(s)

"""
my result -->
1234567890123456789012345678901234567890123456789012345678901234567890
                                                            1234567890
"""