How would you write a number (integer) using English words? Here is one way, and to keep it simple let's just use numbers from 1 to 999.

``````# write a number from 1 to 999 in English words

ones = ["", "one ","two ","three ","four ", "five ",
"six ","seven ","eight ","nine "]

tens = ["ten ","eleven ","twelve ","thirteen ", "fourteen ",
"fifteen ","sixteen ","seventeen ","eighteen ","nineteen "]

twenties = ["","","twenty ","thirty ","forty ",
"fifty ","sixty ","seventy ","eighty ","ninety "]

# your test number between 1 and 999
n = 123

# separate into ones, tens/twenties, hundreds
b1 = n % 10
b2 = (n % 100)//10
b3 = (n % 1000)//100

print b1, b2, b3  # test, for n = 123 should show 3 2 1

nw = ""
# no tens/twenties
if b2 == 0:
nw = ones[b1] + nw
# we have tens
elif b2 == 1:
nw = tens[b1] + nw
# we have twenties etc.
elif b2 > 1:
nw = twenties[b2] + ones[b1] + nw
# we have hundreds
if b3 > 0:
nw = ones[b3] + "hundred " + nw

print nw  # test 123 --> one hundred twenty three``````

Just another word frequency program that shows you how to sort the output by frequency:

``````# count words in a text and show the first ten items
# by decreasing frequency using a list of tuples

# sample text for testing (could come from a text file)
text = """\
My name is Fred Flintstone and I am a famous TV
star.  I have as much authority as the Pope, I
just don't have as many people who believe it.
"""

word_freq = {}

word_list = text.split()

for word in word_list:
# word all lower case
word = word.lower()
# strip any trailing period or comma
word = word.rstrip('.,')
# build the dictionary
count = word_freq.get(word, 0)
word_freq[word] = count + 1

# create a list of (freq, word) tuples for sorting by frequency
freq_list = [(freq, word) for word, freq in word_freq.items()]

# sort the list by the first element in each tuple (default)
freq_list.sort(reverse=True)

print "The ten most frequent words are:"
for n, tup in enumerate(freq_list):
# print the first ten items
if n < 10:
freq, word = tup
print freq, word

"""
my output -->
The ten most frequent words are:
3 i
3 as
2 have
1 who
1 tv
1 the
1 star
1 pope
1 people
1 name
"""``````

Another word frequency program, but this time we want ot create a dictionary of provider:frequency pairs from a number of given email addresses:

``````# count the frequency of providers from a number of given emails

emails = """\
manolis@gmail.com
giannis@gmail.com
kostas@yahoo.com
eirini@yahoo.com
ssss@aol.com
wertza@yahoo.gr
xristhanthi@gmail.com
"""

# split into list of lines (individual email)
lines = emails.split()

provider_freq = {}
for item in lines:
# split each line item at the @ character
user, provider = item.split('@')
#print user, provider  # test
# build the dictionary
count = provider_freq.get(provider, 0)
provider_freq[provider] = count + 1

print provider_freq

"""
my output -->
{'yahoo.com': 2, 'aol.com': 1, 'gmail.com': 3, 'yahoo.gr': 1}
"""``````
commented: very nice code +8

If you just want to count the words, lines and characters in a text file, Python offers an elegant solution:

``````# find the number of lines, words and characters in a text file

# these are the counters, start at zero
number_lines = 0
number_words = 0
number_characters = 0

# pick a text file you have
filename = 'my_text.txt'
for line in file(filename):
# update the counters
number_lines += 1
number_words += len(line.split())
number_characters += len(line)

print filename, 'has:'
print number_lines, 'lines'
print number_words, 'words'
print number_characters, 'characters'``````

Thanks to bgeddy for his inspiring pseudo code.

commented: Another example of clean code +8

Here is an example how to use Python25's new partial function in a Tkinter callback situation ...

``````# a tiny Tkinter calculator showing the
# use of the new Python25 partial function

import Tkinter as tk
from functools import partial  # needs Python25 or higher

def click(key):
global memory
if key == '=':
# avoid division by integer
if '/' in entry.get() and '.' not in entry.get():
entry.insert(tk.END, ".0")
# guard against the bad guys abusing eval()
str1 = "-+0123456789."
if entry.get() not in str1:
entry.insert(tk.END, "first char not in " + str1)
# here comes the calculation part
try:
result = eval(entry.get())
entry.insert(tk.END, " = " + str(result))
except:
entry.insert(tk.END, "--> Error!")
elif key == 'C':
entry.delete(0, tk.END)  # clear entry
elif key == '->M':
memory = entry.get()
# extract the result
if '=' in memory:
ix = memory.find('=')
memory = memory[ix+2:]
root.title('M=' + memory)
elif key == 'M->':
entry.insert(tk.END, memory)
elif key == 'neg':
if '=' in entry.get():
entry.delete(0, tk.END)
try:
if entry.get() == '-':
entry.delete(0)
else:
entry.insert(0, '-')
except IndexError:
pass
else:
# previous calculation has been done, clear entry
if '=' in entry.get():
entry.delete(0, tk.END)
entry.insert(tk.END, key)

root = tk.Tk()
root.title("My Calculator PF")

# this also shows the calculator's button layout
btn_list = [
'7',  '8',  '9',  '*',  'C',
'4',  '5',  '6',  '/',  'M->',
'1',  '2',  '3',  '-',  '->M',
'0',  '.',  '=',  '+',  'neg' ]

# create all buttons with a loop
r = 1
c = 0
for b in btn_list:
rel = 'ridge'
cmd = partial(click, b)  # function click and argument b
tk.Button(root,text=b,width=5,relief=rel,command=cmd).grid(row=r,column=c)
c += 1
if c > 4:
c = 0
r += 1

# use Entry widget for an editable display
entry = tk.Entry(root, width=33, bg="yellow")
entry.grid(row=0, column=0, columnspan=5)

root.mainloop()``````

Just a short Python code to show you how to use module urllib and module re to extract information from the html code of a web page. In this case we want to find all the links contained in the html code ...

``````# extract the links in a web page's html code

import urllib
import re

# connect to url
fp = urllib.urlopen(url)
# use regex module re to extract links in the html code

# use the url of a web page you know
url = 'http://www.python.org'

"""
my output -->
http://www.w3.org/1999/xhtml
http://www.python.org/channews.rdf
http://python-groups.blogspot.com/feeds/posts/default
http://www.awaretek.com/python/index.xml
...
...
http://www.swa.hpi.uni-potsdam.de/dls/dls08/
http://www.xs4all.com/
http://www.pollenation.net/
"""``````

Python makes it easy to compare two files and check if they are equal or differ:

``````# compare two files and check if they are equal
# files can be binary or text based

import filecmp

# pick two files you want to compare ...
file1 = "Boing1.wav"
file2 = "Boing2.wav"
if filecmp.cmp(file1, file2):
print "Files %s and %s are identical" % (file1, file2)
else:
print "Files %s and %s differ!" % (file1, file2)``````

A simple way to make a scrolling text ticker or marquee ...

``````# using Tkinter to create a marquee/ticker
# uses a display width of 20 characters
# not superly smooth but good enough to read

import Tkinter as tk
import time

root = tk.Tk()

# width=width chars, height=lines text
text = tk.Text(root, width=20, height=1, bg='yellow')
text.pack()

# use a proportional font to handle spaces correctly
text.config(font=('courier', 24, 'bold'))

s1 = "I was wondering how someone would go about making a scrolling ticker"

# pad front and end with 20 spaces
s2 = ' ' * 20
s = s2 + s1 + s2

for k in range(len(s)):
# use string slicing to do the trick
ticker_text = s[k:k+20]
text.insert("1.1", ticker_text)
root.update()
# delay by 0.15 seconds
time.sleep(0.15)

root.mainloop()``````

Simple debugging using the Python debug module pdb:

``````# test the built-in Python Debugger (Pdb in the Python reference)
# at the debugger's '(Pdb)' prompt you can type  h  for help or
# more specifically use   h step  or   h next

import pdb

#help('pdb')

# once the '(Pdb)' prompt shows, you are in the debugger
# and you can trace through by entering:
#
# next (or n) which goes line by line and does not get
# into functions or into every iteration of a loop
#
# step (or s) which is more detailed and for instance
# loops through an entire range()
#
# so use next to get where you want to be and then use step,
# once you have all the details you need, use next again

pdb.set_trace()

# now you can test the following code ...

def hasCap(s):
"""returns True if the string s contains a capital letter"""
for num in range(65, 91):
capLetter = chr(num)
if capLetter in s:
return True
return False

str1 = 'Only pick up strings without Capital letters!'
str2 = 'only pick up strings without capital letters!'

# test the function hasCap()
if hasCap(str1):
print "str1 has a capital letter"
else:
print "str1 has no capital letter"

if hasCap(str2):
print "str2 has a capital letter"
else:
print "str2 has no capital letter"``````

You need to play with this a little to get familiar with the pdb debugger.

Tkinter only displays gif and ppm images, to show the more popular jpg and png images you have to incorporate the Python image Library (PIL). Here is an example:

``````# load and display an image with Tkinter
# Tkinter only reads gif and ppm images
# use Python Image Library (PIL) for other image formats
# give Tkinter a namespace to avoid conflicts with PIL
# (they both have class Image) PIL is free from:
# http://www.pythonware.com/products/pil/index.htm

import Tkinter as tk
from PIL import Image, ImageTk

root = tk.Tk()
cv1 = tk.Canvas(root, width=500, height=500)
cv1.pack(fill='both', expand='yes')

# open a jpeg file into an image object
# image should be in the source folder or give full path name
image1 = Image.open("flowers.jpg")
# convert image object to Tkinter PhotoImage object
tkimage1 = ImageTk.PhotoImage(image1)

# tk.NW anchors upper left corner of image
# at canvas coordinates x=10, y=20
cv1.create_image(10, 20, image=tkimage1, anchor=tk.NW)

root.mainloop()``````

Get your lotto numbers here, simple with Python:

``````# select 6 unique lotto numbers from 1 - 49

import random

lotto_list = random.sample(range(1, 50), 6)

print lotto_list
print sorted(lotto_list)

"""
possible result --->
[49, 43, 8, 42, 1, 33]
[1, 8, 33, 42, 43, 49]
"""``````

You can run the command window from python and obtain the results and error messages:

``````# run DOS cmd.exe from Python code
# works on XP, but may not work on Windows Vista

import subprocess

cmd = "cmd.exe"
command = "dir c:"

p = subprocess.Popen(cmd,
shell=True,
#bufsize=1,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)

# the \n is important to flush buffer
p.stdin.write("%s\n" % command)

p.stdin.close()
# give it enough time to respond
p.wait()

# optional check (0 = success)
print p.returncode

# read the result to a string
print result

# optionally read any error message returned
print "error =", error``````

Here is an example showing you how to read off a number, in this case a phone number, digit by digit on your computer's sound system. You need to extract the attached Numbers.zip file into your working directory. It contains sound files 0.wav to 9.wav spoken by a pleasant female voice ...

``````# read each digit of a phone number using module pyglet
# soundfiles 0.wav ... 9.wav are in subdirectory num
# extract the Numbers.zip file into your working directory

import pyglet
import time

#window = pyglet.window.Window(640, 480)

# read all the sound sources into a list
sound = []
for n in range(0, 10):
# soundfiles 0.wav ... 9.wav are in subdirectory num
sound_file = "num/%s.wav" % n
#print sound_file

# create an instance of the media player class
# for better control
s = pyglet.media.Player()
# optional volume setting 0.0 to 1.0
s.volume = 0.8

# read out a phone number string
phone_number_str = '734-344-9941'
for n in phone_number_str:
if n.isdigit():
s.queue(sound[int(n)])
s.play()
# give each digit play() time to finish properly
# you might have to experiment with sleep seconds
time.sleep(0.8)
s.next()
time.sleep(0.4)

pyglet.app.run()``````

If you make a copy of a list, and you have a nested list or don't know what the list might be in the your program, always use module copy:

``````# make a true copy of a nested list

import copy

nested_list = [1, [2, 3], 4]
copied_list = copy.deepcopy(nested_list)

# a regular list copy looks alright at first
copied_list2 = nested_list[:]

print nested_list   # [1, [2, 3], 4]
print copied_list   # [1, [2, 3], 4]
print copied_list2  # [1, [2, 3], 4]

print '-'*20

# change the orignal list
nested_list = 99

# but the test shows a surprise!
print nested_list   # [1, [99, 3], 4]
print copied_list   # [1, [2, 3], 4]
# with simple copy the inner list is just an alias
print copied_list2  # [1, [99, 3], 4]  oops!``````

Just a basic Python class example to show you how you can work with it:

``````# basic experiments with Python class

class Cat(object):
# this is public
cost = 100
# this is private to the class
__price = cost + cost * 0.25
# constructor
def __init__(self, num=1):
self.num = num
self.sound = "meow " * self.num
print self.sound

def own(self):
print "I own", self.num, "cats"

def paid(self):
self.total = self.__price * self.num
print "I paid", self.total, "for my cats"

def kitten(self):
self.kit = 5
print "One cat just had", self.kit, "kittens"
return self.kit

class Dog(object):
# this is public
cost = 400
# this is private to the class
__price = cost + cost * 0.25
# constructor
def __init__(self, num=1):
self.num = num
self.sound = "woof " * self.num
print self.sound

def own(self):
print "I own", self.num, "dogs"

def paid(self):
self.total = self.__price * self.num
print "I paid", self.total, "for my dogs"

class Pets(Cat, Dog):
"""class Pets inherits class Cat and class Dog"""
# constructor
def __init__(self):
self.num = cat.num + dog.num
self.sound = cat.sound + dog.sound
print self.sound

def own(self):
print "I own", self.num, "pets"

def paid(self):
print "I paid", dog.total + cat.total, "for my pets"

def update(self):
# notice how Pets inherited kitten() from class Cat
self.kit = self.kitten()
print "So now I have", self.num + self.kit, "pets"

cat = Cat(3)
cat.own()
cat.paid()

print '-'*30

dog = Dog(2)
dog.own()
dog.paid()

print '-'*30

pets = Pets()
pets.own()
pets.paid()

print '-'*30

pets.update()

"""
my output -->
meow meow meow
I own 3 cats
I paid 375.0 for my cats
------------------------------
woof woof
I own 2 dogs
I paid 1000.0 for my dogs
------------------------------
meow meow meow woof woof
I own 5 pets
I paid 1375.0 for my pets
------------------------------
One cat just had 5 kittens
So now I have 10 pets
"""``````
commented: very nice example +8

The module pygame is an SDL based GUI toolkit written for game development. It handles sound, images, animation and drawing objects like lines, circles, polygons. Here is a playful example to give you a taste of pygame code ...

``````# draw random circles with module pygame
# pygame free from: http://www.pygame.org/

import pygame as pg
import random as rn

# color rgb tuples
black = 0, 0, 0
blue = 0, 0, 255
green = 0, 255, 0
olive = 128, 128, 0
orange = 255, 165, 0
magenta = 255, 0, 255
red = 255, 0, 0
yellow = 255, 255, 0
white = 255, 255, 255
color_list = [red, blue, green, yellow, olive, orange, magenta]

# window/screen width and height
w = 500
h = 500
screen = pg.display.set_mode((w, h))
pg.display.set_caption('Draw a number of random circles')
screen.fill(black)

# draw n circles
n = 20
for k in range(n):
x = rn.randint(10, w)
y = rn.randint(10, h)
color = rn.choice(color_list)
position = x, y
# circle border width = 2

# update display
pg.display.flip()

# event loop ...
running = True
while running:
for event in pg.event.get():
# quit when window corner x is clicked
if event.type == pg.QUIT:
running = False``````

The module gasp is a wrapper for pygame with a limited functionality. It is meant for beginners' game development and basic drawing:

``````# using module gasp to draw an arc, a box, plots and circles
#
# info: GASP (Graphics API for Students of Python)
# A library built on pygame that enables absolute beginners to
# write 1980's style arcade games as an introduction to python.
#
# http://dev.laptop.org/pub/gasp/releases/SOURCES/python-gasp-0.1.1.tar.bz2
# unpack python-gasp-0.1.1.tar.bz2 and copy the 'gasp' subdirectory
# into your python path eg. C:\Python25\lib\site-packages\gasp

from gasp import *

# rgb color tuples
black = 0, 0, 0
blue = 0, 0, 255
brown = 165, 42, 42
green = 0, 255, 0
orange = 255, 165, 0
red = 255, 0, 0
white = 255, 255, 255
yellow = 255, 255, 0

begin_graphics()

t = Text("Huston, we have a problem!", (100,420), color=blue, size=40)

# Line(from (x, Y), to (x, y))
q1 = Line((30, 400), (500, 400), color=black)
q2 = Line((30, 395), (500, 395), color=yellow)
q3 = Line((30, 390), (500, 390), color=black)

# Arc(center (x, y), radius, degrees_start, degrees_end)
# degrees relative to x axis (horizontal)
a = Arc((100,200), 100, 30, 330, filled=True, color=red)

# Box(lower_left_corner (x, y), width, height)
b1 = Box((100, 100), 200, 200, color=blue, thickness=5)
b2 = Box((10, 50), 500, 20, filled=True, color=brown)

c1 = Circle((420,200), 100, filled=True, color=green)
c2 = Circle((420,200), 120, color=orange, thickness=5)

# Plot(center (x, y)) a filled rectangle of given size
p1 = Plot((550,380), color=red, size=10)
p2 = Plot((550,60), color=blue, size=10)

sleep(5)  # wait 5 seconds

end_graphics()``````

Editor's note: For module gasp to work you need module pygame installed first.

Easy ways to break out of nested loops came up in the forum, so I played with it a little. Using break will only get you out its associated loop like this example shows ...

``````w = h = d = 10  # for testing
for x in range(0, w):
for y in range(0, h):
for z in range(0, d):
print x, y, z
stop = raw_input("Stop? y/n")
# alas this will only break out of the z loop
if stop == "y":
break``````

One solution would be to put the nested loops into a function and use return to break out ...

``````def nested_loop():
w = h = d = 10  # for testing
for x in range(0, w):
for y in range(0, h):
for z in range(0, d):
print x, y, z
stop = raw_input("Stop? y/n")
if stop == "y":
return

nested_loop()``````

You can also raise an exception to get out ...

``````# use of try/except to exit a nested loop
w = h = d = 10  # for testing
try:
for x in range(0, w):
for y in range(0, h):
for z in range(0, d):
print x, y, z
if raw_input("Stop? y/n") == "y":
raise StopIteration()
except StopIteration:
pass``````

An interesting way to check if a letter is between A and Z:

``````def has_cap(text):
"""return True if text contains a capital letter"""
for ch in text:
# character ch is between A and Z inclusive
if 'A' <= ch <= 'Z':
return True
return False

text1 = 'the Good die young, Pricks live forever!'
text2 = 'the good die young, pricks live forever!'
print 'text1 =', text1
print 'text2 =', text2

# test the function has_cap()
if has_cap(text1):
print "text1 has a capital letter"
else:
print "text1 has no capital letter"

if has_cap(text2):
print "text2 has a capital letter"
else:
print "text2 has no capital letter"``````

One of the features of Python3 will be that the division operator / will give a float result ( // is used for integer divisions as usual ). You can use this feature now by importing the __future__ module. Test it out with this example:

``````# access Python3 features like / for float division

from __future__ import division

print "Enter a math statement like 355/113 or (2+3)/2 ..."
while True:
result = input("Statement: ")
print result
if raw_input("Continue? (y, n)").lower() == 'n': break``````

The module xlrd can read Excel spreadsheets without the use of COM:

``````# module xlrd is used to extract data from Excel spreadsheets.
# Handles older and newer formats. Can be used on any platform.
# Has support for Excel dates and is unicode-aware.
# http://pypi.python.org/pypi/xlrd
# or:
# http://www.lexicon.net/sjmachin/xlrd.htm

import xlrd

# pick an Excel file you have
book = xlrd.open_workbook("myfile.xls")

sheet = book.sheet_by_index(0)

for row in range(sheet.nrows):
print sheet.row(row)``````

very nice information
Thank u....

Thanks for the post!

Sorting lists in Python is simple, but when the list elements are numeric strings like they are in Tkinter or wxPython ListBoxes you need to sort them as floats not strings to make it work properly. Here is an example ...

``````def cmp_float(s1, s2):
"""
s1 and s2 are numeric strings in a list
compare to sort as floats low to high
"""
if float(s1) > float(s2): return 1
elif float(s2) > float(s1): return -1
else: return 0

q = ['4.5', '11.3', '1.6', '9.4', '10.2', '-7.3']

print q
print sorted(q)
# you need to supply a custom compare function
print sorted(q, cmp=cmp_float)

"""
my output -->
['4.5', '11.3', '1.6', '9.4', '10.2', '-7.3'] <-- unsorted
['-7.3', '1.6', '10.2', '11.3', '4.5', '9.4'] <-- sorted as strings
['-7.3', '1.6', '4.5', '9.4', '10.2', '11.3'] <-- sorted as floats
"""``````

I was working with patient information and came up with this list of instances that made it relatively easy to find specific information:

``````# creating and processing one list of class objects

import operator

class Patient(object):
"""__init__() functions as the class constructor"""
def __init__(self, fname=None, sname=None, id=None):
self.fname = fname
self.sname = sname
self.id = id

def __repr__(self):
"""
if you print the instance of the class this format will display
"""
# use the class dictionary iterator
class_dictiter = self.__dict__.iteritems()
return "  ".join(["%s: %s" % (k,v) for k,v in class_dictiter])

# make list of class Patient instances
# instance --> surname, firstname, id
patientList = []
patientList.append(Patient("Elmer", "Fudd", "1234"))
patientList.append(Patient("Donald", "Duck", "1235"))
patientList.append(Patient("Mighty", "Mouse", "1236"))
patientList.append(Patient("Fargo", "Ferkel", "1237"))

print "Show/test the whole patientList via __repr__ overload:"
print patientList

print '-'*60

print "Just one instance in the list via __repr__ overload:"
print patientList

print '-'*60

print "Show one particular item:"
print patientList.sname

print '-'*60

print "Sort the patientList in place by sname ..."
patientList.sort(key=operator.attrgetter('sname'))

print

print "... then show all patients info in one nice table:"
for patient in patientList:
print "sname: %-20s  fname= %-20s   id=%s" % \
(patient.sname, patient.fname, patient.id)

"""
my output -->

Show/test the whole patientList via __repr__ overload:
[sname: Fudd  id: 1234  fname: Elmer, sname: Duck  id: 1235  fname: Donald,
sname: Mouse  id: 1236  fname: Mighty, sname: Ferkel  id: 1237  fname: Fargo]
------------------------------------------------------------
Just one instance in the list via __repr__ overload:
sname: Ferkel  id: 1237  fname: Fargo
------------------------------------------------------------
Show one particular item:
Fudd
------------------------------------------------------------
Sort the patientList in place by sname ...

... then show all patients info in one nice table:
sname: Duck                  fname= Donald                 id=1235
sname: Ferkel                fname= Fargo                  id=1237
sname: Fudd                  fname= Elmer                  id=1234
sname: Mouse                 fname= Mighty                 id=1236

"""``````

The module pygame makes it easy to load, display and move images around the screen ...

``````# experiments with module pygame
# free from: http://www.pygame.org/
# load, display and move an image

import pygame as pg

# initialize pygame
pg.init()

# pick an image you have (.bmp  .jpg  .png  .gif)
# if the image file is not in the working folder,
# use the full pathname like "C:/Images/gifs/Pooh.gif"
image_file = "Pooh.gif"

# RGB color tuple used by pygame
white = (255, 255, 255)

# create a 300x300 white screen
screen = pg.display.set_mode((300,300))
screen.fill(white)

# load the image from a file
# convert() unifies the pixel format for faster blit

# draw image, position the image ulc at x=50, y=20
screen.blit(image, (50, 20))

# get the rectangle the image occupies
# rec(x, y, w, h)
start_rect = image.get_rect()

# set up the timed event loop
x = 0
y = 0
clock = pg.time.Clock()
keepGoing = True
while keepGoing:
# set rate of move
clock.tick(30)
for event in pg.event.get():
# quit when user clicks on window x
if event.type == pg.QUIT:
keepGoing = False
# move the image ...
x += 1
y += 1
# stop when x exceeds limit
if x > 270:
keepGoing = False
image_rect = start_rect.move(x, y)
# this erases the old sreen with white
screen.fill(white)
# put the image on the screen at new location
screen.blit(image, image_rect)
# update screen
pg.display.flip()``````

You can use the module pygame to load, rotate and zoom an image ...

``````# experiments with module pygame
# free from: http://www.pygame.org/
# load, rotate, zoom and display an image

import pygame as pg

# initialize pygame
pg.init()

# pick an image you have (.bmp  .jpg  .png  .gif)
# if the image file is not in the working folder,
# use the full pathname like "C:/Images/gifs/Froggy.jpg"
image_file = "Froggy.jpg"

# RGB color tuple used by pygame
black = (0, 0, 0)
white = (255, 255, 255)

# create a 450x420 black screen
screen = pg.display.set_mode((450,420))
screen.fill(black)

# load the image from a file

# this will rotate the image using angle and zoom using scale
# pygame.transform.rotozoom(surface, angle, scale)
angle = 45.5
scale = 1.5
image = pg.transform.rotozoom(image, angle, scale)

# draw image, position the image ulc at x=15, y=5
screen.blit(image, (15, 5))

# nothing gets displayed until one updates the screen
pg.display.flip()

# start eventloop and wait until
# the user clicks on the window corner x
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
raise SystemExit``````

Something simple for a change, some Python code to use Newton's method to approximate a square root:

``````# use Newton's method to get the square root of a
a = 144

# any initial approximation
x = 4.0
while True:
print x
# Newton's square root approximation
y = (x + a/x) / 2
# with floats it's safer to compute the absolute value
# of the difference between them rather then using y == x
# make delta something small
delta = 0.000000001
if abs(y - x) < delta:
break
# now asign y to x and go again
# the approximation gets closer with every loop
x = y

"""
my output --->
4.0
20.0
13.6
12.0941176471
12.0003662165
12.0000000056
12.0
"""``````

thanks for all the little hints, i'm new to programming, i'm pully out my hair and have a blast at the same time

Just an application for lambda, and the use of a dictionary to mimic C's switch/case statement:

``````# lambda creates an anonymous function
# returnedExpr must be an expression, not a statement
# this code could form a simple calculator

import math

def do_op(op, a=1, b=1):
"""use of a dictionary similar to C's switch/case"""
return {
'+': lambda: a + b,
'-': lambda: a - b,
'*': lambda: a * b,
'/': lambda: a / b,
'//': lambda: a // b,   # floor
'**': lambda: a ** b,   # power
'sin': lambda: math.sin(a),
'cos': lambda: math.cos(a),
'asin': lambda: math.asin(a),
'acos': lambda: math.acos(a)
}[op]()

# 355/113.0 pi approx.
print do_op('/', 355, 113.0)  # 3.14159292035

# sqroot(25)
print do_op('**', 25, 0.5)    # 5.0

# asin(sin(0.5))
print do_op('asin', do_op('sin', 0.5))  # 0.5``````
Be a part of the DaniWeb community

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