Try this: write a program that tests someones reaction times and records them in a text file and then makes comparisons to see the level of improvment or the lack of.

sneekula commented: nice idea +4

With so much hoopla about hydrogen as fuel of the future let's do this:
Write a Python program that calculates the energy obtained from burning one liter of hydrogen (H2) gas, as compared to one liter of methane gas or propane gas.

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 have a good project for beginers of python if you want to join me then mail me back at my yahoo id that is off_gl(@)yahoo(.)com
subject want to join project

You can create a relatively safe numeric input using this function:

``````def get_num(prompt="Enter a number: "):
"""
the function will loop until a number has been entered,
accepts int or float, returns a float
"""
while True:
try:
return float(raw_input(prompt))
except ValueError:
print "Numeric value required!"

# test it ...
print get_num()
price = get_num("Enter the price: ")
print price``````

Your mission, should you accept, is to limit the numeric input to a number within a given range.

Oh the price of petrol!

I just made a back of the envelop calculation from the latest German Automobile Club numbers. As of July 15, 2008 the price of the liter petrol there is 1.55 Euro. The price in the US is \$4.25 per gallon. A US gallon is 3.785 liter and the Euro costs US \$1.60. It would be nice to make a small Python program to compare the cost of petrol there to the price of petrol in the US.

I calculated the US price to be \$1.20 per liter or 0.75 Euro per liter. If you would travel to Germany it would cost you US \$9.39 per gallon. Your program ought to spit this out quickly.

Write a program that generates acronyms, for instance it would turn the string "National Aeronautics and Space Administration" into NASA for short. Notice that words like "and", "the" are most often ignored

1. Create a program that shutsdown/loggsoff a user after a period of inactivity.
Hint: Use the PyHook module at http://mindtrove.info/articles/monitoring-global-input-with-pyhook/ and the os module

2. Create a function that filters obcenities out of typed speech like in some IRC or AIM chatrooms.
Hint: Use the standard re module (may make it easier)

3.Ever see The Number 23? Ask a user for their age, birthday, address, name,Phone numbers etc... and see if it can find any 23's or 32's
Hint: Change letters to numbers(duh!) a = 1, b = 2, c = 3...

4. I've heard that it is possible to create a brainf*ck compiler/interpreter in python pretty easily. Try it out.
Hint: http://linuxgazette.net/issue79/divakaran.html http://en.wikipedia.org/wiki/Brainfuck

5. Create an application that allows you to chat with someone directly over the internet
Hint: you need the socket module

Write a Python program to find the five digit number, that when multiplied by 4 gives a number with the 5 digits in reverse order?

Everyone loves a game. So why not make a series of Dice games such as Two up and Yahtzee.

For an extra challenge make an AI to play with and also add a GUI!

See if you can refine this random sentence generator a little:

``````# 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[0].upper() + s[1:] + '.'
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
the bare barrister
this mean mouse
the skinny sister
the aspiring FBI agent
my bald uncle
old aunt Jessy
the green giant
a timid trucker
the lawless lawyer"""

# middle part of a sentence (action)
part2 = """\
jumps over
flies over
crawls under
runs across
hops across
rapidly removes
openly ogles
carefully tastes
tightly hugs
flirts with
cries over
passionately kisses
looks for
takes a whiff of"""

# ending part of a sentence (object)
part3 = """\
a rusty fence
the laughing cow
the weedcovered backyard
my moldy malt
the rancid old cheese
the jolly green jelly
a tiny stick
a bottle of beer
a singing blue nun
a big lardy lump
the smelly salesman
a big mug of coffee
an old wooden table
any cheap garments
some spilled milk"""

print '-'*60

# number of sentences created
n = 5
sentence = make_sentence(part1, part2, part3, n)
for item in sentence:
print item

print '-'*60

"""
typical result -->
A giggling goose flirts with a tiny stick.
This mean mouse carefully tastes a big lardy lump.
A timid trucker openly ogles the rancid old cheese.
The bare barrister runs across the laughing cow.
The obese ostrich takes a whiff of some spilled milk.
"""``````

Editor's note: Snee, I see you improved the code from http://www.daniweb.com/forums/post159482-4.html just a little. It's not an exact duplicate, so I keep it here.

Sorry Mister Moderator, I found this program on my hardrive (under yet unfinished projects). Now I know where it came from. I was thinking about refining it into a random story teller. Now that would be a worthwhile project.

With more and more folks thinking it their business to snoop around in your e-mail, write a little Python program to encode regular text. It is assumed that you will send this text to a friend, who has Python installed and can run a program you send beforehand to decode the encrypted text (after using the correct password of course). Use Python module md5 to encrypt the password too.

I am showing you the basic framework of a simple quiz program. You can improve this program and/or set up a different dictionary of question:answer pairs, like country:capital or roman numerals:value ...

``````# question and answer quiz using a dictionary
# here a US state capital quiz, but easy to modify
# has optional file save and load

import pickle
import random

def test(d):
# key words would come up in the dictionary's hash order
# so shuffle the word list obtained from d.keys()
word_list = d.keys()
# shuffle is an inplace operation
random.shuffle(word_list)
for word in word_list:
count = 0
while True:
# change the prompt to whatever suites your quiz
prompt = "What is the capital of " + word + ": "
ans = raw_input(prompt)
if ans.lower() == d[word].lower():
print "Correct!"
break
else:
print "That is incorrect. Try again."
count += 1
# ask 3 times then go on to the next word
if count >= 3:
break

def save_d(filename, d):
'''save the dictionary to a file'''
fout = open(filename, "w")
pickle.dump(d, fout)
fout.close()

'''load the dictionary from a file'''
fin = open(filename, "r")
fin.close()
return d

# use a dictionary of state:capital pairs
# this keeps word and answer together and is easy to modify
d = {
'Alabama': 'Montgomery',
'Arizona': 'Phoenix',
'Arkansas': 'Little Rock',
'California': 'Sacremento',
'Connecticut': 'Hartford',
'Delaware': 'Dover',
'Florida': 'Tallahassee',
'Georgia': 'Atlanta',
'Hawaii': 'Honolulu',
'Idaho': 'Boise',
'Illinois': 'Springfield',
'Indiana': 'Indianapolis',
'Iowa': 'Des Moines',
'Kansas': 'Topeka',
'Kentucky': 'Frankfort',
'Louisiana': 'Baton Rouge',
'Maine': 'Augusta',
'Maryland': 'Annapolis',
'Massachusetts': 'Boston',
'Michigan': 'Lansing',
'Minnesota': 'St. Paul',
'Mississippi': 'Jackson',
'Missouri': 'Jefferson City',
'Montana': 'Helena',
'New Hampshire': 'Concord',
'New Jersey': 'Trenton',
'New Mexico': 'Santa Fe',
'New York': 'Albany',
'North Carolina': 'Raleigh',
'North Dakota': 'Bismarck',
'Ohio': 'Columbus',
'Oklahoma': 'Oklahoma City',
'Oregon': 'Salem',
'Pennsylvania': 'Harrisburg',
'Rhode Island': 'Providence',
'South Carolina': 'Columbia',
'South Dakota': 'Pierre',
'Tennessee': 'Nashville',
'Texas': 'Austin',
'Utah': 'Salt Lake City',
'Vermont': 'Montpelier',
'Virginia': 'Richmond',
'Washington': 'Olympia',
'West Virginia': 'Charleston',
'Wyoming': 'Cheyenne'
}

# optionally save and load any dictionary changes
filename = "state_capital.dat"
save_d(filename, d)

test(d)``````

Improvements could be to ask 10 questions, count correct and incorrect answers and give the user a score when done.

commented: Rep for overall work in this thread +9

How would you program a voting system in Python that would allow the typical uneducated voter to vote and yet be secure to fraud by dead voters and such?

Most of you know the song

99 bottles of beer on the wall,
99 bottles of beer!
Take one down, pass it around,
98 bottles of beer on the wall!

98 bottles of beer on the wall,
98 bottles of beer!
Take one down, pass it around,
97 bottles of beer on the wall!

...
...

2 bottles of beer on the wall,2 bottles of beer!
Take one down, pass it around,
1 bottle of beer on the wall!

1 bottle of beer on the wall,
1 bottle of beer!
Take one down, pass it around,
No more bottles of beer on the wall!

Your mission is to write the entire lyrics of this song using a Python for loop.

Has anyone heard of happy numbers?
Well wikipedia says this about them:

Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers.

For example:

23
2**2 = 4
3**3 = 9
4+9=13
1**1=1
3**3=9
1+9=10
1**1=1
0**0=0
0+1=1

So therefore 23 IS a happy number.
Try and make a program that can do two things:

• That can tell wether a number is happy.
• Check for all happy numbers in a range

I don't know if this has been mentioned yet (and I'm not going to look through the many pages of this thread to check), but write a simple program to convert a number in our system (base of 10) to a different base - such as binary (2), or hexadecimal (16). Or even a base of 3, 4, 5, e, pi, etc.

EX: a decimal number of 157 to a binary number would be: 10011101

Here's a useful little segment on binary numbers:
http://www.helpwithpcs.com/courses/binary-numbers.htm

Just a not for the folks that can't read well:
"If you have questions, start your own thread and don't clutter the sticky."

Here is one approach to a rock, paper and scissors game in console format:

``````# Rock, paper and scissors game ...

import random

def game(you):
"""
returns draw, win or lose in message string
"""
# pick the computer hand
comp = random.choice(hand)
# determine the winner
if you == comp:
return "You %s and computer %s result is a draw!" % (you, comp)
elif you == "rock" and comp == "scissors":
return "You %s and computer %s you win!" % (you, comp)
elif you == "paper" and comp == "rock":
return "You %s and computer %s you win!" % (you, comp)
elif you == "paper" and comp == "scissors":
return "You %s and computer %s you lose!" % (you, comp)
elif you == "rock" and comp == "paper":
return "You %s and computer %s you lose!" % (you, comp)
elif you == "scissors" and comp == "paper":
return "You %s and computer %s you win!" % (you, comp)
elif you == "scissors" and comp == "rock":
return "You %s and computer %s you lose!" % (you, comp)
else:
return ""

print "Rock, paper and scissors game by ... "
print
print "Options:"
print "1  rock"
print "2  paper"
print "3  scissors"
print "4  random"
print "5  exit"
print

hand = ["rock", "paper", "scissors"]
win = 0
lose = 0
draw = 0
result = ""
while True:
try:
opt = int(raw_input("Enter your option number ( 1- 5): "))
except:
opt = 4  # default on error is random pick
if opt == 1:
result = game("rock")
elif opt == 2:
result = game("paper")
elif opt == 3:
result = game("scissors")
elif opt == 4:
result = game(random.choice(hand))
elif opt == 5:
break
else:
result = ""

if "draw" in result:
draw += 1
elif "win" in result:
win += 1
elif "lose" in result:
lose += 1
else:
print "Please enter number 1 - 5 only"

print
print result
print "win = %d, lose = %d, draw = %d" % (win, lose, draw)

print
print "Thanks for playing!"``````

See if you can make the game simpler, or more modern by going to a GUI and graphics.

Hi,
This is the first Python code i have written without the aid of a tutorial, i was wondering if you could look over it and provide me with your feed back on any bad habits i may have and if there was an easier way to write this, Your feedback would be greatly appreciated.

Thanks

import time
print "Welcome to my measurement converter"
print "This converter will convert meters into yards"

Meters = int(raw_input("Enter the number of meters"))
Yards = Meters * 1.094
print Meters, "Meters is equal to", Yards, "yards"

time.sleep(5)

Why don't you post it in a new thread so that we don't muddy up the tutorial thread with random comments.

Editor: Thanks, this post has been moved to its own thread.

commented: Thanks for the comment +11

Python is very well suited for text modifications. Write a small Python program that modifes this typical raw email text:

``````Why did the chicken cross the road?
>
>
>           BARACK OBAMA:
>>          The chicken crossed the road because it was time for a
>           CHANGE! The chicken wanted CHANGE!
>
>
>           JOHN McCAIN:
>>          My friends, that chicken crossed the road because he
>           recognized the need to engage in cooperation and dialogue
>           with all the chickens on the other side of the road.
>
>
>           HILLARY CLINTON:
>           When I was First Lady, I personally helped that little
>           chicken to cross the road. This experience makes me
>           uniquely qualified to ensure -- right from Day One! -- that
>           every chicken in this country gets the chance it deserves to
>
>
>           GEORGE W. BUSH:
>           We don't really care why the chicken crossed the road.
>           We just want to know if the chicken is on our side of the
>           road or not. The chicken is either against us or for us.
>           There is no middle ground here.
>
>
>           COLIN POWELL:
>           Now to the left of the screen, you can clearly see the
>           satellite image of the chicken crossing the road...
>
>
>           JOHN KERRY:
>           Although I voted to let the chicken cross the road, I am
>           now against it! It was the wrong road to cross, and I was
>           misled about the chicken's intentions. I am not for it
>           now, and will remain against it.
>
>
>           BILL CLINTON:
>           I did not cross that road with THAT chicken!!!! .... What,
>           exactly, is your definition of chicken?
>
>
>           AL GORE:
>           I invented the chicken!
>
>
>           DICK CHENEY:
>           Where's my gun?
>
>
>           ANDERSON COOPER:
>           We have reason to believe there is a chicken, but we have
>           not yet been allowed to have access to the other side of the
>
>
>           PAT BUCHANAN:
>           To steal the job of a decent, hard-working American.
>
>
>           BARBARA WALTERS:
>           Isn't that interesting? In a few moments, we will be
>           listening to the chicken tell, for the first time, the
>           heart-warming story of how it experienced a serious case of
>           molting, and went on to accomplish its life long dream of
>
>
>           OPRAH WINFREY:
>           Well, I understand that the chicken is having problems,
>           of having the chicken learn from his mistakes and take
>           falls, which is a part of life, I'm going to give this
>           chicken a car so that he can just drive across the road and
>           not live his life like the rest of the chickens.
>
>
>           DR. PHIL:
>           The problem we have here is that this chicken won't
>           realize that he must first deal with the problem on
>           'THIS' side of the road before it goes after the
>           problem on the 'OTHER SIDE' of the road. What we
>           need to do is help him realize how stupid he's acting by
>           not taking on his 'CURRENT' problems before adding
>           'NEW' problems.
>
>
>           MARTHA STEWART:
>           No one called me to warn me which way that chicken was
>           going. I had a standing order at the Farmer's Market to
>           sell my eggs when the price dropped to a certain level. No
>           little bird gave me any insider information.
>
>
>           NANCY GRACE:
>           That chicken crossed the road because he's GUILTY! You
>           can see it in his eyes and the way he walks.
>
>
>           BILL GATES:
>           I have just released eChicken2008, which will not only
>           documents, and balance your check book. Internet Explorer is
>           an integral pa rt of eChicken. This new platform is much
>           more stable and will never crash.
>
>
>           GRANDPA:
>           In my day, we didn't ask why the chicken crossed the
>           that was good enough.
>
>
>           DR. SEUSS:
>           Did the chicken cross the road? Did he cross it with a
>           toad? Yes, the chicken crossed the road, but why it crossed
>           I've not been told.
>
>
>           ERNEST HEMINGWAY:
>           To die in the rain. Alone.
>
>
>           ARISTOTLE:
>           It is the nature of chickens to cross the road.
>
>
>           JOHN LENNON:
>           Imagine all the chickens in the world crossing roads
>           together, in peace.
>
>
>           ALBERT EINSTEIN:
>           Did the chicken really cross the road, or did the road move
>           beneath the chicken?
>
>
>           COLONEL SANDERS:
>           Did I miss one?``````

To a more normal text like this:

``````Why did the chicken cross the road?

Barack Obama:
The chicken crossed the road because it was time for a
CHANGE! The chicken wanted CHANGE!

John McCain:
My friends, that chicken crossed the road because he
recognized the need to engage in cooperation and dialogue
with all the chickens on the other side of the road.

Hillary Clinton:
When I was First Lady, I personally helped that little
chicken to cross the road. This experience makes me
uniquely qualified to ensure -- right from Day One! -- that
every chicken in this country gets the chance it deserves to

George W. Bush:
We don't really care why the chicken crossed the road.
We just want to know if the chicken is on our side of the
road or not. The chicken is either against us or for us.
There is no middle ground here.

Colin Powell:
Now to the left of the screen, you can clearly see the
satellite image of the chicken crossing the road...

John Kerry:
Although I voted to let the chicken cross the road, I am
now against it! It was the wrong road to cross, and I was
misled about the chicken's intentions. I am not for it
now, and will remain against it.

Bill Clinton:
I did not cross that road with THAT chicken!!!! .... What,
exactly, is your definition of chicken?

Al Gore:
I invented the chicken!

Dick Cheney:
Where's my gun?

Anderson Cooper:
We have reason to believe there is a chicken, but we have
not yet been allowed to have access to the other side of the

Pat Buchanan:
To steal the job of a decent, hard-working American.

Barbara Walters:
Isn't that interesting? In a few moments, we will be
listening to the chicken tell, for the first time, the
heart-warming story of how it experienced a serious case of
molting, and went on to accomplish its life long dream of

Oprah Winfrey:
Well, I understand that the chicken is having problems,
of having the chicken learn from his mistakes and take
falls, which is a part of life, I'm going to give this
chicken a car so that he can just drive across the road and
not live his life like the rest of the chickens.

Dr. Phil:
The problem we have here is that this chicken won't
realize that he must first deal with the problem on
'THIS' side of the road before it goes after the
problem on the 'OTHER SIDE' of the road. What we
need to do is help him realize how stupid he's acting by
not taking on his 'CURRENT' problems before adding
'NEW' problems.

Martha Stewart:
No one called me to warn me which way that chicken was
going. I had a standing order at the Farmer's Market to
sell my eggs when the price dropped to a certain level. No
little bird gave me any insider information.

Nancy Grace:
That chicken crossed the road because he's GUILTY! You
can see it in his eyes and the way he walks.

Bill Gates:
I have just released eChicken2008, which will not only
documents, and balance your check book. Internet Explorer is
an integral pa rt of eChicken. This new platform is much
more stable and will never crash.

Grandpa:
In my day, we didn't ask why the chicken crossed the
that was good enough.

Dr. Seuss:
Did the chicken cross the road? Did he cross it with a
I've not been told.

Ernest Hemingway:
To die in the rain. Alone.

Aristotle:
It is the nature of chickens to cross the road.

John Lennon:
Imagine all the chickens in the world crossing roads
together, in peace.

Albert Einstein:
Did the chicken really cross the road, or did the road move
beneath the chicken?

Colonel Sanders:
Did I miss one?``````

Notice that something like JOHN McCAIN: --> John McCain: needs special attention.

You pay 2 Dollars and you are allowed to throw 4 dice. If the sum of the dice is less than 9, you win 12 Dollars, otherwise you lose your investment. Should you play this game?

How about making a program that will get your weather forecast for tomorrow?

You can use modules such as urllib2 and things like that to get the source code of your favourite web weather forecaster and then scrape off all of the html tags to leave you with your forecast for the next few days.

Let's have some fun with mathematics, write a Python program for each question:

1) What do you get when you add up the numbers 1-100 consecutively?

2) What number multiplied by itself gives the number 12345678987654321?

3) What five digit number, when multiplied by the number 4, gives a number with the digits in reverse order?

Write a simple calendar program. One that will remember dates that you have set. For this you would have to save it in some place.
Perhaps take a look at Pickle modules. This can be used to save instances and the like.

This program could be used very well in a GUI in fact wxPython has a specific built in object for making a calendar...

Python30 has been released, install it and go through much of the existing sample Python code and rewrite it so it will work on Python30.

Write a programmer's calculator that shows a numeric integer entry in denary (base10), binary(base2), octal(base8) and hexadecimal (base16). Allow entry in any of these bases.

Also does some simple binary stuff like shift-left and shift-right, binary or, binary and and binary xor.

If the integer falls into the ASCII range, display its character or meaning.

Write a program that gets that latest comic from your favourite webcomic.