Create a letter pyramid in Python.

let's say the user enters H
the pyramid should like this:
       A
      ABA
     ABCBA
    ABCDCBA
   ABCDEDCBA
  ABCDEFEDCBA
 ABCDEFGFEDCBA
ABCDEFGHGFEDCBA

Here is a small Python program for an online gem store:

# the online gem store

def add2cart(item, amount):
    """build up the cart list"""
    price = amount*list_of_gems[item-1][1]
    cart.append((item-1, amount, price))
    
# list of (gem, price) tuples
list_of_gems = [('ruby', 99.99), ('emerald', 72.50), ('topaz', 23.95), ('agate', 14.00)]

# will be list of (item#, amount, price) tuples
cart = []
# total of all purchases
total = 0

while True:
    print '-'*32, '\n\t\tList of Gems\n', '-'*32
    for k in range(len(list_of_gems)):
        # starts with item_number to enter
        print '%d\t%8s for $%0.2f each' % (k+1, list_of_gems[k][0], list_of_gems[k][1])
    try:
        item = int(raw_input('\nPlease select a gem (by number): '))
        if item > len(list_of_gems):
            print "item number too high! Try again!"
            item = 0
    except ValueError:
        print "Item number not correct! Try again!"
        item = 0
    try:
        if item > 0:
            amount = int(raw_input('Enter quantity of selected item: '))
    except ValueError:
        print "Amount not correct, has to be whole number!  Try again!"
        amount = 0
    if item > 0 and amount > 0:
        add2cart(item, amount)
    else:
        print "Please enter item and amount again!\a\n"
    
    # added .lower() so user can enter 'No' or 'NO' or 'no'
    more = raw_input('Want to buy something else (yes/no)? ').lower()
    # user can enter 'no' or just 'n'
    if 'n' in more:
        print
        print "Thank you for your order, here is your purchase detail:"
        break

print '\n', '~'*38
for x in range(len(cart)):
    item_number = cart[x][0]
    gem = list_of_gems[item_number][0]
    price = list_of_gems[item_number][1]
    quantity = cart[x][1]    
    total_per_item = cart[x][2]
    print '%4d  %8s @ $%0.2f = $%5.2f' % (quantity, gem, price, total_per_item)
    total += total_per_item
    
print '~'*38
print "\t%18s = $%4.2f" % ('TOTAL', total)

There are a few problems for you to iron out. If the customer enters an order for the same gem more than once, the program should consolidate the order for that paticular gem. Also the customer should be asked at the end, if the order is correct. If not, a user-friendly correction mechanism should be built in.

commented: Practical Stuff! +5

Create a database you can search for names, phone numbers, addresses, hobbies, aspirations and so on.

You could use something like snippet:
http://www.daniweb.com/code/snippet390.html

However, you need to improve it so you can update and save and load the data as a file.

Just a sometimes elusive Python/Tkinter rectangle. Could that be turned into a game?

# click on the red rectangle ...
 
from Tkinter import *
import random
 
def create_rect():
    chance = random.sample(range(1, 250), 4)
    print chance  # test  eg. [72, 206, 116, 166]
    canvas.create_rectangle(chance, fill="red")
 
def check_rect(event):
    rect = canvas.find_overlapping(event.x, event.y, event.x, event.y)
    if rect:
        # delete old rectangle
        canvas.delete(rect)
        # create new rectangle
        create_rect()
 
root = Tk()
root.title("click on red")
 
canvas = Canvas(root, height=250, width=250, bg="yellow")
canvas.pack()
 
# create the starting random rectangle
create_rect()
 
# respond to left mouse button click
canvas.bind("<Button-1>", check_rect)
 
root.mainloop()

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

Write a function primes(n) that returns a list of primes less than n.

primes(13)
[2,3,5,7,11]
primes(25.2)
[2,3,5,7,11,13,17,19,23]

If you don't know any clever ways to generate primes, Google for the "Sieve of Eratosthenes"

Project for the advanced: write code to hack into Ene's gem store above from a remote zombie and change all the prices to $19.99.

:lol:

Write Human vs. Computer Battle Ship Game in Python. Tkinter should/could do it for the graphics.

Possible setup:
Battleship (1) = 4 adjoining squares
Cruiser (2) = 3 adjoining squares
Destroyer (3) = 2 adjoining squares

The code below shows a birthday message on fairly large banner using the Tkinter GUI module.

# a simple banner using Tkinter
 
from Tkinter import *
 
#create the form
root = Tk()
 
canvas1 = Canvas(root, height=100, width=600, bg="white")
canvas1.pack()
 
str1 = "Happy Birthday Ursula!"
x = 20
y = 20
text1 = canvas1.create_text(x, y, anchor=NW, text=str1, font=('times', 32, 'bold'), fill='red')
 
root.mainloop()

Now improve the code so each of the letters shows up in a different color following the colorpattern of a rainbow.

Member Avatar for Mouche

Create a game similar to "Wheel of Fortune." Have a list of words, and have the program randomly pick a word from the list. Then, let the user guess 5 or so letters, and after each guess, show the word he or she is guessing in this format:

- Say the word is "jelly" and they guessed "l"

--ll-

After the five letters, have the user guess the word. If they get it right, congratulate them. Otherwise, tell them the correct word.

What I like to do is to take an idea that you might think is really easy and see how small you can make the code I've made a script that prints Fibonacci's numbers in 66 bytes. its challenging but fun at the same time it pushes your skill beyond what a simple prgramming idea works.

f=[0,1]
for i in range(input()-2):
 f.append(f[-2]+f[-1])
print f

btw if someone knows a way to make this smaller email me please

Take a look at:
http://www.daniweb.com/code/snippet604.html
and use this database templet to create an address book. You can add a 'print address labels' feature to it.

The easiest would be to write the address labels to a file and use one of the editors or word processors to actually print it out to the printer.

Below is the Python code for a simple console blackjack game. It's just you against the computer ...

# a simple blackjack game to figure out the ace_1_11 algorithm
from random import choice as rc
def total(hand):
    # how many aces in the hand
    aces = hand.count(11)
    # to complicate things a little the ace can be 11 or 1
    if aces == 1:
        t = sum(hand)
        if t > 21:
            # evaluate the ace as a 1
            t = t - 10
    elif aces == 2:
        t = sum(hand)
        if t > 21:
            # evaluate one ace as a 1
            t = t - 10
            if t > 21:
                # evaluate second ace as a 1
                t = t - 10
    elif aces == 3:
        t = sum(hand)
        if t > 21:
            # evaluate one ace as a 1
            t = t - 10
            if t > 21:
                # evaluate second ace as a 1
                t = t - 10
                if t > 21:
                    # evaluate third ace as a 1
                    t = t - 10
    elif aces == 4:
        t = sum(hand)
        if t > 21:
            # evaluate one ace as a 1
            t = t - 10
            if t > 21:
                # evaluate second ace as a 1
                t = t - 10
                if t > 21:
                    # evaluate third ace as a 1
                    t = t - 10
                    if t > 21:
                        # evaluate fourth ace as a 1
                        t = t - 10
    # could go for more aces here ... (odds?)
    else:
        t = sum(hand)
    return t
 
# for a suit of cards in blackjack assume the following values
# (jack, queen, king have value 10  ace has value 11, can be value 1)
cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
# there are 4 suits per deck and usually several decks
# this way you can assume the cards list to be an unlimited pool
cwin = 0  # computer win counter
pwin = 0  # player win counter
while True:
    player = []
    # draw 2 cards for the player to start
    player.append(rc(cards))
    player.append(rc(cards))
    pbust = False  # player busted flag
    cbust = False  # computer busted flag
    while True:
        # loop for the player's play ...
        tp = total(player)
        print "Player has these cards %s with a total value of %d" % (player, tp)
        if tp > 21:
            print "--> Player is busted!"
            pbust = True
            break
        elif tp == 21:
            print "\a BLACKJACK!"
            break
        else:
            hs = raw_input("Hit or Stand/Done (h or s): ").lower()
            if 'h' in hs:
                player.append(rc(cards))
            else:
                break
    while True:
        # loop for the computer's play ...
        comp = []
        comp.append(rc(cards))
        comp.append(rc(cards))
        # dealer generally stands around 17 or 18
        while True:
            tc = total(comp)
            if tc < 18:
                comp.append(rc(cards))
            else:
                break
        print "Computer has %s for a total of %d" % (comp, tc)
        # now figure out who won ...
        if tc > 21:
            print "--> Computer is busted!"
            cbust = True
            if pbust == False:
                print "Player wins!"
                pwin += 1
        elif tc > tp:
            print "Computer won!"
            cwin += 1
        elif tc == tp:
            print "A draw!"
        elif tp > tc:
            if pbust == False:
                print "Player won!"
                pwin += 1
            elif cbust == False:
                print "Computer wins!"
                cwin += 1
        break
    print
    print "Wins, player = %d  computer = %d" % (pwin, cwin)
    quit = raw_input("Press Enter (q to quit): ").lower()
    if 'q' in quit:
        break
    print
print
print "Thanks for playing blackjack with me!"

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

You are urged to improve the game by adding more players and maybe display real cards using a GUI toolkit.

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. 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.

I guess this one is a bit advanced but it will seriously help you (It is my current personal project)
Write a program that helps determine hand-eye coordination. (A good GUI toolkit is wxPython) First test the hand-eye coordination skills of the user by letting a few images/buttons/words or whatever appear randomly and they have to click on it. So take the current time which the person takes to click on the and calculate the time. the amount of time the person take will determine their hand-eye coordination ability

Also in the blackjack game: find a way to make the total() function deal with aces in a general way so that vega's worry about adding more aces can be satisfied.

def total(hand):
    # how many aces in the hand
    aces = hand.count(11)
    # to complicate things a little the ace can be 11 or 1
    if aces == 1:
        t = sum(hand)
        if t > 21:
            # evaluate the ace as a 1
            t = t - 10
    elif aces == 2:
        t = sum(hand)
        if t > 21:
            # evaluate one ace as a 1
            t = t - 10
            if t > 21:
                # evaluate second ace as a 1
                t = t - 10
    elif aces == 3:
        t = sum(hand)
        if t > 21:
            # evaluate one ace as a 1
            t = t - 10
            if t > 21:
                # evaluate second ace as a 1
                t = t - 10
                if t > 21:
                    # evaluate third ace as a 1
                    t = t - 10
    elif aces == 4:
        t = sum(hand)
        if t > 21:
            # evaluate one ace as a 1
            t = t - 10
            if t > 21:
                # evaluate second ace as a 1
                t = t - 10
                if t > 21:
                    # evaluate third ace as a 1
                    t = t - 10
                    if t > 21:
                        # evaluate fourth ace as a 1
                        t = t - 10
    # could go for more aces here ... (odds?)
    else:
        t = sum(hand)
    return t

With this project you need to do some "googling" to get the needed information.

If the USA would like to replace all the gasoline presently consumed here with ethanol, how many bushels of corn would US farmers have to grow to produce the ethanol.

Are there enough acres of farmland in the US to do this?

Here are some projects that require a little library work and Google searching at first.

1) Write a simple Python code to C++ code converter
2) Write a small Python "Expert System"
3) Write a Python program the applies Artificial Intelligence (AI)
4) Write a Python "Data Mining" program

Here is a simple Tkinter GUI program that has three sliders for the red, green, blue color values that make up the rgb-colors of a canvas rectangle. Move the sliders (scales in tk) and create 16777216 different colors ...

# Tkinter RGB color evaluator
 
import Tkinter as tk
 
def change(event):
    global rect
    # clear the present rectangle
    cv.delete(rect)
    # format RGB hexcolor string eg.  red='#FF0000'
    xcolor = "#%02X%02X%02X" % (v_red.get(), v_green.get(), v_blue.get())
    root.title("hexcolor = %s" % xcolor)
    rect = cv.create_rectangle(0,0,200,200,fill=xcolor)
 
 
root = tk.Tk()
 
v_red = tk.IntVar()
red = tk.Scale(root, label="R", variable=v_red, from_=0, to=255)
red.grid(row=0, column=0, padx=3, pady=3)
red.bind('<B1-Motion>', change)
 
v_green = tk.IntVar()
green = tk.Scale(root, label="G", variable=v_green, from_=0, to=255)
green.grid(row=0, column=1, padx=3, pady=3)
green.bind('<B1-Motion>', change)
 
v_blue = tk.IntVar()
blue = tk.Scale(root, label="B", variable=v_blue, from_=0, to=255)
blue.grid(row=0, column=2, padx=3, pady=3)
blue.bind('<B1-Motion>', change)
 
cv = tk.Canvas(root, width=200, height=200)
cv.grid(row=0, column=3, padx=3, pady=3)
rect = cv.create_rectangle(0,0,200,200,fill='black')
 
root.mainloop()

Your mission is to create a fourth slider that changes the rectangle's colors along the scale of a rainbow (red to blue).

An extra (Jeff will like that):
If you want to experiment with class objects, change the code so it uses a class.

I was playing around with Python's calendar module ...

import calendar
year = 2007
month = 3     # march
# print out the current month's calendar
calendar.prmonth(year, month)
print
# get the week day header as a list
day_list = calendar.weekheader(width=2).split()
print day_list
print
# assign the month's calendar to a matrix (list of lists)
# each sublist is a week (unused days are zero)
week_list = calendar.monthcalendar(year, month)
for week in week_list:
    print week
"""
output -->
     March 2007
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 31
['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su']
[0, 0, 0, 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, 31, 0]
"""

One could create a 7x6 matrix of buttons, let's say with the Tkinter GUI toolkit and fill the buttons with the week_list info. Then use the day_list info as a header. You will have a monthly calendar as a bunch of buttons (zeros would be empty).

Now, one could press a particular day's button and bring up an entry with the date. The user writes in that day's memo (appointmnets, thing to do) and saves it as a dictionary with the date as the key, so it can be linked with that date for later use. You could finish this one.

Here are some well known approximations of pi:

# approximations of pi
# 3/14 is the official 'Pi Day'
# 3/14 is Albert Einstein's birthday (year 1879, born in Ulm)
# as of feb2007 the pi approximation record is 1,241,100,000,000 digits 
 
import math
 
# for your reference here is pi calculated to 77 decimals:
3.14159265358979323846264338327950288419716939937510582097494459230781640628620
 
# Chinese approximation, easy to remember
# take 113355 then split in half ...
p1 = 355/113.0
 
# Ramanujan1 or 'Chinese plus' (still 1, 3 or 5)
p2 = 355/113.0 * (1 - 0.0003/3533)
 
# deJerphanion, possibly easy to remember
p3 = math.log(23 + 1/22.0 + 2/21.0)
 
# Ramanujan2
p4 = 99*99/(2206*math.sqrt(2))
 
# Castellano
p5 = 1.09999901 * 1.19999911 * 1.39999931 * 1.69999961
 
# Kochansky
p6 = math.sqrt(40/3.0 - math.sqrt(12))
 
# Golden Ratio
p7 = 3/5.0 * (3 + math.sqrt(5))
 
print "math.pi =", math.pi # 3.14159265359
print "Ramanujan1 =", p2 # 3.14159265359
print "deJerphanion =", p3 # 3.14159265393
print "Ramanujan2 =", p4 # 3.14159273001
print "Chinese =", p1 # 3.14159292035
print "Castellano =", p5 # 3.14159257347
print "Kochansky =", p6 # 3.14153333871
print "Golden Ratio =", p7 # 3.1416407865

There is still room to invent one approximation for pi that is easy to remember! Go and find it!

Spreadsheets are really not that difficult to make with Python. Here is the beginning of a simple Tkinter based spreadsheet program:

# the beginning of a simple Tkinter spreadsheet program
 
import Tkinter as tk
 
root = tk.Tk()
root.title('Tkinter spreadsheet phase 1')
 
def click(event, cell):
    # can do different things with right (3) and left (1) mouse button clicks
    root.title("you clicked mouse button %d in cell %s" % (event.num, cell))
    # test right mouse button for equation solving
    # eg. data = '=9-3' would give 6
    if event.num == 3:
        # entry object in use
        obj = dict[cell]
        # get data in obj
        data = obj.get()
        # if it starts with '=' it's an equation
        if data.startswith('='):
            eq = data.lstrip('=')
            print data, eq
            try:
                # solve the equation
                result = eval(eq)
                #print result, type(result) # test
                # remove equation data
                obj.delete(0, 'end')
                # update cell with equation result
                obj.insert(0, str(result))
            except:
                pass
 
def key_r(event, cell):
    # return/enter has been pressed
    data = dict[cell].get() # get text/data in given cell
    #print cell, dict[cell], data # test
    root.title("cell %s contains %s" % (cell, data))
 
# create a dictionary of key:value pairs
dict = {}
w = 20
h = 1
alpha = ["", 'A', 'B', 'C', 'D', 'E', 'F']
for row in range(5):
    for col in range(5):
        if col == 0:
            # create row labels
            label1 = tk.Label(root, width=3, text=str(row))
            label1.grid(row=row, column=col, padx = 2, pady=2)
        elif row == 0:
            # create column labels
            label1 = tk.Label(root, width=w, text=alpha[col])
            label1.grid(row=row, column=col, padx = 2, pady=2)
        else:
            # create entry object
            entry1 = tk.Entry(root, width=w)
            # place the object
            entry1.grid(row=row, column=col) #, padx = 2, pady=2)
            # create a dictionary of cell:object pair
            cell = "%s%s" % (alpha[col], row)
            dict[cell] = entry1
            # bind the object to a left mouse click
            entry1.bind('<Button-1>', lambda e, cell=cell: click(e, cell))
            # bind the object to a right mouse click
            entry1.bind('<Button-3>', lambda e, cell=cell: click(e, cell))
            # bind the object to a return/enter press
            entry1.bind('<Return>', lambda e, cell=cell: key_r(e, cell))
 
#print dict # test
 
# set the focus on cell A1
dict['A1'].focus()
 
root.mainloop()

Right now I am using the right mouse button click to evaluate equations starting with '=', for instance a cell data of '=355/113.0' would give the approximation of pi.

Still to do --> summing rows or columns of cells using something like '=sum(A1..A4)' needs to be parsed and evaluated. You also have to add a data save and load, plus a few more items you come up with. A nice project to complete!

You have the following data statements:

data = """
Jim likes Larry and Jean, but hates Kim.
Bob loves Jean, and likes Larry and Kim.
Jean loves Bob, likes Jim, but hates Kim.
Kim hates Jim, likes Larry and Bob.
Larry loves Martin, and hates Karl and Jean.
"""

Write a program that lists each person and whom they love, like and hate.

Am I authorised to post here?

This one should be nice-ish.

I'm sure you've heard of Sudoku? Well write a computer program that creates a sudoku game for the user. Try to be innovative in the program rules (tweak the sudoku game rules a little so that the program is fun to play, or maybe more challenging...nothing dratsic though that doesn't make it "sudoku" anymore).

I already started a very limited working console version that *tries* to generate a solved puzzle, and then plays the game by comparing the solved puzzle to a new grid created to store the user's input.
Scroll down to get the code...

Your objectives are simple(ah...not so much), and ranked by ease(the latter ones may really try you if you are a beginner):

1. Currently, the program generates a very limited set of very easily solved puzzles(there is an obvious pattern that each and every puzzle follows). You are required to change the program so that it can read a puzzle from a data file.

2. Create a Gui front end for this program and get rid of this ugly, tedious console prompt...after which, allow the user to input false/temporary entries in the available squares that they can erase at any time they choose. When you've done with that, to really polish your UI, allow the user the ability to undo a max of 10 moves by order in which they made them (this should be separate from the ability to delete temporary squares), HINT: use a static stack implementation (This isn't too tedious right?)

3. Create an algorithm so that the program will no longer check to see if the user grid matches the solved grid (to determine win), but check each of the nine blocks, rows and columns individually to detemine a win.

4. Create an algorithm that can generate more dynamic "Valid" puzzles.

Questions? PM me. If you need help, I think it's ok to post in the forums...but I'm no mod...

here is the code:

import random, time, sys
NINE=[1, 2, 3, 4, 5, 6, 7, 8, 9]
SIX=[1, 2, 3, 4, 5, 6]
FOUR=[1, 2, 3, 4]
def do_bottom(row, mode):
    if mode==9:
        row2=[]
        i=2
        while len(row2)<7:
            row2.append(row[i])
            i+=1
        i=0
        while i<2:
            row2.append(row[i])
            i+=1
        return row2
    
def do_top(row, mode):
    if mode==9:
        row2=[]
        i=1
        while len(row2)<8:
            row2.append(row[i])
            i+=1
        i=0
        while i<1:
            row2.append(row[i])
            i+=1
        return row2
def do_next(row, mode):
    if mode==9:
        row2=[]
        i=3
        while len(row2)<6:
            row2.append(row[i])
            i+=1
        i=0
        while i<3:
            row2.append(row[i])
            i+=1
        return row2
class Grid(object):
    def __init__(self, size):
        self.rows=[]
        self.size=size
        self.populate(size)
        self.solution=self.rows[:]
        self.erase(1)
        self.wrong=0
        self.turns=0
        
    def populate(self,mode):
        if mode==9:
            starter=NINE[:]
            random.shuffle(starter)
            self.row1=starter
            self.rows.append(self.row1)
            self.row2=do_next(starter, mode)
            self.rows.append(self.row2)
            self.row3=do_next(self.row2, mode)
            self.rows.append(self.row3)
            self.row4=do_top(starter, mode)
            self.rows.append(self.row4)
            self.row5=do_next(self.row4, mode)
            self.rows.append(self.row5)
            self.row6=do_next(self.row5, mode)
            self.rows.append(self.row6)
            self.row7=do_bottom(starter, mode)
            self.rows.append(self.row7)
            self.row8=do_next(self.row7, mode)
            self.rows.append(self.row8)
            self.row9=do_next(self.row8, mode)
            self.rows.append(self.row9)
    def print_me(self):
        print "\n\nColumns:1   2   3   |   4   5   6   |   7   8   9\t|Rows"
        print "_____________________________________________________"
        i=0
        for row in self.rows:
            i+=1
            if i ==4 or i==7:
                print "___________________________________________________",
            print "\n\t",
            j=0
            for number in row:
                j+=1
                if j==4 or j==7:
                    print "|  ",
                print str(number)+"  ",
            print "\t|"+str(i)
    def print_gride(self):
        for row in self.solution:
            print "\n"
            for number in row:
                print str(number)+"  ",
    def erase(self, mode):
        if mode==1:
            num=[]
            for i in range(9):
                nums=[]
                nums.append(random.randrange(3))
                nums.append(random.randrange(3,6))
                nums.append(random.randrange(6,9))
                num.append(nums)
            i=0
            for i in range(9):
                self.rows[i]=["x", "x", "x", "x", "x", "x", "x", "x", "x"]
                for number in num[i]:
                    self.rows[i][number]=self.solution[i][number]
    def check_entries(self, row, column, entry):
        if self.rows[row][column]!="x":
            print "Sorry, this square has already been filled."
            self.turns-=1
        elif self.solution[row][column]==entry:
            print "\nCorrect."
            time.sleep(2)
            self.rows[row][column]=entry
        else:
            print "\nNo. Bad entry. Correct entry is being inserted."
            self.rows[row][column]=self.solution[row][column]
            self.wrong+=1
            time.sleep(2)
    def do_turn(self):
        self.print_me()
        self.turns+=1
        print "\nWrong guesses: "+str(self.wrong)+"\tTurns: "+str(self.turns)
        time.sleep(3)
        raw_input("Press ENTER when you are ready to continue")
        print "Input the row number of the block you wish to guess."
        row=get_integer(1, 10)
        print "Input the column number."
        column=get_integer(1, 10)
        print "Now what number do you think should be in this block?"
        change=get_integer(1, 10)
        print "\nNow, are you absolutely sure about these entries?"
        print "1. Yes"
        print "2. No"
        sure=raw_input()
        if sure =="1":
            self.check_entries(row-1, column-1, change)
        else:
            self.turns-=1
            print "Okay, think about it."
            time.sleep(2)
    def check(self):
        if self.wrong>=5:
            print "Sorry! Too many bad moves!\n\n\n"
            time.sleep(1)
            print"""        GAME OVER - YOU LOST"""
            time.sleep(1)
            print """     reverting to main screen"""
            return False
        elif self.rows==self.solution:
            print "You solved it! You actually solved it."
            print "You conquered this puzzle in", self.turns, "turns, and only", wrong,"bad moves."
            time.sleep(1)
            print "\n\n\n"
            print """       GAME OVER - YOU WON"""
            time.sleep(1)
            print"""     reverting to main screen"""
            return False
        else:
            return True
def interface():
    print "\n\n\t\t9 Puzzle Sudoku\n"
    print "What grid qould you like?"
    print "1. 4x4"
    print "2. 6x6"
    print "3. 9x9"
    print "\n\n4. No Grid. Let me out"
    option=raw_input()
    if option=="1" or option=="2":
        print "sorry, this function has not yet been coded."
    if option=="4":
        print "\t\t\tGOODBYE"
        time.sleep(3)
        sys.exit()
    if option=="3":
        print "\nCreating your puzzle, please wait."
        grid=Grid(9)
        run=1
        while run:
            grid.do_turn()
            run=grid.check()
    interface()
def get_integer(start, stop):
    try:
        x=int(raw_input())
        if x in range(start, stop):
            return x
        else:
            y=int(asdsd)
    except:
        print "You must enter a number between", start,"and",stop-1
        return get_integer(start, stop)
interface()

If you are interested in mathematics, there is a large number of projects you can participate in at:
http://www.projecteuler.net/

You can use any language, but Python seems to be popular. Girls, don't be scared, mathematics is not just for the guys!

Create a webbrowser in 100 % Python.

Just an exercise in drawing letters with the wxPython GUI toolkit:

# a nifty 'Hello' using wxPython drawing stuff
# (you can add 'World' as a coding exercise)

import wx

class MyFrame(wx.Frame):
    """a frame with a panel"""
    def __init__(self, parent=None, id=-1, title=None):
        wx.Frame.__init__(self, parent, id, title)
        self.panel = wx.Panel(self, size=(500, 200))
        self.panel.Bind(wx.EVT_PAINT, self.on_paint)
        self.Fit()

    def on_paint(self, event):
        # establish the painting surface of given color
        dc = wx.PaintDC(self.panel)
        bg_color = 'yellow'
        dc.SetBrush(wx.Brush(bg_color))
        dc.DrawRectangleRect((0, 0, 500, 200))

        # draw 5 adjoining red circles with red fill
        dc.SetPen(wx.Pen('red', 1))
        dc.SetBrush(wx.Brush('red'))
        y = 100
        r = 50
        for k in range(1, 6):
            x = k * 100 - 50
            dc.DrawCircle(x, y, r)

        # cut out a few notches for the letters
        # draw background colored rectangles (x, y, w, h)
        dc.SetPen(wx.Pen(bg_color, 1))
        dc.SetBrush(wx.Brush(bg_color))
        dc.DrawRectangleRect((40, 50, 20, 40))
        dc.DrawRectangleRect((40, 110, 20, 40))
        dc.DrawRectangleRect((150, 70, 50, 20))
        dc.DrawRectangleRect((150, 110, 50, 20))
        dc.DrawRectangleRect((240, 50, 60, 70))
        dc.DrawRectangleRect((340, 50, 60, 70))
        dc.DrawCircle(450, 100, 20)
        

app = wx.PySimpleApp()
frame1 = MyFrame(title='the hello circles')
frame1.Center()
frame1.Show()
app.MainLoop()

hi
I am new member
i am starting python since 2 weeks ago ,and want to learn it from here .

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?

Module for handling strings (learning stuff)

#######################################
# Programmed by : StrikerX
# Purpose : Module for handling string
#######################################


def toUpper(string):
    string_upper = ""
    for char in string :
        if  ord(char) < 97 :
            string_upper += char
        elif ord(char) >= 97 :
            string_upper += chr(ord(char) - 32)
    print string_upper



def toLower(string):
    string_Lower = ""
    for char in string :
        if ord(char) > 97 :
            string_Lower += char
        elif ord(char) <= 97:
            string_Lower += chr(ord(char) + 32 )
    print string_Lower


def swapCase(string):
    string_Swapped = ""
    for char in string :
        if ord(char) >= 97:
            string_Swapped += chr(ord(char) - 32 )
        elif ord(char) < 97:
            string_Swapped += chr(ord(char) + 32 )
    print string_Swapped


def lenString(string):
    count = 0
    for char in string :
        count += 1
    return count
    

def exist(char, string):
    if char in String :
        print "0"  #True
    else :
        print "1"  #False 

    

        
def startsWith(char, string):
    if string[0] == char :
        print "0"  #True
    else :
        print "1"  #False


def endsWith(char, string):
    if string[len(string) - 1] == char:
        print "0" #True
    else :
        print "1" #False
        
def index(string):
    print string[0]


def capitalize(string):
    Str = ""
    char = ''
    x = string[0]
    if ord(string[0]) < 97 :
        char = string[0]
    if ord(string[0]) >= 97 :
        char = chr(ord(string[0]) - 32)
    Str = char + string[1:]
    print Str
    



def printf(string):
    print string
#!bin/python

#-###############################
# Programmer : StrikerX
# Purpose : Cat Tool
##################################

#cat.py state fileName
#cat.py -h

import sys
import os


def read():
    fileName = sys.argv[2]
    f = open(fileName, "r")
    for line in f.readlines():
        print line
    f.close()


def append():
    arr = []
    fileName = sys.argv[2]
    if os.path.exists(fileName):
        f = open(fileName, "a")
        buf = "string"
        while buf != "":
            buf = raw_input("")
            arr.append(buf)
        for x in arr:
            f.write(x + '\n')
        f.close()
        


def write():
        fileName = sys.argv[2]
        arr = []
        f = open(fileName, "w")
        buf = "string"
        while buf != "":
            buf = raw_input("")
            arr.append(buf)
        for x in arr:
            f.write(x + '\n')
        f.close()

def h():
    print "\tParam -> State"
    print "\n\t > -> Write\n\t>> -> Append\n\t-r -> read\n\t-a -> About\n\t-h -> Help Menu"




param = sys.argv[1]

if param == "-h":
    fileName = ""
    h()
elif param == "-r":
    read()
elif param == "-w":
    write()
elif param == "-a":
    append()
else:
    print "an illegal parameter !!"
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.