We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,301 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion
Page 3 of Article: Starting Python
The idea of this thread is to help the beginning Python programmer with hints and helpful code. Please feel free to contribute! If you have any questions start your own thread! The creators of Python are very active, improving the language all the time. Here is a little of the…

Some neat code from the forum. The question was:
... when I take a list with duplicates and make it a set then the duplicates are gone. How can I find out which were those duplicates?

A good solution came from monkeyy ...

lst1 = list('a list of characterstrings')
for item in set(lst1):
    print item, 'counted', lst1.count(item), 'times'
 
"""
result =
a counted 3 times
  counted 3 times  (space)
c counted 2 times
e counted 1 times
...
"""

Edit: changed l to lst1

vegaseat
DaniWeb's Hypocrite
Moderator
6,478 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,612
Skill Endorsements: 36

The thread regarding 'how to do input in python' is great ..
Thanks for the contribution

deeppython
Newbie Poster
3 posts since Jan 2006
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

Just a little thing about reverse spelling I picked up from the internet ...

# reverse the spelling of an input string
# string reverse slice [::-1] introduced in Python23
# reversed() introduced in Python24
 
text = raw_input("Enter a string: ")
print text[::-1]
 
# or
print raw_input("Enter a string: ")[::-1]
 
# or
print ''.join(reversed(raw_input("Enter a string: ")))
vegaseat
DaniWeb's Hypocrite
Moderator
6,478 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,612
Skill Endorsements: 36

Two small examples of sorting in Python. The first example shows you how to sort a list of numeric strings as strings or as integers. The results are quite different ...

# sort a list of numeric strings:
 
list1 = ['0', '100', '28', '39', '1', '1003']
 
print "Original list of numeric strings:"
print list1
 
print "Sort as strings:"
list1.sort()
print list1 # ['0', '1', '100', '1003', '28', '39']
 
print "Sort as integers (Python24):"
list1.sort(key=int)
print list1 # ['0', '1', '28', '39', '100', '1003']

The second examples shows you how to sort two related lists in parallel, so the relationships stay intact ...

# sort two lists in parallel ...
# create two lists of same length
list1 = ['one', 'two', 'three', 'four']
list2 = ['uno', 'dos', 'tres', 'cuatro']
 
# create a list of tuples, (english, spanish) pairs
data = zip(list1, list2)
print data # [('one', 'uno'), ('two', 'dos'), ('three', 'tres'), ('four', 'cuatro')]
 
# can use parallel looping to display result ...
for english, spanish in data:
    print english, spanish # one uno etc.
 
# each whole tuple will be sorted
data.sort()
print data # [('four', 'cuatro'), ('one', 'uno'), ('three', 'tres'), ('two', 'dos')]
 
# if you need two lists again after sorting then use ...
list3, list4 = map(lambda t: list(t), zip(*data))
print list3 # ['four', 'one', 'three', 'two']
print list4 # ['cuatro', 'uno', 'tres', 'dos']
 
# if you need just two tuples use ...
tuple1, tuple2 = zip(*data)
print tuple1 # ('four', 'one', 'three', 'two')
print tuple2 # ('cuatro', 'uno', 'tres', 'dos')
vegaseat
DaniWeb's Hypocrite
Moderator
6,478 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,612
Skill Endorsements: 36

This littel program allows you to find which key had been pressed using the Tkinter GUI.

# bind and show a key event with Tkinter 

from Tkinter import *

root = Tk()
prompt = '      Press any key      '
label1 = Label(root, text=prompt, width=len(prompt))
label1.pack()

def key(event):
    if event.char == event.keysym:
        msg = 'Normal Key %r' % event.char
    elif len(event.char) == 1:
        msg = 'Punctuation Key %r (%r)' % (event.keysym, event.char)
    else:
        msg = 'Special Key %r' % event.keysym
    label1.config(text=msg)

label1.bind_all('<Key>', key)

root.mainloop()
bumsfeld
Nearly a Posting Virtuoso
1,495 posts since Jul 2005
Reputation Points: 409
Solved Threads: 235
Skill Endorsements: 1

This code shows how to input a series of integers each separated by a space and then convert that input to a list of those integers:

# input a sequence of integer numbers separated by a space and convert to a list

def get_integer_list():
    while True:
        # get the sequence string and strip off any trailing space (easy mistake)
        str1 = raw_input("Enter a sequence of integers separated by a space: ").rstrip()
        try:
            # create a list of integers from the string using list comprehension
            return [int(num) for num in str1.split(" ")]
        except ValueError:
            print "Error: '%s' is not an integer! Try again." % num
            
print get_integer_list()

For example the input 1 2 3 4 5 turns into [1, 2, 3, 4, 5]

bumsfeld
Nearly a Posting Virtuoso
1,495 posts since Jul 2005
Reputation Points: 409
Solved Threads: 235
Skill Endorsements: 1

This small code allow you to list your computer's environment, things like processor, os, user and so on:

# list the environmental settings of your computer

import os

keys = os.environ.keys()
keys.sort()
for item in keys:
    print "%-22s : %s" % (item, os.environ[item])

As a bonus another small code to find the IP address of your computer:

# Get the IP address of the machine this program is running on
# or go to http://www.whatismyip.com/

import socket

print socket.gethostname()
print socket.getaddrinfo(socket.gethostname(), None)
# get just the IP address from the list's tuple
print socket.getaddrinfo(socket.gethostname(), None)[0][4][0]

Networks using the TCP/IP protocol route messages based on the IP address of the destination. An IP address is a 32-bit numeric address written as four numbers separated by periods.

bumsfeld
Nearly a Posting Virtuoso
1,495 posts since Jul 2005
Reputation Points: 409
Solved Threads: 235
Skill Endorsements: 1

Here is a class that allows you to convert Fahrenheit to Celcius or the reverse.

# class to convert F to C or C to F
# getFahrenheit(self) would be public
# __getFahrenheit(self) is private
# (double underline prefix makes method private to class)
 
class Temperature (object):
    """allows you to convert Fahrenheit to Celsius and vice versa"""
    def __init__(self):
        self.celsius = 0.0
    def __getFahrenheit(self):
        return 32 + (1.8 * self.celsius)
    def __setFahrenheit(self, f):
        self.celsius = (f - 32) / 1.8
    # property() combines get and set methods into one call
    fahrenheit = property(fget = __getFahrenheit, fset = __setFahrenheit)
 
d = Temperature()
 
# setting celsius value ==> getting fahrenheit value
d.celsius = 25
print "%0.1f C = %0.1f F" % (d.celsius, d.fahrenheit)
 
# setting fahrenheit value and getting celsius value
d.fahrenheit = 98
print "%0.1f F = %0.1f C" % (d.fahrenheit, d.celsius)

You might need to add a few test prints to figure that one out.

vegaseat
DaniWeb's Hypocrite
Moderator
6,478 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,612
Skill Endorsements: 36

This was part of a game, I modified slightly the code. The code checks that input is correct and within a supplied range.

def checkInput(type_string, present_value, low, high):
    '''uses a while loop, loops until an acceptible answer is given, then returns it'''
    prompt = "Present %s is %d, enter a new value (%d-%d): " % (type_string, present_value, low, high)
    while True: 
       try:
          a = int(raw_input(prompt))
          if low <= a <= high:
             return a
       except ValueError:
          print "Enter an integer number, please!"


# modify the present strength of 10 within the range (1-18)
modified_strength = checkInput("strength", 10, 1, 18)
print modified_strength
bumsfeld
Nearly a Posting Virtuoso
1,495 posts since Jul 2005
Reputation Points: 409
Solved Threads: 235
Skill Endorsements: 1

Code sample shows how to run a program and specified file(s) from commandline.

# using commandline to run a program and files

def process_datafile(filename):
    """load specified data file and process data"""
    # code to read file data
    # code to process data and show or return result
    print "Test only, file =", filename   # testing

if __name__ == '__main__':
    import sys

    # run the progam from the commandline and specify the data file(s) to be loaded
    # something like   myProgram data1.dat data2.dat
    if len(sys.argv) > 1:
        # sys.argv is a list eg. ['C:/Python24/Atest/myProgram.py', 'data1.dat', 'data2.dat']
        # sys.argv[0] is program filename, slice it off with sys.argv[1:]
        # using for loop, more than one datafile can be processed
        for filename in sys.argv[1:]:
            process_datafile(filename)
    else:
        print "usage myProgram datafile1 [datafile2 ...]"
bumsfeld
Nearly a Posting Virtuoso
1,495 posts since Jul 2005
Reputation Points: 409
Solved Threads: 235
Skill Endorsements: 1

Just an example how to work with Tkinter's color pick dialog ...

# select a color and color the root window
 
from Tkinter import *
import tkColorChooser
 
#help('tkColorChooser')
 
root = Tk()
 
colorTuple = tkColorChooser.askcolor()
 
print colorTuple # for red = ((255, 0, 0), '#ff0000')
print colorTuple[1] # #ff0000
 
root.configure(bg=colorTuple[1])
 
root.mainloop()
vegaseat
DaniWeb's Hypocrite
Moderator
6,478 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,612
Skill Endorsements: 36

This little code effort came out of one of the forum questions. The function calendar.prmonth(2006, 3) prints a neat little monthly calendar, can the output be assigned to a string for other uses? Here is one way to do this ...

# pipe the output of calendar.prmonth() to a string
 
import subprocess
 
code_str = \
"""
import calendar
calendar.prmonth(2006, 3)
"""
 
# save the code
filename = "mar2006.py"
fout = open(filename, "w")
fout.write(code_str)
fout.close()
 
# execute the code and pipe the result to a string
test = "python " + filename
process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode # 0 = success, optional check
# read the result to a string
month_str = process.stdout.read()
 
print month_str

There are simpler methods, but this is a good example of the os.popen() function, or the more updated subprocess.Popen().

Just remember to stick with a proportional font like Courier to line things up correctly.

vegaseat
DaniWeb's Hypocrite
Moderator
6,478 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,612
Skill Endorsements: 36

You can create a list by concatination and multiplication. The example below shows you a practical approach ...

# in English you print first as 1st, second as 2nd and so on
# create a list of suffixes for the days of the month (1 to 31)
# rather than typing 17 'th' for numbers 4 to 20 you can use 17*['th']
 
day_suffix = ['st', 'nd', 'rd'] + 17*['th'] + ['st', 'nd', 'rd'] + 7*['th'] + ['st']
print day_suffix
"""
result =
['st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th',
'th', 'th', 'th', 'th', 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st']
"""
 
# now test it
for x in range(1, 32):
    print "%d%s" % (x, day_suffix[x-1])
 
"""
result =
1st
2nd
3rd
4th
5th
...
30th
31st
"""
vegaseat
DaniWeb's Hypocrite
Moderator
6,478 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,612
Skill Endorsements: 36

So you want to add an image to your Tkinter GUI program, here is an example ...

from Tkinter import *
 
root = Tk()
 
# reads only GIF and PGM/PPM images
# for additional formats use Image, ImageTk from PIL
# pick a GIF file you have in your working directory
imagefile = "Flowers.gif"
photo1 = PhotoImage(file=imagefile)
 
width1 = photo1.width()
height1 = photo1.height()
canvas1 = Canvas(width=width1, height=height1)
canvas1.create_image(width1/2.0, height1/2.0, image=photo1)
canvas1.pack()
root.mainloop()
vegaseat
DaniWeb's Hypocrite
Moderator
6,478 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,612
Skill Endorsements: 36

You can use a global variable within a function by prefixing it with the word "global". Here is an example:

# keep track of how many times a function has been accessed
# using a global variable, somewhat frowned upon
def counter1():
    global count
    # your regular code here
    count += 1
    return count

# test it
count = 0         # a global variable
print counter1()  # 1
print counter1()  # 2
print count       # 2  variable count has changed
print

The trouble with a global variable is with using it somewhere else in a large program. Everytime you call this function its value will change and may lead to buggy code.

One solution is to use the namespace of the function, making the variable more unique. It gives you a hint where it is used, for example:

# avoid the global variable and use the function namespace
def counter2():
    # your regular code here
    counter2.count += 1
    return counter2.count    

# test it
counter2.count = 0  # now count has counter2 namespace, notice the period
print counter2()    # 1
print counter2()    # 2
print
Ene Uran
Posting Virtuoso
1,830 posts since Aug 2005
Reputation Points: 676
Solved Threads: 255
Skill Endorsements: 7

Ever wrote a Python program and wanted to use passwords? What good is password, if the user can simply look at your code and see it?

The module md5 comes to the rescue! It converts the password string to string containing series of hexadecimal numbers. You do that in program1, then copy and paste this hex string into your program (program2).

Here is program1 (keep that to yourself in save place):

# program 1, code to generate a hashed password
# the result is a series of hexadecimal numbers
# it is saved to one text file, so you can
# copy and paste it to program2 from any editor

import md5

# pick a password you can remember
password = "gummy"
pw_hashed = md5.md5(password).hexdigest()
print pw_hashed  # just testing
fout = open("MyHashedPassword.txt", "w")
fout.write(pw_hashed)
fout.close()

This is program2, showing only hex string hashed password, but user has to enter password 'gummy' for md5 to match:

# program2, copy hashed password from program1 and assign
# it to MYPASSWORDHASH as string, this is all user would see,
# if looking at your code

import md5

MYPASSWORDHASH = "c1944508a0d871c55b501624c36e0f68"
def get_password():
    # give it three tries
    for i in range(3):
        password = md5.md5(raw_input("Enter your password: "))
        password = password.hexdigest()
        if password == MYPASSWORDHASH:
            return True
    return False

def main():
    if get_password():
        print "Success"
        # do something here with rest of the program code
    else:
        print "Failure"
        # do something else here

if __name__ == "__main__":
    main()
bumsfeld
Nearly a Posting Virtuoso
1,495 posts since Jul 2005
Reputation Points: 409
Solved Threads: 235
Skill Endorsements: 1

Python allows you to combine a number of statements into one-liner:

str1 = "we willing women want warm winter woollies"

list1 = str1.split()
print list1  # ['we', 'willing', 'women', 'want', 'warm', 'winter', 'woollies']

list2 = [frag[:2] for frag in list1]
print list2  # ['we', 'wi', 'wo', 'wa', 'wa', 'wi', 'wo']

str2 = "".join(list2)
print str2  # wewiwowawawiwo

# combine all three statements
print "".join([frag[:2] for frag in str1.split()])

Here you have it, but watch out it becomes hard to read and understand at times. Me thinks, me just invented a new word "wewiwowawawiwo". Has nifty ring to it!

bumsfeld
Nearly a Posting Virtuoso
1,495 posts since Jul 2005
Reputation Points: 409
Solved Threads: 235
Skill Endorsements: 1

An example how to run a number of different games or utilities from a menu. The menu is within an infinite while loop with a quit option to break out of the loop. The games or utilities are implemented with a function call ...

import random
import time
import calendar
 
def guess_number():
    # random integer 1 to 99
    n = random.randint(1, 99)
    #print n # test
 
    while True:
        print
        guess = int(raw_input("Enter an integer from 1 to 99: "))
        if guess < n:
            print "guess is low"
        elif guess > n:
            print "guess is high"
        else:
            print "you guessed it!"
        print
        break
 
def calendar_now():
    """show the calendar for the present month"""
    year_month = time.localtime()[:2]
    print
    calendar.prmonth(year_month[0], year_month[1])
    print
 
while True:
    print "-" * 30
    print " Menu"
    print "to guess a number enter n"
    print "for a monthly calendar enter m"
    # more ...
    print "to quit enter q"
    print "-" * 30
    # also convert any upper case choice to lower case
    choice = raw_input("enter your choice: ").lower()
    if choice == 'n':
        guess_number()
    elif choice == 'm':
        calendar_now()
    # more elif here ...
    elif choice == 'q':
        print
        print "thanks for using my program!"
        break
    else:
        print "enter the correct choice!"
    print
vegaseat
DaniWeb's Hypocrite
Moderator
6,478 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,612
Skill Endorsements: 36

Someone should write a palindrome program for every computer language there is. Python knows how to handle strings and makes it relatively easy ...

# check if a phrase is a palindrome
 
def isPalindrome(phrase):
    """
    take a phrase and convert to all lowercase letters
    if it matches the reverse spelling then it is a palindrome
    """
    phrase_letters = [c for c in phrase.lower() if c.isalpha()]
    print phrase_letters # test
    return (phrase_letters == phrase_letters[::-1])
 
 
#phrase = "A man, a plan, a canal, Panama!"
phrase = "Madam in Eden I'm Adam"
if isPalindrome(phrase):
    print '"%s" is a palindrome' % phrase
else:
    print '"%s" is not a palindrome' % phrase
vegaseat
DaniWeb's Hypocrite
Moderator
6,478 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,612
Skill Endorsements: 36

You can use Python program to extract picture from web page and save it. I have tested this with Windows XP, might work with other OS:

# load given picture from web page and save it
# (you have to be on the internet to do this)

import urllib2
import webbrowser
import os

# find yourself a picture on a web page you like
# (right click on the picture, look under properties and copy the address)
picture_page = "http://www.google.com/intl/en/images/logo.gif"

#webbrowser.open(picture_page)  # test

# open the web page picture and read it into variable
opener1 = urllib2.build_opener()
page1 = opener1.open(picture_page)
my_picture = page1.read()

# open file for binary write and save picture
# picture_page[-4:] extracts extension eg. .gif
# (most image file extensions have three letters, otherwise modify)
filename = "my_image" + picture_page[-4:]
print filename  # test
fout = open(filename, "wb") 
fout.write(my_picture)
fout.close()

# was it saved correctly?
# test it out ...
webbrowser.open(filename)
bumsfeld
Nearly a Posting Virtuoso
1,495 posts since Jul 2005
Reputation Points: 409
Solved Threads: 235
Skill Endorsements: 1

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.1740 seconds using 2.81MB