vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Let's say you want to create an English to French dictionary. You go to babelfish.altavista.com and enter "one, two, three, four, five, six, seven, eight, nine, ten" tell it to translate that from English to French and it gives you "un, deux, trois, quatre, cinq, six, sept, huit, neuf, dix". The easy way to make a dictionary from this after copy and paste ...

str1 = "one, two, three, four, five, six, seven, eight, nine, ten"
# after babelfish.altavista.com  English to French translation
str2 = "un, deux, trois, quatre, cinq, six, sept, huit, neuf, dix"

engList = str1.split(", ")
frenList = str2.split(", ")
eng2frenDict = {}
k = 0
for eng in engList:
    eng2frenDict[eng] = frenList[k]
    k += 1
    
print eng2frenDict
""" result =
{'seven': 'sept', 'ten': 'dix', 'nine': 'neuf', 'six': 'six', 'three': 'trois', 
'two': 'deux', 'four': 'quatre', 'five': 'cinq', 'eight': 'huit', 'one': 'un'}
"""

The same thing even shorter ...

str1 = "one, two, three, four, five, six, seven, eight, nine, ten"
str2 = "un, deux, trois, quatre, cinq, six, sept, huit, neuf, dix"

engList = str1.split(", ")
frenList = str2.split(", ")
eng2frenDict = dict(zip(engList, frenList))
print eng2frenDict
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

List comprehension is something Python borrowed from a language called Haskell. It returns a new list and is shorter and simply faster than the traditional loop/append alternative. Look at the two functions and you can get an idea how list comprehension works within the one-line [ ... ].

# the module profile is used to compare the two functions
 
import profile
 
def evenList1():
    """returns a list of even numbers from 0 to 99998 using append in a loop
    the 50000 calls to append() consume a lot of CPU time
    """
    L1 = []
    for x in range(100000):
        if x % 2 == 0:
            L1.append(x)
    return L1
 
def evenList2():
    """returns a list of even numbers from 0 to 99998 using list comprehension
    much faster in CPU time than the standard loop with append()
    """
    L2 = [ x for x in range(100000) if x % 2 == 0 ]
    return L2
 
 
# test first 30 elements
print( evenList1()[0:30] )
print( evenList2()[0:30] )
 
print
print( "Profile of evenList1(), check the time consumed by the many append() calls:" )
print( "(ignore time consumed by the profiler itself)\n" )
profile.run('evenList1()')
 
print( "Profile of evenList2():" )
print( "(ignore time consumed by the profiler itself)\n" )
profile.run('evenList2()')
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Python's lambda allows you to declare a one-line nameless minifunction on the fly. The format is:
lambda parameter(s): expression using the parameter(s)
It returns the result of the expression. The expression has to be a one-liner (no newlines)! Here is a little example ...

# a list of player (name, score) tuples
player_score = [('frank', 88), ('jerry', 68), ('albert', 99)]

# use lambda to sort by score
# (the item at index 1 in the tuple)
player_score.sort(key=lambda tup: tup[1], reverse=True)

print(player_score)  # [('albert', 99), ('frank', 88), ('jerry', 68)]
Lardmeister commented: good example +10
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Python's lambda allows you to declare a one-line nameless minifunction on the fly. The format is:
lambda parameter(s): expression using the parameter(s)
It returns the result of the expression. The expression has to be a one-liner (no newlines)! Here is a little example ...

# sort strings in a list, case insensitive
import string

wordList = ['Python', 'is', 'really', 'great', 'stuff']
print "Original list:"
print wordList

wordList.sort()
print "After standard sort (ASCII upper case is before lower case):"
print wordList

wordList.sort(lambda x, y: cmp(string.lower(x), string.lower(y)))
print "After case insensitve sort with lambda and lower:"
print wordList

I decided to put that also under "Starting Python".

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This project is similar to the "one word at a time" reader, except it functions like a flash card program. You display, let's say, a Spanish word for a certain amount of time and then the corresponding English word. What better to use than a Python dictionary? Then you can just read off the key followed by the value. This can be done as a simple console or a fancy shmenzy GUI program.

I hope the foreign characters display well. Otherwise you might have to stay with something more domestic.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Create a "one word at a time" text reader. Display the word in a large font for a certain amount of time. Set the font size so even grandma can read it. The time the word is displayed could be adjustable and might depend on the length of the word.

Sounds like a GUI program. If you have questions about setting font sizes, ask in the forum.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The game of chess was invented a few hundred years ago in India. The story has it, that the ruler of the area was so enchanted with the game, that he called the inventor to his palace, and asked him to name a gift.

The seemingly humble man asked the ruler to put a grain of rice on the first square of the chessboard, two grains of rice on the second and so on, doubling the grains each time until all 64 squares of the chessboard were filled.

The ruler was thinking about a full sack of rice and happily agreed. I didn't count it myself, but there are 32,000,000 grains of rice in a short ton (2,000 lbs). So do the calculation in Python and make a modern day comparison. Assume that a 50 foot rail car can carry 50 tons of rice.

How long would the train have be to carry the inventor's request?

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Writing a module and testing it ...

# save as  den2bin.py  and use  
# import den2bin  in any program that needs it
# call the function with something like  den2bin.denary2binary(76)
# (it's easiest to keep this file in the working folder)
 
def denary2binary(n):
    '''
    convert denary integer n (base 10) to binary string bStr (base 2)
    '''
    bStr = ''
    if n <= 0: 
        return '0'
    while n > 0:
        bStr = str(n % 2) + bStr
        n = n >> 1
    return bStr
 
# the test code below only runs when used as a standalone program
# let's say you save this module as den2bin.py 
# when you import den2bin  the __name__ namespace would now be  
# 'den2bin'  and not '__main__' and the module test will be ignored
if __name__ == '__main__':
    print( denary2binary(255) )          # 11111111
    # convert back to test it
    print( int(denary2binary(255), 2) )  # 255
    
    # with Python3 you can simply use builtin function bin()
    #print( bin(255), type(bin(255)) )  # 0b11111111 <class 'str'>
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Create a quiz game. Bring up a question and give four possible answers to pick from. Load the question and answers from a data file that also includes the code for the correct answer. Ask the questions in random order, and bring them up only once during the quiz. This can be a console program or dressed up in a GUI. Keep track of the correct answers given and evaluate the contestant at the end.

Attached is a typical data file. The lines are in the following order:
Correct answer's code letter
Question
Answer A
Answer B
Answer C
Answer D
...

The data file is a nice mix of questions with some humor thrown in. Double check the order, I might have goofed it up.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Create a Video Poker game. You can use PyGame, Tkinter or wxPython to bring up the cards.

Attached is a graphics file containing all the cards and a few decks.

mrboolf commented: I just chosen one random post to say thank you for this topic! I'm introducing myself to python and I appreciate very much all these stimulating exercises :) +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you have a computer running Windows XP, then you can let the computer read text to you. For more details look at the Python snippet at:
http://www.daniweb.com/code/snippet326.html

You may load in a textfile and have it read, or simply read the results of a program out loud. You could help elderly people with failing eyesight, just keep thinking about uses.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You just wrote a loop allowing the input of 20 names into a list. Alas, you made an error as you entered name number 17. Redesign your input loop, so you can correct the error easily without having to retype the previous 16 names.

e-papa commented: I try this +6
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Translate from one language to another. For instance from English to Texan.

Hint, one approach would be the one used in the Python code snippet at:
http://www.daniweb.com/code/snippet395.html

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

How would you write a simple spell checker for a text file?

Start simple and test your code. Attached is full English spelling dictionary file, one word on a line.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The question came up in the forum how to represent an integer as a hexadecimal. There were two obvious ways to do this, the hex() function and the format operator %X. The resulting strings 0xac23b and AC23B look different. If you have to display the result, AC23B might be your choice. Otherwise speed might be important, particularly, if you call the function a lot. Here is a way to measure speed ...

# two different ways to represent integer 705083 as a hexadecimal 
# number, 0x is the official prefix for a hexnumber
# the results appear different, but both are of type string 
# and change back to base 10 properly
 
# using the hex() function
hex1 = hex(705083)
print( hex1, type(hex1), int(hex1,16) )  
 
# using the format operator %
hex2 = "%X" % 705083
print( hex2, type(hex2), int(hex2, 16) )  
 
# let's time the two options ...
 
import timeit

print( "Timing study ..." )
 
t = timeit.Timer('hex(705083)')
elapsed = (10 * t.timeit(number=100000))
print( 'hex(705083) takes %0.3f microseconds/pass' % elapsed )
 
t = timeit.Timer('"%X" % 705083')
elapsed = (10 * t.timeit(number=100000))
print( 'Format operator takes %0.3f microseconds/pass' % elapsed )

"""my output (Python 3.1) -->
0xac23b <class 'str'> 705083
AC23B <class 'str'> 705083
Timing study ...
hex(705083) takes 0.591 microseconds/pass
Format operator takes 0.048 microseconds/pass
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Make a physics problem solver. Sometimes called an equation solver.

Let's say you have a simple kinematics question:
Bertha jogs at an average 7 miles/hour, and her typical path is 2.5 miles long. How long will it take her.

You would let the user enter three items:
1. 7 miles/hour
2. 2.5 miles
3. ? hours
Your program should figure out the formula and fill the question mark.

A more advanced version would convert units and standardize them. So the user can enter:
1. 7 miles/hour
2. 17 minutes
3. ? feet

Once you get the hang of it, you can go from simple kinematics to dynamics, force, work, gravitation, magnetic flux, thermodynamics, quantum mechanics or to relativity.

Back in the dark ages when I took physics, I wrote one of these in a then brand-new language called C.

lukasvoz commented: Do you think you might still have the source code? +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Computer art can be fun. PyGame might be the way to go here. Start out by drawing geometric designs using circles, ovals, lines, rectangles, lots of colors, put them in a loop that changes location, dimensions and colors.

To get an idea, look at the Python snippet at:
http://www.daniweb.com/code/snippet384.html
You need to be able to freeze the graphics and save it as an image file.

HiHe commented: I like that one +5
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Why not a story teller? This is for the people that like writing stories. Ask the reader for a preference and the story starts in that direction. After a while ask for another preference and branch off along that preference.

The story evolves as directed by the reader. Great for adventure, mystery, romance and detective stories. Try it out on a short and simple story first. Who knows, it could be the next bestseller.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Construct a sentence generator. Write down a bunch of sentences. Now pick them apart into lists of nouns, verbs, adverbs, adjectives and so forth. Use these pieces and create new sentences more or less at random. Some of those will be silly, some utter nonsense, but some could be the start of poetry or a novel.

Just to get you started, here is a very simple sentence generator, that takes the three parts (subject, action, object) of a standard sentence, shuffles these parts and reassembles the sentence ...

# goofy sentence generator
 
import random
 
def make_sentence(part1, part2, part3, n=1):
    """return n random sentences"""
    # convert to lists
    p1 = part1.split('\n')
    p2 = part2.split('\n')
    p3 = part3.split('\n')
    # shuffle the lists
    random.shuffle(p1)
    random.shuffle(p2)
    random.shuffle(p3)
    # concatinate the sentences
    sentence = []
    for k in range(n):
        try:
            s = p1[k] + ' ' + p2[k] + ' ' + p3[k]
            s = s.capitalize() + '.'
            sentence.append(s)
        except IndexError:
            break
    return sentence
 
# break a typical sentence into 3 parts
# first part of a sentence (subject)
part1 = """\
a drunken sailor
a giggling goose
the yearning youth
the obese ostrich
this mean mouse
the skinny sister"""
 
# middle part of a sentence (action)
part2 = """\
jumps over
flies over
runs across
openly ogles
twice tastes
vomits on"""
 
# ending part of a sentence (object)
part3 = """\
a rusty fence
the laughing cow
the weedcovered backyard
the timid trucker
the rancid old cheese
the jolly jelly"""
 
print '-'*60 …
EnergeticJet commented: I just get invalid syntax? +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A units of measurement converter. Think about all the things that are measured, like distance, area, volume, energy, weight, temperature, pressure and so on. Now think about the many units of measurement the people around the globe use, anything from rods, stones, pounds, inches, pints and liters. A rather long list.

Start simple, let's say just the distances and a few units. Get that to work, then add more. Google the net for conversion factors. How would you handle the information? Maybe a dictionary in Python. Are there any neat shortcuts?

Your program should answer questions like:
"How many inches in a meter?"
"How many milliliters in a pint?"
"How many acres in a square-mile?"
"How many pounds in a metric ton?"
"How many calories in a BTU?"

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Start a code library. As time goes on you will collect code snippets, hints and tricks from all over the net. So why not use Python to store these cut and pasted pieces of code in a file.

Attach a title and a set of keywords to each snippet that allows you to search the file and retrieve the code easily. You might want to use just one file and keep appending, so you have to find a way to keep the snippets appart from each other within the file. I have done it with a list where the items were separated by a dotcode-marker, works well, but it may not be a good way.

You can search the file directly or load the file into a list to speed things up. I leave it up to you. Keep thinking!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

After you got the basics of Python under your belt, the best way to get a good knowledge of the language and improve your coding skills is to start on a project you are interested in. Maybe an image viewer, a slide show, computer generated random or fractal art, a database for your baseball cards, a story writer, ...

This sticky is dedicated to a list of just such projects.

If you know a good project, please post it here. If you have questions, start your own thread and don't clutter the sticky. Please do not post your answeres in here!

There is also a thread Advanced and Intermediate Projects , see:
http://www.daniweb.com/forums/thread257510.html

Editor's note:
Some of the earlier examples are written for Python2 and may contain print statements like
print 'hello'
For Python3 this has to be changed to
print('hello')

DerKleineDude commented: The beginner's tutorials are a big help. The posts are aways well written and easy to understand. +1
Ene Uran commented: nice idea +8
tushg commented: Great Work :) Vegaseat :) Could you please Help me My Python Pyramid is Not working http://www.daniweb.com/software-development/python/threads/438405/running-the-project-application-in-pyramid-python-is-not-working# +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Try this code, I think it's the one I posted on the "Starting Python" sticky here.

# if you are on the internet you can access the HTML code of a 
# given web site
# using the urlopen() method/function from the module urllib2

import urllib2

urlStr = 'http://www.python.org/'
try:
  fileHandle = urllib2.urlopen(urlStr)
  str1 = fileHandle.read()
  fileHandle.close()
  print '-'*50
  print 'HTML code of URL =', urlStr
  print '-'*50
except IOError:
  print 'Cannot open URL %s for reading' % urlStr
  str1 = 'error!'
  
print str1

First try to use it as is, then you can change the URL and give it another try. I know this one works and is tested with Python24 and a normal dialup connection.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Now you got me started, for swapping either integers or floats this will work too ...

#include <iostream>

using namespace std;

int main()
{
    int a = 1;
    int b = 7;
    
    cout << "a = " << a << "   b = " << b << endl; 
    // swap a with b
    a = a + b;
    b = a - b;
    a = a - b;
    
    cout << "a = " << a << "   b = " << b << endl; 
    
    cin.get();   // wait
    return EXIT_SUCCESS;
}

Edit: Just an interrogative alternate, this swap is actually about five times slower then the usual temp variable swap.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A look at a simple Python class example for the OOP beginner ...

# looking at a simple Python class
# a class combines a number of methods/functions that belong together
 
class Box(object):
    """
    class names by convention are capitalized, (object) is 
    a basic class inheritance signifying the new style class
    """
    def __init__(self, depth, height, width):
        """__init__() is called first (acts as Constructor)
        brings in data from outside the class and makes it
        usable within the class via the instance object self.
        Look at self as the data carrier within the class.
        """
        self.depth = depth
        self.height = height
        self.width = width
 
    def volume(self):
        """class methods have self as first argument"""
        return self.height * self.width * self.depth
 
    def surface(self):
        return 2*self.height*self.width + 2*self.height*self.depth + 2*self.width*self.depth
 
# construct an instance of a 10x10x10 box and reference it with box1
box1 = Box(10, 10 ,10)
print( "A 10x10x10 box has a volume of", box1.volume() )
print( "and a surface area of", box1.surface() )
 
print('')  # empty line in Python3 and Python2
 
print( "Let's change the depth to 5" )
# construct an instance of a 5x10x10 box and reference it with box2
box2 = Box(5, 10 ,10)
print( "A 5x10x10 box has a volume of", box2.volume() )
print( "and a surface area of", box2.surface() )
 
print('')
 
print( "Optional tests for the inquisitive folks:" )
print( "box1 =", box1 )
print( "box2 =", box2 )
print( "The depth of box2 is", box2.depth )
 
print('')
 
# Can we set the box dimensions …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This shows you how to mimic a C struct type with an empty Python class ...

# create a structure similar to C struct using an empty class
 
class Employee(object):
    pass
 
 
john = Employee() # Create empty employee record/struct
ted = Employee()
mark = Employee()
 
# fill the fields of the record/struct
john.name = 'John Johnson'
john.dept = 'computer lab'
john.salary = 3000
 
ted.name = 'Ted Tetris'
ted.dept = 'human resources'
ted.salary = 5000
 
mark.name = 'Mark Marksman'
mark.dept = 'shipping area'
mark.salary = 3200
 
# this works like a struct or record
print( "%s works in the %s and earns $%s/month" % \
    (john.name, john.dept, john.salary) )
 
print('-'*60)
 
# or use a list of Employee() instances ...
empList = [john, ted, mark]
for emp in empList:
    print( "%s works in the %s and earns $%s/month" % \
        (emp.name, emp.dept, emp.salary) )

"""my output -->
John Johnson works in the computer lab and earns $3000/month
------------------------------------------------------------
John Johnson works in the computer lab and earns $3000/month
Ted Tetris works in the human resources and earns $5000/month
Mark Marksman works in the shipping area and earns $3200/month
"""

Click on "Toggle Plain Text" so you can highlight and copy the code to your editor without the line numbers.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Since Python does not need type declarations, I wanted to test the numeric capacity for integers with a program that calculates factorials since they quickly give very large numbers. I stopped at the factorial of 69 only because the line started wrapping.

# check the numeric range of Python with huge factorials
# factorial(69) still checks out accurately! Has 98 digits in it!
# 171122452428141311372468338881272839092270544893520369393648040923257279754140647424000000000000000

def fact(n):
    """recursive function, returns the factorial of n"""
    if n == 0:
        return 1
    else:
        k = n * fact(n-1)
        return k

for k in range(1, 70):
    # use % string formatting, works with Python2 and Python3
    sf = "factorial of %d = %d" % (k, fact(k))
    print( sf )

This boggles my mind since it took all sorts of hoops to try this with C++ earlier in my life. In C++ the unsigned long integer fizzles out at a measly 4.3 billion. Those are only ten digits!

Here is another little number trick I picked up from one of the forums. This poor fellow wanted to do it in C, but the old compiler just couldn't handle the number of digits in the result. No sweat for Python ...

# another little number trick ...

a = 111111111   # that's nine ones

print( "%d * %d = %d" % (a, a, a * a) )

"""my result -->
111111111 * 111111111 = 12345678987654321
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I don't have a Linux Box, but if there is a program that plays wave files you could call it with system(). Something like

system("WavePlayer cat.wav")
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

In a recent thread we looked at ways to create a multiline string. Here are a few code samples showing you how to do this, some are preference, some are cosmetic ...

# a look at multiline strings
 
# using line continuation (\) to form one long/multiline string
# complex and tough to read
# (no space right after \ or an empty line following \)
str1 = "The alien gasps and says, 'Oh, this is it.  I will die! \n\
Tell my 2.4 million larvae that I loved them... \n\
Good-bye, cruel universe.' "
 
 
# using line continuation (\) to combine three strings to one string
# ignores indentations between strings, easy on the eye
str2 = "The alien gasps and says, 'Oh, this is it.  I will die! \n"\
       "Tell my 2.4 million larvae that I loved them... \n"\
       "Good-bye, cruel universe.'"
 
 
# using just triple quotes, still tough to read?
# note: newline characters are taken care of
str3 = """The alien gasps, 'Oh, this is it.  I will die!
Tell my 2.4 million larvae that I loved them...
Good-bye, cruel universe.' """
 
 
# using triple quotes and line continuation (\)
# the text lines up properly and 
# IMHO the easiest to write and read
str4 = """\
The alien gasps and says, 'Oh, this is it.  I will die!
Tell my 2.4 million larvae that I loved them...
Good-bye, cruel universe.' """
 
 
# note: indentations become part of the string
str5 = """The alien …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A short code example of case sensitive and case insensitive string sorts ...

# sorting a list of strings

s = "I dearly love Monty Python's Flying Circus"
word_list = []
word_list = s.split()
print("The original list of words:")
print(word_list)

# make a shallow copy since sort() is inplace
word_list1 = list(word_list)

print("\nSort this list (the default sort is case sensitive):")
word_list1.sort()
print(word_list1)

word_list2 = list(word_list)
# use keword key to do a case insensitive sort
# applies lower() to every string item in the list during compare
print("\nHere is a sort that is case insensitive:")
word_list2.sort(key=str.lower)
print(word_list2)

"""my output -->
The original list of words:
['I', 'dearly', 'love', 'Monty', "Python's", 'Flying', 'Circus']

Sort this list (the default sort is case sensitive):
['Circus', 'Flying', 'I', 'Monty', "Python's", 'dearly', 'love']

Here is a sort that is case insensitive:
['Circus', 'dearly', 'Flying', 'I', 'love', 'Monty', "Python's"]
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just simple code to construct a toggle button, in this case we are using the venerable Tkinter for the GUI implementation.

# make a toggle button with Tkinter
 
try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk
 
toggleFlag = True
 
def entryColor():
    """toggle the entry color between white and red"""
    global toggleFlag
    if toggleFlag:
        e1.config(bg='red')
        toggleFlag = False
    else:
        e1.config(bg='white')
        toggleFlag = True
 
# create the root window
root = tk.Tk()
# create a button, command runs the given function 
# when button is clicked
b1 = tk.Button(root, text="Toggle Color", command=entryColor)
# pack button into root window
b1.pack(fill=tk.BOTH, expand=1)
# create an entry box to color
e1 = tk.Entry(root)
e1.pack(fill=tk.BOTH, expand=1)
 
# start the event loop
root.mainloop()

Click on "Toggle Plain Text" so you can highlight and copy the code to your editor.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Another recent thread was the impetus for this hint.

As you run the Python interpreter on a Python text code file (.py), the file is internally compiled to a .pyc byte code file that speeds up the interpretation process. Most of the time this is transparent to you, as the byte code file for speed sake is created in memory only.

If a Python text code .py file is imported by another Python file, a corresponding .pyc is created on disk to speed up the reuse of that particular file. Using .pyc files speeds things up saving the compilation step.

There is an additional benefit, the compiled files are not readable with a text editor. You can distribute your .pyc file instead of the .py file, this way you can hide your source code a little from folks who like to fiddle with source code.

Let's say you have a file called MyPyFile.py and want to create the compiled file MyPyFile.pyc for higher speed and/or the prevention of unauthorized changes. Write a little one line program like this:

import MyPyFile # converts MyPyFile.py to MyPyFile.pyc

Save it as CompileMyPyFile.py in the same folder as MyPyFile.py and run it. There now should be a MyPyFile.pyc file in that folder. Python.exe runs the source file or the compiled file.

Here is another way to create the compiled file ...

# create a byte code compiled python file
 
import py_compile …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Strings are immutable, which means you cannot directly change an existing string, bummer! The following code would give you an error ...

str1 = 'Hello World!'
str1[0] = "J"  # gives TypeError: object does not support item assignment

Where there is a will, there is a way around this obstacle ...

str1 = 'Hello World!'
# these statements give the intended result, since they create a new string
# slicing and concatination
str2 = 'J' + str1[1:]
# using replace()
str3 = str1.replace('H', 'J')
# or change the string to a list of characters, do the operation, and join the 
# changed list back to a string
charList = list(str1)
charList[0] = 'J'
str4 = "".join(charList)
 
print( str1 )
print( str2 )
print( str3 )
print( str4 )

Along the last thought, lets have some word fun ...

# just a little word fun ...
import random
str1 = "Mississippi"
charList = list(str1)
random.shuffle(charList)
str2 = "".join(charList)
print( "\nString '%s' after random shuffle = '%s'" % (str1, str2) )

The last code example could be the start of a "guess the word" game.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Tuples are handy for transferring multiple data, for instance to and from a function. They are easy to construct and transfer and assign their data easily. Check the multiReturn() example in the "Starting Python" sticky to see what I mean.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I took this from a recent thread, to show you how you can use a temporary print statement to figure out what is going on ...

# create a jumbled word/string
# tested with Python 2.5.4
 
import random 
 
# create a sequence, here a tuple, of words to choose from 
WORDS = ("python", "jumble", "easy", "difficult", "answer", "babysitter") 
 
# pick one word randomly from the sequence 
word = random.choice(WORDS) 
 
# create a variable to use later to see if the guess is correct 
correct = word 
 
# create a jumbled version of the word
# start with an empty string to be built up in the while loop
jumble = ""
# word is reduced in size by one character each time through the loop
# when it is empty it will be equal to None(False) and the loop stops
while word:
    print( word, '  ', jumble )   # for test only
    position = random.randrange(len(word)) 
    jumble += word[position] 
    word = word[:position] + word[(position + 1):]
 
 
print( jumble  )  # now you can ask to guess the word ...

Just a little note, when you save this code, don't save it as random.py. Python will confuse this in the import statement! It will look for the module random.py in the working directory first, before it goes the \Lib directory where the proper module is located.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This little fun with numbers program shows how range() and the for loop work together. A little trick I learned in fourth grade applied to Python.

# call it "all the same"
 
num1 = 12345679 # the 8 is left out!
 
# k goes from 9 to <82 in steps of 9
for k in range(9, 82, 9):
    print( num1 * k )

Here is another one ...

print("Bo Derek getting older:")
for k in range(10, 0, -1):
    print(k)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Do you want to impress your friends? Of course you do! Try this Python code example using the datetime module ...

# how many days old is this person?
 
from datetime import date
 
# a typical birthday  year, month, day
# or change it to your own birthday...
birthday = date(1983, 12, 31)
 
now = date.today()
 
print( '-'*30 )  # 30 dashes
print( "Today's date is", now.strftime("%d%b%Y") )
print( "Your birthday was on", birthday.strftime("%d%b%Y") )
 
# calculate your age
age = now - birthday
print( "You are", age.days, "days old" )

The datetime module is smart enough to catch erroneous dates like date(1983, 12, 32) or date(1983, 2, 29).

Notice the variation of the import statement. Here we are just importing the date method from the datetime module. This saves you from having to code:
now = datetime.date.today()
Might be good for long code where you would have to write this twenty times.

Here is another practical code ...

# calculate days till xmas
 
from datetime import date
 
now = date.today()
 
# you may need to change the year later
xmas = date(2005, 12, 25)
 
tillXmas = xmas - now
 
print( '-'*30 )  # 30 dashes
print( "There are", tillXmas.days, "shopping days till xmas!" )

Calculations like this can lead to a lot of headscratching, Python does it for you without a scratch ...

# add days to a given date
 
from datetime import date, timedelta
 
now = date.today()
 
delta = timedelta(days=77)
 
addDays …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Instead of reading a file, you can read the HTML code of a web site. Of course, you have to be connected to the internet to do this ...

# if you are on the internet you can access the HTML code of a given web site
# using the urlopen() method/function from the module urllib2
# tested with Python 2.5.4
 
import urllib2
 
urlStr = 'http://www.python.org/'
try:
    fileHandle = urllib2.urlopen(urlStr)
    str1 = fileHandle.read()
    fileHandle.close()
    print '-'*50
    print 'HTML code of URL =', urlStr
    print '-'*50
except IOError:
    print 'Cannot open URL %s for reading' % urlStr
    str1 = 'error!'
 
print str1

Notice that we have added the try/except exception handling to this code.

Note: Python3 uses urllib.request.urlopen() instead of urllib2.urlopen()
If you use Python3, try this code ...

# get html code of given URL
# Python3 uses urllib.request.urlopen()
# instead of Python2's urllib.urlopen() or urllib2.urlopen()
# also urllib is a package in Python3 
# tested with Python 3.1

import urllib.request

fp = urllib.request.urlopen("http://www.python.org")
# Python3 does not read the html code as string
# but as html code bytearray
mybytes = fp.read()
fp.close()

# try utf8 to decode the bytearray to a string
mystr = mybytes.decode("utf8")
print(mystr)

If you are the curious type and want to know beforehand whether you are connected to the internet, this code might tell you ...

# are we connected to the internet?
# tested with Python 2.5.4
 
import os
 
def isSSL():
    """ return true …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Use readlines() to get a list of lines ...

# read a text file as a list of lines
# find the last line, change to a file you have
fileHandle = open ( 'test3.txt',"r" )
lineList = fileHandle.readlines()
fileHandle.close()
print lineList
print "The last line is:"
print lineList[len(lineList)-1]
# or simply
print lineList[-1]
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

We have used the replace() function before. This time we use it in a for loop to create new words. The example also gives us a look at the if conditional statement ...

# make your own words, when Q comes up we want to use Qu
str1 = 'Aark'
print( "Replace A in %s with other letters:" % str1 )
# go from B to Z
for n in range(66, 91):
    ch = chr(n)
    if ch == 'Q':      # special case Q, use Qu
        ch = ch + 'u'
    print( str1.replace('A', ch) )

A variation of the above to show off the if/else statement ...

# make your own words, here we have to avoid one
# word to get past the guardians of the nation's morals
str1 = 'Auck'
print( "Replace A in %s with other letters:" % str1 )
# go from B to Z
for n in range(66, 91):
    ch = chr(n)
    if ch == 'Q':      # special case Q, use Qu
        ch = ch + 'u'
    if ch == 'F':      # skip the F word
        continue
    else:
        print( str1.replace('A', ch) )

These little code samples are fun to experiment with.

A note for the C programmers, Python treats characters as strings. This makes life a lot simpler!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Since we are on the subject of modules that come with Python, there is the operating system module called simply os. Here is one thing you can use it for ...

# list all the configuration (.ini) files in C:\Windows
 
import os
 
fileList = []  # start with an empty list
for filename in os.listdir("C:/Windows"):
    if filename.endswith(".ini"):
        fileList.append(filename)
 
# now show the list
for filename in fileList:
    print( filename )

There are lots of things you can do with this module. I guess you just have to type help('os') in the interactive window (the one with the >>> prompt) .

You Mac folks will have to change the folder/directory name and the extension.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The Python module calendar is another interesting collection of functions (methods). If you ever need to show all 12 monthly calendars for the year, use this code ...

# print out a given year's monthly calendars
 
import calendar
 
calendar.prcal(2005)

If you just want June 2005 use ...

import calendar
 
calendar.prmonth(2005, 6)
 
"""
result -->
     June 2005
Mo Tu We Th Fr Sa Su
       1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
"""

Just for fun, ask a C++ programmer to do this in two lines of code. Now you know why Python is considered a high level language.

Here is a somewhat more complete program, asking the user for the year ...

# allowing for user input
 
import calendar
 
print( "Show a given year's monthly calendars ..." )
print('')
# Python3 uses input() instead of raw_input()
year = int(raw_input("Enter the year (eg. 2005): "))
print('')
calendar.prcal(year)
print('')
raw_input("Press Enter to go on ...")  # wait
# with Pytho3 use ...
#input("Press Enter to go on ...")  # wait

Note, print('') prints an empty line in Python2 and Python3.
Since I have Dev-C++ on my computer I tricked it into using Python and do the calendar thing.

// needs the Python-2.4.1.DevPak installed into Dev-C++, download from:
// http://prdownloads.sourceforge.net/devpaks/Python-2.4.1.DevPak?download
// create project with File > New > Project... > Scripting > Python …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The Python module pickle allows you to save objects to file as a byte stream that contains the object information. When you load the file back the object is intact. Here is a little code example ...

# use binary file modes "wb" and "rb" to make pickle 
# work properly with both Python2 and Python3

import pickle
 
myList1 = [1, 2, 03, 04, 3.14, "Monty"]
print( "Original list:" )
print( myList1 )
 
# save the list object to file
file = open("list1.dat", "wb")
pickle.dump(myList1, file)
file.close()
 
# load the file back into a list 
file = open("list1.dat", "rb")
myList2 = pickle.load(file)
file.close()
 
# show that the list is still intact
print( "List after pickle.dump() and pickle.load():" )
print( myList2 )

The same procedure applies to other objects like variables, tuples, sets, dictionaries and so on.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I need to write a function that can return more than one item. This is a simple example how to do it ...

# use a tuple to return multiple items from a function
# a tuple is a set of values separated by commas
def multiReturn():
    return 3.14, "frivolous lawsuits", "Good 'N' Plenty"
 
# show the returned tuple
# notice that it is enclosed in ()
print( multiReturn() )
 
# load to a tuple of variables
num, str1, str2 = multiReturn()
print( num )
print( str1 )
print( str2 )
 
# or pick just the element at index 1, should be same as str1
# tuples start at index zero just like lists etc.
print( multiReturn()[1] )

This example has not only a multiple argument return, but also allows you to call it with multiple arguments of flexible size/number ...

# explore the argument tuple designated by *args
# used for cases where you don't know the number of arguments
def sum_average(*args):
    size = len(args)
    sum1 = sum(args)
    average = sum1/float(size)
    # return a tuple of three arguments
    # args is the tuple we passed to the function
    return args, sum1, average
 
# notice that the first element is the args tuple we send to the function
print( sum_average(2, 5, 6, 7) )  # ((2, 5, 6, 7), 20, 5.0)
 
# or unpack into a tuple of appropriate variables
args_tuple, sum2, average = sum_average(2, 5, 6, 7)
 
print( "sum of %s = %d" % (args_tuple, sum2) ) …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The correct answer is from
http://www.daniweb.com/techtalkforums/thread20774.html

# raw_input() reads every input as a string
# then it's up to you to process the string
str1 = raw_input("Enter anything:")
print "raw_input =", str1

# input() actually uses raw_input() and then tries to
# convert the input data to a number using eval()
# hence you could enter a math expression
# gives an error if input is not numeric eg. $34.95
x = input("Enter a number:")
print "input =", x
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

To get string input from the user you can use the raw_input() function with Python2 and the input() function with Python3. .

Here is an example of an input loop that checks the data you enter. The function get_list(prompt) is generic and can be used whenever you want to enter a series of numbers (accepts integer or float). It returns a list of the entered numbers. It's up to you to process the list of numbers ...

print( "The grade point average (GPA) calculator:" )
 
def get_list(prompt):
    """
    loops until acceptable data or q (quit) is given
    returns a list of the entered data
    """
    data_list = []
    while True:
        sin = raw_input(prompt)  # input(prompt) in Python3
        if sin == 'q':
            return data_list
        try:
            data = float(sin)
            data_list.append(data)
        except ValueError:
            print( "Enter numeric data!" )
 
print('')
gp_list = get_list("Enter grade point (q to quit): ")
print( gp_list )  # test
# process the list ... 
# calculate the average (sum of items divided by total items)
gpa = sum(gp_list)/len(gp_list)
 
print( "The grade point average is:", gpa )

Since Python2's raw_input() will not work with Python3, you can use try/except to make your program work with both versions ...

# use module datetime to show age in days
# modified to work with Python2 and Python3

import datetime as dt

prompt = "Enter your birthday (format = mm/dd/yyyy): "
try:
    # Python2
    bd = raw_input(prompt)
except NameError:
    # Python3
    bd = input(prompt)

# split the bd string into …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The IDLE integrated development environment that comes with the normal Python installation is really a GUI program. It uses Tkinter as the GUI toolkit which is part of the normal Python installation. Tkinter uses tcl script language to do the work.

Here is a typical Python code example using Tkinter ...

# explore the Tkinter GUI toolkit

try:
    # for Python2
    import Tkinter as tk
except ImportError:
    # for Python3
    import tkinter as tk

# create a window frame 
frame1 = tk.Tk() 
# create a label 
label1 = tk.Label(frame1, text="Hello, world!") 
# pack the label into the window frame
label1.pack() 
 
frame1.mainloop()  # run the event-loop/program

This code should run on Windows and Unix (PC or Mac). On a Windows machine save the program with a .pyw extension. This way it associates with pythonw.exe and avoids the ugly black DOS display popping up.

You can also find much Tkinter detail at:
http://infohost.nmt.edu/tcc/help/pubs/tkinter/index.html

There is another GUI library worth mentioning, it's wxPython based on C++. The code is more efficient for GUI stuff. The download of the installer is free, look at http://wiki.wxpython.org/

You can get wxPython for either Windows, Linux or Unix. You can find quite a few wxPython GUI code examples in the DaniWeb Python Code Snippets and in the Starting wxPython sticky. Here is a very nice wxPython tutorial I like to recommend, it will give you a good overview:
http://wiki.wxpython.org/index.cgi/AnotherTutorial

Note: GUI stands for Graphical User …

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

One more function sample to show you that a function can decide internally what type of number to return. Also shows an example of try/except exception handling.

# a function to return the numeric content of a cost item
# for instance $12.99 or -$123456789.01 (deficit spenders)
def getVal(txt):
  if txt[0] == "$":    # remove leading dollar sign
    txt = txt[1:]
  if txt[1] == "$":    # could be -$xxx
    txt = txt[0] + txt[2:]
 
  while txt:           # select float or integer return
    try:
      f = float(txt)
      i = int(f)
      if f == i:
        return i
      return f
    except TypeError:  # removes possible trailing stuff  
        txt = txt[:-1]
  return 0
 
# test the function ...
print( getVal('-$123.45') )

Click on "Toggle Plain Text" so you can highlight and copy the code to your editor without the line numbers.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

One more helpful hint to get this thing off to a hopefully good start. How do we read a simple text file in Python? Also, what can we do with the data after we read it?

# read a text file to a string and create a list of words

# use any text file you have ...
textf = open('xmas.txt', 'r')
str1 = textf.read()
textf.close()

print( "The text file as one string:" )
print( str1 )

# splits at the usual whitespaces
wordlist = str1.split(None)
print( "\nThe string as a list of words:" )
print( wordlist )
  
print( "\nThere are %d words in the list." % len(wordlist) )

Want more help about split()? At the interactive page >>> prompt enter
help("string.split")

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Python has a very helpful feature called help(). Here is a sample ...

# list all the modules Python currently knows about ...
help("modules")
 
# now pick a module from that list you want to know
# more about ...
 
# to get help about module calendar ...
help("calendar")
 
# dito for the math module
help("math")
 
# file stuff ...
help("file")
 
# down to method/function level ...
help("os.read")

That means you can use help in the program code, or at the interactive page >>> prompt. Not many other languages offer this handiness! To copy the help result into a help file see:
http://www.daniweb.com/forums/post1306519.html#post1306519

If you want other people to read and help with your code, you might want to follow the Python style guide, written by GVR himself:
http://www.python.org/peps/pep-0008.html