vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

In the past there have been several projects to write an Operating System in Python. The one that survived seems to be cleese:
http://code.google.com/p/cleese/

Remember that Python is a glue language and can easily use ABC or C to do the low level stuff.

To write a modern OS would be a massive effort that would take hundreds of smart folks several years.

Nick Evan commented: I'll have to try this one :) +19
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I was a veteran, before I was a teenager.
-- Michael Jackson

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Be nice to people on your way up, because you'll meet 'em on your way down.
-- Wilson Mizner

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Are you using a 32-bit compiler or a 16-bit?
If 16-bit then you have a problem!


100000000
is 05f5e100 in hex requiring 32-bits to store. Since you are being signed due to the -1, It seems a Highes score of 32767 would be a more suitable test, IFF you are using a 16-bit compiler!

This is Python, the interpreter handles very large integer values only limited by available memory.

tux4life commented: Yes :) +10
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just a note to remind you that range(start, stop, step) has a step option, so you could have used ...

for celsius in range(0, 101, 2):
    fahrenheit = 1.8 * celsius + 32 
    print ('%0.2f %0.2f' % (celsius,fahrenheit))

All in all, nice clean coding style. Hope you enjoy your Python experience.

shadwickman commented: haha brilliantly clean, simple solution +2
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Not everything that can be counted counts, and not everything that counts can be counted.
-- Albert Einstein

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can use Hide and Show, here is an example ...

# create two frames with wxFrame, only one is showing

import wx

class Frame1(wx.Frame):
    def __init__(self, parent, mytitle):
        wx.Frame.__init__(self, parent, -1, mytitle)
        self.SetBackgroundColour("green")
        # pass frame1 to frame2 as instance self
        self.frame2 = Frame2(None, 'Frame2', self)

        # create input widgets
        self.button1 = wx.Button(self, -1, label='show Frame2')
        # bind mouse event to an action
        self.button1.Bind(wx.EVT_BUTTON, self.button1Click)

        # use a box sizer to lay out widgets
        sizer_v = wx.BoxSizer(wx.VERTICAL)
        # Add(widget, proportion, flag, border)
        sizer_v.Add(self.button1, 0, flag=wx.ALL, border=50)
        self.SetSizer(sizer_v)
        # size the frame so all the widgets fit
        self.Fit()

    def button1Click(self, event):
        """button1 has been left clicked"""
        # self is instance of frame1
        self.Hide()
        self.frame2.Show()


class Frame2(wx.Frame):
    def __init__(self, parent, mytitle, frame1):
        wx.Frame.__init__(self, parent, -1, mytitle)
        self.SetBackgroundColour("brown")
        self.frame1 = frame1

        # create input widgets
        self.button1 = wx.Button(self, -1, label='show Frame1')
        # bind mouse event to an action
        self.button1.Bind(wx.EVT_BUTTON, self.button1Click)
        # optional respond to exit symbol x on frame2 title bar
        #self.Bind(wx.EVT_CLOSE, self.button1Click)

        # use a box sizer to lay out widgets
        sizer_v = wx.BoxSizer(wx.VERTICAL)
        # Add(widget, proportion, flag, border)
        sizer_v.Add(self.button1, 0, flag=wx.ALL, border=50)
        self.SetSizer(sizer_v)
        # size the frame so all the widgets fit
        self.Fit()

    def button1Click(self, event):
        """button1 has been left clicked"""
        # self is instance of frame2
        self.Hide()
        self.frame1.Show()


app = wx.App(0)
# create a MyFrame instance and show the frame
frame1 = Frame1(None, 'Frame1')
frame1.Show()
app.MainLoop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Well the book that I have is called "How to think like a Computer Scientist: Learning with Python" Printed in 2002. The version of Python on my computer is Python 3.0 IDLE(GUI). What version would you say the example that I posted from the book is in?

Thank you

If you want to follow the examples in that tutorial, then you may be better off using Python2.5. Python3.0 does make quite a number of significant changes to the syntax. If you have a Windows computer, you can download portable python version 2.5 and install it on a USB flash drive, an inexpensive 256M drive will do.

Portable Python is free from:
http://www.portablepython.com/releases/

Portable Python 1.1 based on Python 2.5.4 installs:
Python 2.5.4
Django-1.0.2-final (for web development)
IPython-0.9.1
Matplotlib-0.98.5.2 ( for graphic plotting)
Numpy-1.2.1 (for high speed arrays)
PIL-1.1.6 (for image manipulation)
Py2exe-0.6.9 (packed python code to .exe files)
PyGame-1.8.1 (the python game toolkit)
PyReadline-1.5
PyScripter v1.9.9.6 (a very nice IDE to write programs with)
PyWin32-212 (window extension library)
Rpyc-2.60 (remote python)
Scipy-0.7.0b1 (a high speed scientific toolkit)
SPE-0.8.4.c (another very nice IDE)
VPython-3.2.11 (for 3D scientific modeling)
wxPython-unicode-2.8.9.1 (a popular GUI toolkit)

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just a table of ASCII characters ...

# print a 16 column table of ASCII characters from 0 to 127

# dictionary of non-printable asccii characters
controls_dic = {
0: 'NUL', 1: 'SOH', 2: 'STX', 3: 'ETX', 4: 'EOT', 5: 'ENQ', 6: 'ACK',
7: 'BEL', 8: 'BS', 9: 'HT', 10: 'LF', 11: 'VT', 12: 'FF', 13: 'CR',
14: 'SO', 15: 'SI', 16: 'DLE', 17: 'DC1', 18: 'DC2', 19: 'DC3',
20: 'DC4', 21: 'NAK', 22: 'SYN', 23: 'ETB', 24: 'CAN', 25: 'EM',
26: 'SUB', 27: 'ESC', 28: 'FS', 29: 'GS', 30: 'RS', 31: 'US'
}

n = 1
for k in range(0, 128):
    if k < 32:
        s = controls_dic[k]
    else:
        s = chr(k)
    if n % 16 > 0:
        print "%4s" % s,
    else:
        print "%4s" % s
    n += 1
sneekula commented: very useful! +8
Ene Uran commented: great stuff +7
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Some days you're the dog - some days you're the hydrant.
-- Unknown

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Anyone who has never made a mistake has never tried anything new.
-- Albert Einstein

jalpesh_007 commented: good one.. +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Once harm has been done, even a fool understands it.
-- Homer

Ene Uran commented: great +0
jingda commented: Nice +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

In 2001 "Star Trek The Motion Picture" brought up a living machine so big that we couldn't fathom it.

Then who could forget HAL in "2001 SO"?

jephthah commented: 2001: kubrick meets clarke. win + win. +10
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The { and } keys.

Hmm, maybe you inherited the keyboard from a Pascal, Java, C#, C or C++ programmer. My first intro to the {} pair was with Pascal comments.

On my own keyboard it must be the space bar. Any lettering is totally worn off! :)

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This code sample shows you how to select and display multiple lines from a Tkinter Listbox ...

# a simple Tkinter Listbox example
# press the shift or ctrl key to select multiple items
# source: snee

import Tkinter as tk

def get_list():
    """
    function to read the listbox selection(s)
    (mutliple lines can be selected)
    and put the result(s) in a label
    """
    # tuple of line index(es)
    sel = listbox.curselection()
    # get the text, might be multi-line
    seltext = '\n'.join([listbox.get(x) for x in sel])
    label_text.set(seltext)

root = tk.Tk()
# used for label text
label_text = tk.StringVar(root)

# extended mode allows CTRL/SHIFT mouse selections
listbox = tk.Listbox(root, selectmode=tk.EXTENDED)
listbox.pack()

# click the button to show the selection(s)
button = tk.Button(root, text="Get Selection(s)", command=get_list)
button.pack()

# used to display selection(s)
label = tk.Label(root, textvariable=label_text)
label.pack()

# load some datalines into the listbox
items = ["one", "two", "three", "four", "five", "six"]
for item in items:
    listbox.insert(tk.END, item)

# highlight/preselect line 3 of listbox (starts with zero)
# lb.selection_set(first, last=None) can preselect more than 1 line
listbox.selection_set(3)

root.mainloop()

Left mouse click with and without pressing the SHIFT or CTRL key to see how the multiple selection works.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Ignorance is bliss
Apathy is a mental illness

Ancient Dragon commented: nice :) +36
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Today it be the usual grilled salmon with spinach-olive rice. :)

William Hemsworth commented: Mmmm. +10
Sulley's Boo commented: yummm fish *_* +6
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

One of my standard test programs for any GUI toolkit, creating, loading a listbox and selecting an item. Here is the PyQT code ...

# a simple window using PyQT 
# with a button and a listbox to load and select

import sys
# might be easier to use this import option
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyForm(QWidget):
    def __init__(self, name_list):
        QWidget.__init__(self)
        # setGeometry(x_pos, y_pos, width, height)
        self.setGeometry(100, 150, 300, 220)
        self.setWindowTitle("Load the listbox first")
        
        # make name_list available for methods
        self.name_list = name_list

        # use a grid layout for the widgets
        grid = QGridLayout()

        btn_load = QPushButton("Load List")
        # bind the button click to a function reference
        self.connect(btn_load, SIGNAL("clicked()"), self.on_click)
        
        self.listbox = QListWidget()
        self.connect(self.listbox, SIGNAL("itemSelectionChanged()"), self.on_select)
        
        # addWidget(widget, row, column, rowSpan, columnSpan)
        grid.addWidget(btn_load, 0, 0, 1, 1)
        # listbox spans over 5 rows and 2 columns
        grid.addWidget(self.listbox, 1, 0, 5, 2)
        self.setLayout(grid)
    
    def on_click(self):
        """the load button has been clicked, load the listbox"""
        self.listbox.addItems(self.name_list)
    
    def on_select(self):
        """an item in the listbox has been clicked/selected"""
        selected_name =  self.listbox.selectedItems()[0].text()
        self.setWindowTitle(selected_name)
        

name_list = [
"Erich Meitinger",
"Udo Baus",
"Jens Klein",
"Bjorn Bork",
"Heidrun Lovelace",
"Klaus Abraham",
"Ulla Jorgens",
"Volger Jenkings",
"Helmut Schmidt",
"Freja Larse",
"Larry Orkan",
"Andreas Mauser",
"Harry Heimlich"
]

app =  QApplication(sys.argv)
form = MyForm(name_list)
form.show()
app.exec_()

I do miss the colors. Here is the corresponding wxPython code with some colors added ...

# a simple window using wxPython 
# with a button and a listbox to load and select

import wx

class MyFrame(wx.Frame): …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

PyQT was no problem on Windows XP. I downloaded and installed:
http://www.riverbankcomputing.com/static/Downloads/PyQt4/PyQt-Py2.5-gpl-4.4.3-1.exe

The cumbersome split between QtCore and QtGui is made simpler if you use the import statements show below ...

# a simple window using PyQT 
# with 2 buttons and a label

import sys
# might be easier to use this import option
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyForm(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        # setGeometry(x_pos, y_pos, width, height)
        self.setGeometry(100, 150, 320, 100)
        self.setWindowTitle("A simple window")

        # use a grid layout for the widgets
        grid = QGridLayout()

        btn_hello = QPushButton("Hello")
        # bind the button click to a function reference
        self.connect(btn_hello, SIGNAL("clicked()"), self.on_click)
        
        btn_quit = QPushButton("Quit")
        self.connect(btn_quit, SIGNAL("clicked()"), app.quit)
        
        self.label = QLabel("-------------")

        # addWidget(widget, row, column, rowSpan=1, columnSpan=1)
        grid.addWidget(btn_hello, 0, 0)
        # this will span the label over 3 columns
        grid.addWidget(self.label, 1, 0, 1, 3)
        grid.addWidget(btn_quit, 2, 0)

        self.setLayout(grid)
    
    def on_click(self):
        self.label.setText("You clicked the Hello button!")


app =  QApplication(sys.argv)
form = MyForm()
form.show()
app.exec_()

This little PyQT template can be used for quite a few basic programs. Now, if I could introduce some color! Hey, I am a slow learner!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Thanks for the sample code and the nice picture. I thought I should add pyglet, which is an audio-visual module using GL and FFmpeg available for Windows and Unix systems ...

# show an image using pyglet
# download pyglet from: http://www.pyglet.org/download.html
# (the event handler is attached via a function decorator)

import pyglet

# pick an image file you have in the working directory, or give
# the full path, can be a .jpg, .png, ,gif, .bmp image file
# (I understand filenames are case sensitive on Linux)
image_file = 'LAKE2.gif'
img = pyglet.image.load(image_file)

# create and size the window to the picture size + 
# a small frame around it
w = img.width + 10
h = img.height + 10
win = pyglet.window.Window(width=w, height=h)

# give the window a title
win.set_caption(image_file)

@win.event
def on_draw():
    win.clear()
    # draw image in window at coordinates x=5, y=5
    # note that coordinates start at lower left corner 
    img.blit(5, 5)

pyglet.app.run()

Pyglet is not a full GUI toolkit, but has its strength in audio and video presentations.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This 'sticky' thread is for working examples of Python GUI code. Note that most wxPython examples have their own thread.

Please use comments in your code to help the reader.

The example code should be usable as a template, so folks get a feel for the toolkit and can use those examples/templates as a basis for more complex programs.

We also welcome code that compares the various GUI toolkits.

Again, don't clutter up the sticky with questions. Ask question in the regular forum.

A brief history of GUI based Operating Systems migh be in order:
The first Graphical User Interface (GUI)) consisting of graphical elements such as windows, menus, radio buttons, check boxes and icons was developed by Xerox. Xerox created an integrated Operating System (OS) based in this. It allowed the use of a keyboard and a pointing device.

Apple in the early 1980s improved the GUI based OS, followed by Atari, Microsoft and IBM. Apple's Mac OS X uses a Unix-like OS as a base, and Microsoft's Windows sits on top of the original MS DOS. The first successful MS Windows version was Windows 3.0 (1990). The open source Linux OS (also a Unix-like OS) had people develop GUIs like KDE (1996, QT based) and GNOME (1997).

Here is a general discussion of some Python GUI toolkits: http://en.wikibooks.org/wiki/Python_Programming/GUI_Programming

For a typical installation of PyGame and PyQT for Windows see:
http://www.daniweb.com/software-development/python/threads/355545/1519470#post1519470

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A clean house is the sign of a broken computer.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can use the local dictionary vars() to introduce variables into strings ...

# using the local dictionary vars() to put
# variables into strings

name = "Harry"
name2 = "Verderchi"

for i in range(1, 5):
    # %d for integers and %s for strings
    print( "#%(i)d: %(name)s %(name2)s" % vars() )

"""
my result  -->
#1: Harry Verderchi
#2: Harry Verderchi
#3: Harry Verderchi
#4: Harry Verderchi
"""

String templating was introduced in Python 2.4 ...

# using string.Template() and the local dictionary vars()
# for formatted printing

import string

name = "Harry"
name2 = "Verderchi"

# create the template (note the $ before each variable name)
t = string.Template("#$i: $name $name2")

for i in range(1, 5):
    # use safe_substitute() for potential missing variables
    print( t.safe_substitute(vars()) )

"""
my output -->
#1: Harry Verderchi
#2: Harry Verderchi
#3: Harry Verderchi
#4: Harry Verderchi
"""

If you want to know what vars() looks like, just print it.

Nick Evan commented: Random rep for effort in this thread +17
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

One way to approach multidimensional arrays in Python is to use a dictionary container with the index tuple as a key ...

# create a 3x4x2 3D-array using a dictionary with index tuples as keys
# initialize values to zero
arr3d = dict([((x,y,z), 0) for x in range(3) for y in range(4) 
    for z in range(2)])

# Python3 has dictionary comprehension to simplify this
#arr3d = {(x,y,z):0 for x in range(3) for y in range(4) for z in range(2)} 

# sorts the key index tuples
for ix in sorted(arr3d):
    print( "ix=%s val=%s" % (ix, arr3d[ix]) )

print('-'*20)

# change some values, basically assign to index
arr3d[2, 1, 0] = 5
arr3d[1, 0, 1] = 17
# or ...
ix = (0, 0, 0)
arr3d[ix] = 9
# or just ...
ix = 1, 1, 1
arr3d[ix] = 3

for ix in sorted(arr3d):
    print( "ix=%s val=%s" % (ix, arr3d[ix]) )
    
print('-'*20)

# get a specific value from a given index
print(arr3d[1, 1, 1])  # 3
# or ... 
ix = 0, 0, 0
print(arr3d[ix])  # 9

print('-'*20)

# get the lowest and highest key
low = (min(arr3d.keys()))    # --> (0, 0, 0) 
heigh = (max(arr3d.keys()))  # --> (2, 3, 1)
# show values
print( "ix=%s val=%s" % (low, arr3d[low]) )
print( "ix=%s val=%s" % (heigh, arr3d[heigh]) )

# get the heighest value in the array
print(max(arr3d.values()))  # 17

"""
my result -->
ix=(0, 0, 0) val=0
ix=(0, 0, 1) val=0
ix=(0, 1, 0) val=0
ix=(0, 1, 1) val=0
ix=(0, 2, …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you have .NET installed on your Windows machine, or Mono on your Linux machine you can use those libraries to run IronPython ...

# create a window with 2 buttons using ironpython
# experiment with events, colors, styles
# ironpython gives access to the Windows .NET or Linux Mono libraries
# download ironpython from:
# http://ironpython.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=12481
# tutorial at:
# http://www.zetcode.com/tutorials/ironpythontutorial/
#
# if ironpython is installed in 'C:\IronPython 2.0.1\' and you save this script
# as 'ip_Buttons2.py' in subdirectory 'Atest' then you can run it with command:
# C:\IronPython 2.0.1\ipy.exe C:\IronPython 2.0.1\Atest\ip_Buttons2.py

import clr

clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")

from System.Windows.Forms import Application, Form, Button
from System.Windows.Forms import FlatStyle
from System.Drawing import Size, Point, Color

class IForm(Form):

    def __init__(self):
        # set form title, position, size, bachground color
        self.Text = 'Button'
        self.CenterToScreen()
        self.Size = Size(300, 150)
        self.BackColor = Color.Green

        btn1 = Button()
        btn1.Parent = self
        btn1.Text = "Quit"
        btn1.Location = Point(50, 30)
        btn1.BackColor = Color.Pink
        # click on the button to call btn1_OnClick()
        btn1.Click += self.btn1_OnClick

        btn2 = Button()
        btn2.Parent = self
        btn2.Text = "Press Me"
        btn2.Location = Point(50, 70)
        btn2.FlatStyle = FlatStyle.Popup
        btn2.BackColor = Color.Linen
        # click on the button to call btn2_OnClick()
        btn2.Click += self.btn2_OnClick

    def btn1_OnClick(self, sender, args):
        self.Close()

    def btn2_OnClick(self, sender, args):
        self.Text = 'btn2 pressed'
        # test information ...
        print sender
        print sender.Text, type(sender.Text)


Application.Run(IForm())

Familiar with C#? IronPython is basically Python, but has a little C# thrown in.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you experienced the clumsiness of Windows Vista, Unix or Linux is a breath of fresh air! We need a book titled:
"The Vista Haters' Handbook"

tux4life commented: Yeah, but the difference between the two is that the Vista Hater's Book will be filled up with real facts and the Unix Hater's Book is just rubbish :P +3
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Try this ...

import random

n = 5
# list with unique elements
print(random.sample(range(1, 11), n))

print('-'*20)

# list with non-unique elements
print([random.randint(1, 10)for k in range(n)])

"""
my random output -->
[1, 6, 3, 5, 10]
--------------------
[5, 2, 6, 5, 9]
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I simply wrote a small Python program to run with Python30 to convert some of my Python25 files ...

# run_2to3_convert.py
#
# convert a Python25 code file to a Python30 code file
# generates a backup file and overwrites the original
# file with the converted file
#
# it is best to put this file into a special directory
# together with the Python25 file you want to convert
#
# run this program with Python30

import subprocess

# the Python2x code file you want to convert ...
python2x_scriptfile = "TryExcept1.py"

subprocess.call([r"C:\Python30\Python.exe",
    r"C:\Python30\Tools\Scripts\2to3.py",
    "-w",
    python2x_scriptfile])

Also handles Tkinter GUI programs well.

leegeorg07 commented: thanks great code +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Give this a try to include image files and all into one exe file ...

"""
Py2ExeWinSetup.py

Py2Exe (version 6.6 and higher) setup file for windows/GUI programs.
Creates a single .exe file.

Simply add this file into the same folder with the source file.
Change your source filename at the bottom to whatever you called your 
code file.  Now run Py2ExeWinSetup.py ...

Two subfolders will be created called build and dist.
The build folder is for info only and can be deleted.
Distribute whatever is in the dist folder.

The dist folder contains your .exe file, any data files you specified
in "data_files =", MSVCR71.dll and w9xpopen.exe

Your .exe file contains your code as . pyo optimized byte code files, 
all needed modules and the Python interpreter (as a Pythonxx.dll).
MSVCR71.dll can be distributed, but is often already in the system32 
folder. 
w9xpopen.exe is needed for os.popen() only, can be deleted otherwise.
"""


from distutils.core import setup
import py2exe
import sys

sys.argv.append("py2exe")
sys.argv.append("-q")

setup(
  options = {"py2exe": {"compressed": 1,
                        "optimize": 2,
                        "ascii": 1,
                        "bundle_files": 1}},
  zipfile = None,
  # to add .dll or image files use list of filenames
  # these files are added to the dir containing the exe file
  data_files = ['apple.jpg', 'cheese.jpg'],

  # replace 'pyg_Image3.py' with your own code filename
  # (replace windows with console for a console program)
  windows = [{"script": 'pyg_Image3.py'}]
)

Yes, zipfile=None is important if you just want one exe file with everything in it! Haven't totally tested the code, so you …

lllllIllIlllI commented: Ooh, i like! :) +2
Nick Evan commented: thanks, I've been looking for something like this! +15
sneekula commented: nice example code +6
tux4life commented: Nice !! :) +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Hint:
Recursive functions call themselves, basically form a loop

Your function definition should look like:
def summer(n, mysum=0):

You are summing from the top down. Each recursion you add n to mysum and decrease n by 1. So your recursive call becomes
return summer(n-1, mysum+n)

You loop until n drops to zero, then you return mysum. That's where an if/else is used.

Your initial function call is something like
mysum = summer(5)
if you want to sum up integers 1 to 5.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

BeautifulSoup works fine with Python30 if you
copy
BeautifulSoup.py (version3.0.7a or lower)
and
sgmllib.py (find it typically in C:\Python25\Lib)
to a separate directory and convert both programs with 2to3.py

This rather obvious approach was overlooked by the BeautifulSoup folks.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

April 1 is just around the corner, and it has come to my attention that the brains behind MicroSoft have used this simple Python program to determine the release number of the next Windows version ...

# name the next Windows version ...

def next_version(release_list):
    j = ",".join(release_list)
    s = sum([x.isdigit() for x in j])
    return sum(map(int, str(s)))


release_list = ['1.0', '2.0', '2.1x', '3.0', '3.1', '3.5', '3.51',
    '4.0', '95', '98', 'ME', 'NT', '2000', 'XP', 'Vista']

print( "The next Windows version is %s" % next_version(release_list) )
Nick Evan commented: :) +14
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You want to go into a circle so you get printable characters. Here is an example of Python's builtin rotation encoder, it starts in the middle of the 26 alpha character sets ...

# example of simple encoding/decoding using Python's 'rot13'
# alphabet is shifted by 13 positions to nopqrstuvwxyzabcdefghijklm
# so original 'a' becomes 'n' or 'A' becomes 'N' and so on 
# (non-alpha characters are not affected)

text = "Peanuts88-q"
print "original =", text

encoded = text.encode('rot13')
print "encoded  =", encoded

decoded = encoded.encode('rot13')
print "decoded  =", decoded

"""
output -->
original = Peanuts88-q
encoded  = Crnahgf88-d
decoded  = Peanuts88-q
"""
Gribouillis commented: I didn't know the "rotation encoder" ! +2
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is an example ...

# show the list of (r, g, b) tuples of a bitmap image

from PIL import Image

img = Image.open("FrenchFlag.bmp")
data = img.getdata()

#show a list of (r, g, b) tuples
print(list(data))

"""
partial output -->
[(6, 0, 240), (6, 0, 240), (6, 0, 240), (6, 0, 240),
(6, 0, 240), (6, 0, 240), (6, 0, 240), (85, 81, 244),
(253, 252, 255), (255, 255, 255),(255, 255, 255), (255, 255, 255),
(255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255),
(255, 255, 255), (255, 251, 251), (244, 71, 67), (240, 6, 0),
(240, 6, 0), (240, 6, 0), (240, 6, 0), (240, 6, 0), (240, 6, 0), (
240, 6, 0), (6, 0, 240), ...]
"""

Now you can search/process the list for any unusual (r, g, b) tuple.

kiddo39 commented: Always very helpful +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Q: a function with two positional parameters that returns two values (both integers or real numbers)
A: hint, your function receives two values, let's say x, y and does some calculations on each and returns the changed values

Q: a function which generates random numbers and returns them (any amount you want)
A: hint, since you may want more than one random number, best to return a list of random numbers

Q: a function with one parameter, which it gets from a random number generator, that returns two values (strings are returned)
A: hint, take the first element from your returned r_list and pass it as the argument to a function that incorporates this number into two different strings then return the two strings

For instance if your random number is r, then create two silly strings:
s1 = "I won $" + str(r) + " in the lottery!"
s2 = "I plan to retire at age " + str(r)

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The function s.strip() will do ...

s = repr("callbackfunctionname({'Last': 'Doe', 'First': 'John'})")

print s
# remove leading and trailing character '"'
print(s.strip('"'))

"""
my output -->
"callbackfunctionname({'Last': 'Doe', 'First': 'John'})"
callbackfunctionname({'Last': 'Doe', 'First': 'John'})
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can use a list comprehension to speed things up ...

# create a list of indexes for spaces in a text

text = "According to Sigmund Freud fuenf comes between fear and sex."
space_ix = [ix for ix, c in enumerate(text) if c == " "]
print(space_ix)  # [9, 12, 20, 26, 32, 38, 46, 51, 55]
wheatontrue commented: Very helpful +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here we develop the concept of a standard deviation of a set of numbers following the steps outlined in the wikipedia reference. Python is really well suited for that sort of thing ...

# Suppose we wished to find the standard deviation of the data set
# consisting of the values 3, 7, 17, and 19
q = [3, 7, 17, 19]

# Step 1: find the arithmetic mean (average) of 3, 7, 17, and 19
avg = float(sum(q))/len(q)
print(avg)  # --> 11.5
 
# Step 2: find the deviation of each number from the mean or avg
dev = []
for x in q:
    dev.append(x - avg)
print(dev)  # --> [-8.5, -4.5, 5.5, 7.5]

# Step 3: square each of the deviations,
# which amplifies large deviations and makes negative values positive
sqr = []
for x in dev:
    sqr.append(x * x)
print(sqr)  # --> [72.25, 20.25, 30.25, 56.25]
 
# Step 4: find the mean (average) of those squared deviations
mean = sum(sqr)/len(sqr)
print(mean)  # --> 44.75
 
# Step 5: take the square root of the quotient
# (converting squared units back to regular units)
standard_dev = mean**0.5
print( "the standard deviation of set %s is %f" % (q, standard_dev) )

"""
final result -->
the standard deviation of set [3, 7, 17, 19] is 6.689544
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You could convert the list to a string and use slice ...

q = [23, 'CL', '006', '2004', 'DBA8ORPU', '41', '8Y', 'S0111P', '2']

# slice off first and last character
str_q = str(q)[1 : -1]
print(str_q)

"""
my result -->
23, 'CL', '006', '2004', 'DBA8ORPU', '41', '8Y', 'S0111P', '2'
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Are human beings the only living things that try to make sense out of the universe?

William Hemsworth commented: Nice ;] +6
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The Tkinter widget Label has a default border width of 2, so use bd=0 like shown here:
heading = tk.Label(self.heading_frame, image=savvy_bar1, bd=0)

scru commented: his rep doesn't work +4
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I never knew what real happiness was until I got married, and by then it was too late.

William Hemsworth commented: Hah! :) +6
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Please do not call your program the same name as a module, Python will load the program first at the import statement! In this case pygame.py, so delete that program name from your work directory and name it something else like my_pygame1.py.

This goes for other import modules like random, beginners often call their random test program 'random.py', that will flop!

Thanks for postig the whole error traceback, I couldn't have figured it out without.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The stable version of Python30 has been released, there are a number of critical changes to the syntax. Here is a look at the new print() that replaces the print statement ...

# in Python30 the print statement has been replaced with
# the Python30 print() function
# print([object, ...][, sep=' '][, end='n'][, file=sys.stdout]) 
# formatting can be done with string.format()

import math

print(123)  # 123 followed by newline, end='\n' is default
print()     # newline
print('hello', end=' ') # ends with a space rather then a newline
print('world')          # hello world
print()

# string is default and does not have a type specifier
# {0} and {1} index the format args
sf = 'the {0} jumped over the {1}!'
print(sf.format('mouse', 'moon'))

# allow 10 char spaces, left align (<) is default
print('the {0:10} jumped over the {1:10}!'.format('mouse', 'moon'))
# use right align (>)
print('the {0:>10} jumped over the {1:>10}!'.format('mouse', 'moon'))

"""
result =
the mouse jumped over the moon!
the mouse      jumped over the moon      !
the      mouse jumped over the       moon!
"""

print('-'*42)  # prints 42 dashes

# float formatting with type specifier f
print('x = {0:5.3f}'.format(1234.567))     # x = 1234.567
print('x = {0:12.9f}'.format(1234.567))    # x = 1234.567000000
print('x = {0:-12.9f}'.format(1234.567))   # x = 1234.567000000
print('x = {0:+12.9f}'.format(1234.567))   # x = +1234.567000000
print('x = {0:+12.9f}'.format(-1234.567))  # x = -1234.567000000
print('x = {0:012.3f}'.format(1234.567))   # x = 00001234.567
print()
print('x = {0:1.5e}'.format(1234.567))     # x = 1.23457e+03
print('x = {0:1.5e}'.format(0.000001234))  # x = 1.23400e-06
print('x = {0:1.5g}'.format(0.000001234))  # x = 1.234e-06 …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Which editor are you using. My guess is that you are using PyScripter.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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?

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Peace on Earth and lower taxes to everybody!

Alex Edwards commented: That sounds more like a dream than a wish, but that would be great if it happened! =) +4
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Happy dog?

William Hemsworth commented: awwh :) +4
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Q: "How many Californians does it take to screw in a light bulb?"
A: "Californians don't screw in light bulbs they screw in hot tubs."

tiger86 commented: ROFL some californians! +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The Tkinter GUI toolkit, that normally comes with the Python installation, contains a turtle module that allows you to draw items with a turtle along the lines of the old logo language.

First draw a simple line ...

# module turtle is part of Tkinter
# turtle starts in the center of canvas (0, 0) by default
# draw a turtle line in a given direction and length

import turtle
import time

tp = turtle.Pen()
# optional pen color
# use (r, g, b) tuple
# colors r, g, b have values of 0.0 to 1.0
# default is black (0, 0, 0), (0, 0, 1.0) is blue
tp.color(0, 0, 1.0)

# from the center go to the right for 150 pixels
tp.right(0)
tp.forward(150)

# show the result for 3 seconds
time.sleep(3)

Something more elaborate, using a loop to draw a square ...

# module turtle is part of Tkinter
# turtle starts in the center of canvas (0, 0) by default
# draw 4 turtle lines to form a square

import turtle
import time

tp = turtle.Pen()

# optional pen color
tp.color('red')

# form a square by drawing 4 lines of 100 pixels length
# changing the direction by 90 degrees (360/4) each time
for k in range(4):
    tp.right(90)
    tp.forward(100)

# show the result for 3 seconds
time.sleep(3)

Looky here, a simple pentagon adopting the square drawing approach ...

# module turtle is part of Tkinter
# turtle starts in the center of canvas (0, …