#!bin/python

###################################
# Written by : StrikerX
# Date : May 10 07
# Purpose : simple Shell in Python
###################################
from os import *  # to use getcwd(), listdir(), chdir(), system() .
from sys import * # to use exit().

print "Welcome to Python Shell ! " 

command = ""

while (command != "exit"):
    command = raw_input(getcwd() + " %>#")
    command = command.strip()
    if command.strip()[:2] == 'cd':
            chdir(command.strip()[3:]) #getting the Path to be changed 2 !
    elif command == "ls":
        for x in listdir(getcwd()):
               print x
    else:
        system(command)

print "you are logging out of Python Shell ! "
exit() #EXIT

Predict the outcome of this Python code:

def sub_one(x):
    print "x before if -->", x
    if x > 1:
        x = x - 1
        sub_one(x)
    print "x after if -->", x
    return x
 
x = 5
final = sub_one(x)
print "final result -->", final

Can you explain the odd behaviour?

Easy. The call to sub_one(x) prints x, calls sub_one(x-1), and prints x-1!

x before if --> 5
x before if --> 4
x before if --> 3
x before if --> 2
x before if --> 1 (the if is not executed here)
x after if --> 1
x after if --> 1
x after if --> 2
x after if --> 3
x after if --> 4
final result --> 4 (the only modification made to x is "x = x - 1")

Crypting text is always fun, here is a simple rotation crypt (enough to make the NSA guys laugh) ...

# simple rotation crypting of lowercase strings
 
import string
 
shift_right_by2 = string.maketrans(string.ascii_lowercase,
    string.ascii_lowercase[2:] + string.ascii_lowercase[:2])
 
# test --> cdefghijklmnopqrstuvwxyzab
print string.ascii_lowercase[2:] + string.ascii_lowercase[:2]
 
shift_left_by2 = string.maketrans(string.ascii_lowercase,
    string.ascii_lowercase[-2:] + string.ascii_lowercase[:-2])
 
# test --> yzabcdefghijklmnopqrstuvwx
print string.ascii_lowercase[-2:] + string.ascii_lowercase[:-2]
 
print "hello world".translate(shift_right_by2)  # jgnnq yqtnf
print "jgnnq yqtnf".translate(shift_left_by2)   # hello world
 
# stay below 26 or you go full circle
# --> abcdefghijklmnopqrstuvwxyz
print string.ascii_lowercase[26:] + string.ascii_lowercase[:26]

You can try other shift values from 1 to 25. If you use 26, you go once around the circle of course. How would you include capital letters?

Luckily, I have kept most of the useless stuff I wrote when I was a beginner. I knew they helped a lot, even though they were quite trivial, and note that I'm listing everything here (even the silliest!)

1) Create a proggie called "even" to print, for a range of numbers, whether they're even or odd. Make the range user-specified. Generalise so the user can input any divisor they like to check for (not only 2). Generalise so the user can not only input a range of numbers, but an arithmetic progression.

2) Create a program called "exp". It should ask for two numbers and then do an exponentiation, without using the exponentiation operator
(flow control).

3) Generate a random string. Make the length user-specified. Make the set of characters user-changeable.

4) Create a program to print the UTC time. Change it to your local time.

5) Create a base-converter.

commented: nice ideas +10

Here is code for simple word guessing game:

# a very simple word guessing game

import random

def check(veil, guess, word):
    """
    check if the guess letter is in the word
    if found then update the veil
    """
    for ix, letter in enumerate(word):
        if letter == guess:
            veil[ix] = guess
    return veil

print "Guess a word (lower case letters only) ... "

words = ['art', 'bush', 'letter', 'banana', 'radio', 'hard',
    'kiss', 'perl', 'target', 'fork', 'rural', 'zero', 'organ']

while True:
    # pick a word at random
    word = random.choice(words)
    tries = 0
    # create veil of dashes matching the word length
    veil = list('-' * len(word))
    while '-' in veil:
        print "".join(veil),
        guess = raw_input("Enter a letter: ").lower()
        veil = check(veil, guess, word)
        tries += 1
    
    print "".join(veil)
    prompt = "You guessed correctly in %d tries, try again (y or n): " % tries
    tries = 0
    yn = raw_input(prompt).lower()
    if 'n' in yn:
        print "Thank you for playing!"
        break

Improve the game making sure each random word is picked only once. How would you add an hint to each of the words?

This would be one way to create multiple stories from the same basic text ...

# string templating is new in Python24
 
import string
 
def change_text(text, sub_dictionary):
    t = string.Template(text)
    return t.substitute(sub_dictionary)
 
text = 'The $animal says "$sound, my name is $name!"'
 
d_cow = dict(animal='cow', sound='mooh', name='Hilda')
print change_text(text, d_cow)
 
d_dog = dict(animal='dog', sound='woof', name='Rover')
print change_text(text, d_dog)
 
d_cat = dict(animal='cat', sound='meow', name='George')
print change_text(text, d_cat)
 
print
 
# test the dictionary creation
print d_cow  # {'sound': 'mooh', 'name': 'Hilda', 'animal': 'cow'}
 
"""
result -->
The cow says "mooh, my name is Hilda!"
The dog says "woof, my name is Rover!"
The cat says "meow, my name is George!"
"""

If you read the news from Europe, you will find that temperatures are given in degrees Celcius and rain fall is measured in liters per squaremeter. Write a program the converts between Celcius and Fahrenheit, also between liters per squaremeter and inches of rain.

I don't know if this idea has already been added, but beginners can create an address book. That was the first real project I undertook. Ask the user for: name, address, phone, cell, fax, etc. Then store the data in a .txt file. Let the user search people in the list, create new listings, delete listings, and edit existing ones.

# the numbers in this list have the same sum and product
lst = [0.5, 1.2, 3.75, 4.36]
 
# test the assertion ...
print 0.5 * 1.2 * 3.75 * 4.36  # 9.81
print sum(lst)                 # 9.81

1) Test this assertion using a for loop.
2) Can you come up with other such lists, using Python to help you?

This little code could be beginning of a scrambled sentence game:

# simple sentence scrambler

import random

def scatter_word(a_word):
    """
    scramble a word, and leave words less than 4 characters long,
    and the beginning and ending characters of longer words alone
    """
    if len(a_word) < 4:
        return a_word
    else:
        # create a list of interior characters
        t = list(a_word[1:-1])
        # shuffle the characters
        random.shuffle(t)
        # join back to form a word
        return a_word[0] + "".join(t) + a_word[-1]

def scatter_text(text):
    return " ".join(scatter_word(x) for x in text.split(" "))


text = "A goldfish has a memory span of three seconds"
print scatter_text(text)

"""
possible result -->
A gfiosldh has a momery sapn of trehe sondecs
"""
# This is text from a file I found.  Write a Python program to
# convert the text into a dictionary with "state": "motto" pairs
# something like {"Alabama": "At Least We're not Mississippi",
# "Alaska": "11,623 Eskimos Can't be Wrong!", ...}
#
# Then write a program that allows you to enter the state and
# it will display the motto of that state.

state_mottos = """\
Alabama:    At Least We're not Mississippi

 Alaska:     11,623 Eskimos Can't be Wrong!

 Arizona     But It's a Dry Heat

 Arkansas:   Litterasy Ain't Everthing

 California: As Seen on TV

 Colorado:   If You Don't Ski, Don't Bother

 Connecticut:  Like Massachusetts, Only Dirtier and with less Character

 Delaware:   We Really Do Like the Chemicals in our Water

 Florida:    Ask Us About Our Grandkids

 Georgia:    We Put the 'Fun' in Fundamentalist Extremism

 Hawaii:     Haka Tiki Mou Sha'ami Leeki Toru (Death to Mainland
             Scum, But Leave Your Money)

 Idaho:      More Than Just Potatoes... Well Okay, Maybe Not, But
             The Potatoes Sure Are Good

 Illinois:   Please Don't Pronounce the "S"

 Indiana:    2 Billion Years Tidal Wave Free

 Iowa:       We Do Amazing Things With Corn

 Kansas:     First Of The Rectangle States

 Kentucky:   Five Million People; Fifteen Last Names

 Louisiana:  We're Not All Drunk Cajun Wackos, But That's Our Tourism Campaign

 Maine:      We're Really Cold, But We Have Cheap Lobster

 Maryland:   A Thinking Man's Delaware

 Massachusetts:    Our Taxes Are Lower Than Sweden's (For Most Tax Brackets)

 Michigan:   First Line of Defense From the Canadians

 Minnesota:  10,000 Lakes and 10,000,000 Mosquitoes

 Mississippi:      Come Feel Better About Your Own State

 Missouri:   Your Federal Flood Relief Tax Dollars at Work

 Montana:    Land of the Big Sky, the Unabomber, Right-Wing Crazies, and
             Very Little Else

 Nebraska:   Ask About Our State Motto Contest

 Nevada:     Whores and Poker!

 New Hampshire:    Go Away and Leave Us Alone

 New Jersey: You Want a ##$%##! Motto? I Got Yer ##$%##! Motto Right Here!

 New Mexico: Lizards Make Excellent Pets

 New York:   You Have the Right to Remain Silent, You Have the Right to
             an Attorney...

 North Carolina:   Tobacco is a Vegetable

 North Dakota:     We Really are One of the 50 States!

 Ohio:       We Wish We Were In Michigan

 Oklahoma:   Like the Play, only No Singing

 Oregon:     Spotted Owl... It's What's For Dinner

 Pennsylvania:     Cook With Coal

 Rhode Island:     We're Not REALLY An Island

 South Carolina:   Remember the Civil War? We Didn't Actually Surrender

 South Dakota:     Closer Than North Dakota

 Tennessee:  The Educashun State

 Texas:      Si' Hablo Ingles

 Utah:       Our Jesus Is Better Than Your Jesus

 Vermont:    Yep

 Virginia:   Who Says Government Stiffs and Slackjaw Yokels Don't Mix?

 Washington: Help! We're Overrun By Nerds and Slackers!

 Washington, D.C.: Wanna Be Mayor?

 West Virginia:    One Big Happy Family -- Really!

 Wisconsin:  Come Cut Our Cheese

 Wyoming:    Wynot?
"""

Write an anagram program that takes someone's name and uses all the letters to create a phrase, for instance:
Osama Bin Laden --> 'bad neon salami'
George W Bush --> 'whose bugger'
George Bush --> 'he bugs Gore'
Tony Blair --> 'bony trail'
Ronald Reagan --> 'loan arranged'
David Letterman --> 'nerd amid late TV'
Elvis --> 'lives'

... beyond names:
The Morse Code --> Here Come Dots
Slot Machines --> Cash Lost in'em
Mother-in-law --> Woman Hitler
Statue of Liberty --> Built to Stay Free
New York Times --> Monkey writes
eleven plus two --> twelve plus one

You could also write a Python program that checks the above anagrams for correctness.

Something little more entertaining:

Write program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number, and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

Topic: Encryption

#1 Write a program that that encrypts a string based on a alphanumeric key input by the user (or a number for a step encrypt program).

#2 enhance your program in #1 so that is the encrypted output is different every time, but can still be decrypted with the key.

#3 Modify the program in #2 so that it can handle private/public keys.

#4Write a script that can generate private and public keys for use with #3

#5 Write a program that can look for patterns in and break simple encryptions. Test it on #1, #2 and #3 (but do not write it based on your knowledge of howw they work). Be sure to set timouts, ie., if your loops exceed a certain amount of runs, force to program to stop, instead of hanging.

In the above:
Think of an innovative way to use dictionaries in any/all.

the random module will help in #2. But using it incorrectly will yield an undesired result. A bit of thinking and planning would be required. Perhaps there is way way to do this without random. Can you think of it?

char() and ord() functions in python are useful.

Comment your code, and use meaningful variable names. You will soon find that your program will swell at a rapid rate and otherwise understanding will be difficult. It is also a good practise to employ regardless what what you program

I am having a problem with the green highlighted
items that appear in your text
How do I get " what looks like a magnifying glass
followed by code" and "what looks like a magnifying glass followed by keywords"

I still don't understand how to put that in my code. How is it done? Do I have to have some special test tool?

That is one of the more nauseating features added by DaniWeb. It brings up unwanted advertisement from certain words.

Editor's note ...
To get rid of the green IntelliText, follow this path:
User Control Panel
Edit Options
Miscellaneous Options
Disable IntelliTXT

Write a Python program that calculates pi to a precision of 100 decimal places.

Write a Python program that converts the string 'supercalifragilisticexpialidocious' to the string 'SuPeRcAlIfRaGiLiStIcExPiAlIdOcIoUs'.

Make a small plug-in (extension) with Python that for example opens a (new) file in one of the following free programs:

* Blender (3D modeling)
* The Gimp (2D editing)
* Inkscape (vector editing)
* OpenOffice (office suite)


Some info links:

Blender:
http://www.blender.org/
http://jmsoler.free.fr/didacticiel/blender/tutor/python_script00_en.htm

The Gimp
http://www.gimp.org/
http://www.jamesh.id.au/software/pygimp/

Inkscape
http://www.inkscape.org
http://www.inkscape.org/screenshots/index.php?lang=en&version=0.42

OpenOffice
http://www.openoffice.org/index.html
http://wiki.services.openoffice.org/wiki/Python
http://udk.openoffice.org/python/python-bridge.html

Write a Python program that asks the user a series of multiple choice questions about preferences (hair, eyes, figure, food, car, vacation, music, sport, fun etc.), and then picks a date from a number of celebreties. You might have to do some googling.

Here is an easy one. Create a list of integers between 1 an 100 that are not divisible by 2 or 3.

If you had a way to mark water molucules, and then added 1 drop of
that marked water into the earth's oceans and mixed it well. How many
of the marked molcules of water would you find in each drop of ocean water?

Some helpful information:
Avogadro's number N = 6.023 x 10^23 (6.023e23) molecules/mole
1 mole of water has a volume of 18 ml
Assume that 1 ml water contains 30 drops
Volume of all the earth's oceans is 1.35 billion cubic kilometers

You are constructing a robot vehicle that has two tracks like a tank. Each track is driven by a DC motor that can go from full foreward (signal = 1.0) to slower foreward (eg. signal = 0.3) to rest (signal = 0.0) and slow reverse (eg. signal = -0.1) to full reverse (signal = -1.0). To turn, one track is moved slower than the other.

The control is done with a joy stick that has two variable outputs. One is the x-axis (full foreward 1.0 to full reverse -1.0) and y-axis (full left = 1.0 to full right -1.0). Write a Python program that interprets these outputs correctly so the two motors can receive the proper signal for variable speeds foreward, reverse, and left and right turns.

Tomorrow is Easter Sunday, and it's quite early this year. Use the following Python function to calculate the earliest Easter Sunday for the next 100 years (2008 to 2108) and for the next 1000 years ...

def calc_easter(year):
    """returns the date of Easter Sunday of the given yyyy year"""
    y = year
    # golden year - 1
    g = y % 19
    # offset
    e = 0
    # century
    c = y/100
    # h is (23 - Epact) mod 30
    h = (c-c/4-(8*c+13)/25+19*g+15)%30
    # number of days from March 21 to Paschal Full Moon
    i = h-(h/28)*(1-(h/28)*(29/(h+1))*((21-g)/11))
    # weekday for Paschal Full Moon (0=Sunday)
    j = (y+y/4+i+2-c+c/4)%7
    # number of days from March 21 to Sunday on or before Paschal Full Moon
    # p can be from -6 to 28
    p = i-j+e
    d = 1+(p+27+(p+6)/40)%31
    m = 3+(p+26)/30
    # returns (month, day, year) tuple of Easter Sunday
    return (m, d, y)

Here is a small dictionary of food items and their calories. The portion amounts vary all over the map. Convert all calories for a 1 oz portion or, if you desire, a 100 gram portion (1 oz = 28.35 grams):

# a dictionary of {food_name:[amount, calories], ...}
food = {
"pastrami": ["2 oz", 170],
"meatloaf": ["3 oz", 315],
"veal": ["3.5 oz", 190],
"beef": ["2 oz", 310],
"venison": ["4 oz", 225],
"potato": ["8 oz", 100],
"spinach": ["8 oz", 45],
"tomato": ["8 oz", 45],
"egg plant": ["3.5 oz", 25],
"cauliflower": ["8 oz", 35],
"butter": ["1 oz", 200],
"cheddar": ["1 oz", 115],
"swiss": ["1 oz", 105],
"egg": ["2 oz", 80]
}

Using the Tkinter or the wxPython GUI toolkit, design a program that uses sliders to change the RGB values of a sample label's background color and its text (foreground) color in real time. Once you are happy with the colors, allow it to save the rgb values to the clipboard so they can be used in a program.

This Python snippet might be of help:
http://www.daniweb.com/code/snippet457.html

Here is a very basic text editor using the wxPython GUI toolkit. Your mission will be to add some features like find, replace, wordcount etc. to it:

# the start of a small text editor with file load and save menu
# notice that the wx.TextCtrl() surface has already some advanced
# features: 
# you can select text, right click to cut, copy and paste etc.

import os
import wx

# pick unique ID values
ID_ABOUT = 101
ID_LOAD = 102
ID_SAVE = 103
ID_EXIT = 110

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, wx.ID_ANY, title, size = (500, 300))
        self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE)
        # statusBar at the bottom of the window
        self.CreateStatusBar() 
        # set up the menu
        filemenu= wx.Menu()
        filemenu.Append(ID_ABOUT, "&About"," Information about this program")
        filemenu.Append(ID_LOAD,"File&Load", " Load a text file")
        filemenu.Append(ID_SAVE,"File&Save", " Save a text file")
        filemenu.AppendSeparator()
        filemenu.Append(ID_EXIT,"E&xit"," Terminate the program")
        # create the menubar
        menuBar = wx.MenuBar()
        # adding the "filemenu" to the MenuBar
        menuBar.Append(filemenu,"&File")
        # adding the MenuBar to the Frame content 
        self.SetMenuBar(menuBar)  
        # attach the menu-event ID_ABOUT to the method self.OnAbout
        wx.EVT_MENU(self, ID_ABOUT, self.OnAbout)
        # attach the menu-event ID_OPEN to the method self.OnOpen
        wx.EVT_MENU(self, ID_LOAD, self.OnLoad)
        # attach the menu-event ID_SAVE to the method self.OnSave
        wx.EVT_MENU(self, ID_SAVE, self.OnSave)
        # attach the menu-event ID_EXIT to the method self.OnExit
        wx.EVT_MENU(self, ID_EXIT, self.OnExit)
        # display the frame   
        self.Show(True)

    def OnAbout(self, e):
        """ the about box """
        about = wx.MessageDialog( self, " A very simple editor \n"
            " using the wxPython GUI toolkit", "About Simple Editor", wx.OK)
        about.ShowModal()
        about.Destroy()

    def OnLoad(self, e):
        """ open a file"""
        self.dirname = ''
        dlg = wx.FileDialog(self, "Choose a file to load", 
            self.dirname, "", "*.*", wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()
            f = open(os.path.join(self.dirname,self.filename),'r')
            self.control.SetValue(f.read())
            f.close()
        dlg.Destroy()

    def OnSave(self, e):
        """ Save a file"""
        self.dirname = ''
        dlg = wx.FileDialog(self, "Choose or create a file to save to", 
            self.dirname, "", "*.*", wx.SAVE)
        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()
            f = open(os.path.join(self.dirname,self.filename),'w')
            f.write(self.control.GetValue())
            f.close()
        dlg.Destroy()
    
    def OnExit(self, e):
        self.Close(True)


app = wx.PySimpleApp()
frame = MyFrame(None, -1, "A Simple Editor (click on File for menu)")
app.MainLoop()

How about a Noughts and Crosses game with AI so when the computer can it will win and it will block the player from winning if it can.
Try make it so there are difficulty setting ranging from easy to beat to nearly impossible.
If you want you could add a tournament kind of thing by having 'best of three' rounds

Some Python riddles. Try to figure out the possible results:

print max(max('hello', 'world'))
print [1] * 5
q = zip(range(3), 'abc')
t1, t2 = zip(*q)
print q
print t1
print t2

The short Python program below shows you how to create a hot-spot on a frame/window surface using the Tkinter GUI toolkit:

# show mouse position as mouse is moved and create a hot-spot

import Tkinter as tk

root = tk.Tk()

def showxy(event):
    xm = event.x
    ym = event.y
    str1 = "mouse at x=%d  y=%d" % (xm, ym)
    root.title(str1)
    # switch color to red if mouse enters a set location range (hot-spot)
    x = 100
    y = 100
    delta = 10  # range around center x,y
    if abs(xm - x) < delta and abs(ym - y) < delta:
        frame.config(bg='red')
    else:
        frame.config(bg='yellow')
        

frame = tk.Frame(root, bg= 'yellow', width=300, height=200)
frame.bind("<Motion>", showxy)
frame.pack()

root.mainloop()

Your project will be to put a picture or map image on the surface, and then create a number of hot-spots. When the mouse pointer gets in range of these hot-spots a descriptive text message could appear. You could also make it different sounds or whatever, use your imagination.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.