F = 9 * C/5 + 32
Is the same as
F = (9/5) * C + 32
With Python2 / is integer division, so avoid it by using 5.0 instead of 5
F = 9 * C/5 + 32
Is the same as
F = (9/5) * C + 32
With Python2 / is integer division, so avoid it by using 5.0 instead of 5
Very nice! Just what I was looking for.
I would say English language skills. Everyone in our department hates to call the help desk, because you can not understand those imported folks that work there.
Well, C has a goto statement.
However, an interpretive language with a good IDE is better for beginners.
Buy everything but Lenovo!
These folks install Superfish malware at the factory!
I always thought that typing := was one of the less desirable things of Pascal, now GO has picked it up. Otherwise the language has some nice new approaches, some seem to come from Python.
Buy one where the hard drive is not infected with spyware at the factory level.
PySide comes with drag and drop designer.
Linux sounds more and more interesting. Seems to have a lot of nice tools.
One teaspoon of matter from a neutron star would weigh close to one billion tons.
After the help Gribouillis gave you, also run a test:
class A(object):
def __init__(self):
self.a = 4
self.b = 6
class B(A):
def __init__(self):
A.__init__(self)
#some code
def action(self):
self.a = 9
# test it
aa = A()
print(aa.a) # 4
bb = B()
print(bb.a) # 4
bb.action()
print(bb.a) # 9
So, what will this do?
with open('numbers.txt') as f:
for line in f:
print(line, type(line))
There is a limit to recursions in Python,
find the limit with
sys.getrecursionlimit() --> usually 1000
Can be changed with
sys.setrecursionlimit(new_limit)
However,
print float('0x123abc')
does not work
So maybe this would be better:
def is_float(s):
try:
float(s)
return True
except:
return False
for s in ['1e3', '+3.14', '-77', '0x123abc']:
if is_float(s):
print float(s)
else:
print s + ' value gives float() error'
"Hard work spotlights the character of people: some turn up their sleeves, some turn up their noses, and some don't turn up at all."
--- Sam Ewing
"When I need a little advice about Saddam Hussein, I turn to country music."
—- George Bush Sr. (1991)
Try this:
def lap_average(lap1, lap2):
# get minutes, seconds, centiseconds
m1, s1, c1 = [int(x) for x in lap1.split(':')]
m2, s2, c2 = [int(x) for x in lap2.split(':')]
# form a list of centisecond values
tlist1 = [m1*60*100, s1*100, c1]
tlist2 = [m2*60*100, s2*100, c2]
# get the total centiseconds
centis = sum(tlist1) + sum(tlist2)
# take integer average
centis = centis // 2
# get minutes, seconds from centiseconds
seconds, centis = divmod(centis, 100)
minutes, secs = divmod(seconds, 60)
print('-'*33)
print("Given lap times %s %s" % (lap1, lap2))
print("Average time = %02d:%02d:%02d" % (minutes, secs, centis))
# test times
lap_average('03:40:00', '05:20:00')
lap_average('03:00:02', '02:00:00')
lap_average('02:25:50', '06:50:75')
lap_average('00:02:00', '00:03:00')
lap_average('00:02:20', '00:04:40')
lap_average('02:40:40', '03:30:30')
lap_average('02:60:30', '60:40:40')
''' result ...
---------------------------------
Given lap times 03:40:00 05:20:00
Average time = 04:30:00
---------------------------------
Given lap times 03:00:02 02:00:00
Average time = 02:30:01
---------------------------------
Given lap times 02:25:50 06:50:75
Average time = 04:38:12
---------------------------------
Given lap times 00:02:00 00:03:00
Average time = 00:02:50
---------------------------------
Given lap times 00:02:20 00:04:40
Average time = 00:03:30
---------------------------------
Given lap times 02:40:40 03:30:30
Average time = 03:05:35
---------------------------------
Given lap times 02:60:30 60:40:40
Average time = 31:50:35
'''
The console screen can be cleared with multiple print():
for x in range(40):
print('')
Or simply:print('\n'*40)
If you have the Windows OS, maybe you should look into Portable Python and run your code from a USB flashcard, and also use the PyScripter IDE that comes with it.
For the free download and info see:
http://www.portablepython.com/releases/
Since you are a beginner I would download Python version 2.7.3 it makes working with older code examples much easier.
C is great for low level coding. You are talking about a high level task and could switch to a higher level language to make your life more productive.
''' ps_image_viewer101.py
view an image with Python using the PySide GUI toolkit
PySide is the official LGPL-licensed version of PyQT (QT)
Python and PySide are available for Windows, Linux and Apple OS X.
If you have Windows, download and execute the Windows self-extracting
installers in this order.
For Python33 (get the 32 bit version):
python-3.3.0.msi
free from:
http://python.org/download/
For PySide:
PySide-1.1.2.win32-py3.3.exe (based on QT483)
free from:
http://developer.qt.nokia.com/wiki/PySide_Binaries_Windows
'''
from PySide.QtCore import *
from PySide.QtGui import *
app = QApplication([])
# create the window/frame
win = QWidget()
# set location and size
win.setGeometry(100, 50, 500, 688)
# set the title
win.setWindowTitle("PySide Image Viewer")
# get an imagefile you have in the working folder
# or give full file path
fname = "cogtrain-500x688.jpg"
# load the picture in a form PySide can process
image = QPixmap(fname)
# use a label to display the image in
label = QLabel(win)
label.setPixmap(image)
win.show()
app.exec_()
// show "How are you %dad%"
#include <stdio.h>
int main()
{
printf( "How are you %cdad%c", '%', '%');
getchar(); // wait
return 0;
}
The rich are getting poorer, they had to take 15 Senators off the payroll.
... Jay Leno
"Success without honor is an unseasoned dish; it will satisfy your hunger, but it won't taste good."
___ Joe Paterno
A closer look at recursive functions:
''' func_recursion_GDC1.py
exploring recursive functions, in a nutshell:
return exit value if condition is met else
call function again with adjusted paramters
'''
def GCD(x, y):
'''
a recursive function to return the
Greatest Common Divisor/Denominator of x and y
'''
return x if y == 0 else GCD(y, x%y)
# testing ...
print(GCD(240, 150)) # 30
print(GCD(14, 63)) # 7
print(GCD(14, 0)) # 14
print(GCD(14, 3)) # 1
Evolutionists:
An almost chicken laid the egg the first real chicken came out off.
Creationists:
God made the chicken and then it laid an egg.
Putting up with relatives and missing my friends.
Line 9if isinstance(key, types.SliceType):
can be changed toif isinstance(key, slice):
to work with Python27 and Python33
How about knitting yourself a sweater?
A list can have a number of the same elements, whereas a set has only unique elements.
mylist = ['b', 'a', 'n', 'a', 'n', 'a', 'b', 'o', 'a', 't']
print(mylist)
# elements will be unique and in hash order
myset = set(mylist)
print(myset)
print(list(myset))
''' result -->
['b', 'a', 'n', 'a', 'n', 'a', 'b', 'o', 'a', 't']
set(['a', 'b', 't', 'o', 'n'])
['a', 'b', 't', 'o', 'n']
'''
You can use the canvas image as a background to your turtle drawings:
''' turtle_Tk_Canvas_Image_url.py
display a GIF image obtained from an internet web page
on a Tkinter canvas, then use the canvas for some turtle drawing
modified Vegaseat code
'''
import io
import base64
import turtle
try:
# Python2
import Tkinter as tk
from urllib2 import urlopen
except ImportError:
# Python3
import tkinter as tk
from urllib.request import urlopen
root = tk.Tk()
root.title("turtle graphics a website image")
# this GIF picture previously downloaded to tinypic.com
image_url = "http://i46.tinypic.com/r9oh0j.gif"
image_byt = urlopen(image_url).read()
image_b64 = base64.encodestring(image_byt)
photo = tk.PhotoImage(data=image_b64)
# create a white canvas large enough to fit the image+
w = 540
h = 340
cv = tk.Canvas(bg='white', width=w, height=h)
cv.pack()
# this makes the canvas a turtle canvas
# point(0, 0) is in the center now
tu = turtle.RawTurtle(cv)
# put the image on the turtle canvas with
# create_image(xpos, ypos, image, anchor)
xpos = int(w/2 * 0.9)
ypos = int(h/2 * 0.9)
print(xpos, ypos)
cv.create_image(-xpos, -ypos, image=photo, anchor='nw')
# now do some turtle graphics
tu.pensize(2)
for radius in range(50, 200, 40):
# pen up
tu.up()
# move pen to point x, y
# keeps the center of the circle at canvas center
tu.goto(0, -radius)
# pen down
tu.down()
tu.circle(radius)
root.mainloop()
Assume the sentences end with '.' or '?' or '!' so count these characters and divide the total words by the number of these characters.
You need to update the canvas as shown. Otherwise the Tkinter event loop just waits till time.sleep(5) is done.
import ImageTk
import tkMessageBox
from Tkinter import*
from turtle import *
import time
root = Tk() #main window
canvas = Canvas(root, width=800, height=480, bg="white")
canvas.grid(column=1, rowspan=6, row=0, columnspan=5)
start=ImageTk.PhotoImage(file="start.gif")
after_prymase2a=ImageTk.PhotoImage(file="after_prymase2a.gif")
canvas.create_image(200,400,image=start)
canvas.update() # needed to do one pic at a time
time.sleep(5)
canvas.create_image(100,100,image=after_prymase2a)
root.mainloop()
Control a turtle graphics canvas (module turtle) from an external Tkinter window with buttons.
Don't jump the gun and download Python 3.3 yet, it still has a few bugs.
Download the much more stable Python 3.2
Look at this:
# named tuples have named indexes they behave similar to class
# instances but require no more memory than regular tuples
# the record_list of named tuples can be saved(dumped) and loaded
# with Python module pickle
import collections as co
# create the named tuple
Movies = co.namedtuple('Movies',
'title, year, director, minutes, cast')
record_list = []
# create one record for the record_list
title = "The Holy Grail"
year = 1975
director = "Terry Jones & Terry Gilliam"
minutes = 91
cast = [
'Graham Chapman',
'John Cleese',
'Terry Gilliam',
'Eric Idle',
'Terry Jones',
'Michael Palin']
record_list.append(Movies(title, year, director, minutes, cast))
# now you can do things like this
actor = 'John Cleese'
for movies in record_list:
if actor in movies.cast:
print("%s acted in %s" % (actor, movies.title))
'''my result -->
John Cleese acted in The Holy Grail
'''
Hope you are not a mouse. This shows you how to select multiple listbox items from a Tkinter listbox widget:
'''Tk_Listbox_multiselect1.py
create a scrollable listbox using Tkinter
load the listbox with tasty cheese data
and select your favorite cheese or cheeses with the mouse
press <Shift> and/or <Ctrl> to select multiple cheeses
'''
try:
# for Python2
import Tkinter as tk
except ImportError:
# for Python3
import tkinter as tk
def get_list(event):
"""
function to read the listbox selection(s)
and put the result in a label widget
"""
# get multiselected line indices
indices = listbox.curselection()
print(indices) # test
# get the selected lines' text
seltext = '\n'.join(listbox.get(ix) for ix in indices)
# put the selected text in the label
label['text'] = seltext
root = tk.Tk()
root.title("Cheeses")
# use width x height + x_offset + y_offset (no spaces!)
root.geometry("150x300+100+70")
# create a label (width in characters)
s1 = "Click on a cheese"
s2 = "press <Shift> and/or"
s3 = "<Ctrl> for multiples"
sf = "%s\n%s\n%s" % (s1, s2, s3)
label = tk.Label(root, text= sf, width=25)
label.grid(row=0, column=0)
# create a listbox (height in characters/lines)
# give it a nice yellow background (bg) color
# press <Shift> and/or <Ctrl> to select multiple listelements
listbox = tk.Listbox(root, height=15, bg='yellow', selectmode='extended')
listbox.grid(row=1, column=0)
# the Tkinter listbox does not automatically scroll, you need
# to create a vertical scrollbar to the right of the listbox
yscroll = tk.Scrollbar(command=listbox.yview, orient=tk.VERTICAL)
yscroll.grid(row=1, column=1, sticky='n'+'s')
listbox.configure(yscrollcommand=yscroll.set)
cheese_list = [
'Feta', 'Limburger', 'Camembert', 'Roquefort', 'Edam',
'Romadur', …
The PyGTK GUI toolkit can make a list box, but it is not simple:
'''pgtk_listbox1.py
uses gtk.TreeView(), gtk.ListStore() and gtk.CellRendererText()
to create a single column listbox
'''
import pygtk
pygtk.require('2.0')
import gtk
class MyListBox(object):
'''
create a single column listbox
'''
def delete_event(self, widget, event, data=None):
gtk.main_quit()
return False
def __init__(self, name_list):
"""create a single column list box and load it with data"""
self.name_list = name_list
# Create a new window
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_size_request(200, 300)
# allows for smooth exit on 'x' click
self.window.connect("delete_event", self.delete_event)
# create the list model and load with the name_list
self.listmodel = self.make_list()
# create the TreeView
self.treeview = gtk.TreeView()
cell = gtk.CellRendererText()
# create the "Name" column
self.tvcolumn = gtk.TreeViewColumn("Names", cell)
# align data to the left
cell.set_property('yalign', 1.0)
self.tvcolumn.set_cell_data_func(cell, self.cell_property)
# append the only column to the treeview
self.treeview.append_column(self.tvcolumn)
# make it a list
self.treeview.set_model(self.listmodel)
# create a scrolled window for the treeview
self.scrolledwindow = gtk.ScrolledWindow()
self.scrolledwindow.add(self.treeview)
# add the scrolled window to the main window
self.window.add(self.scrolledwindow)
# now show the main window
self.window.show_all()
def make_list(self):
"""
create and load the list model
"""
self.window.set_title("My name list")
listmodel = gtk.ListStore(object)
for name in self.name_list:
#print(name) # test
listmodel.append([name])
return listmodel
def cell_property(self, column, cell, model, iter):
"""set cells to text"""
cell.set_property('text', model.get_value(iter, 0))
return
# a list of names for testing
name_list = [
"Frank Ferkel",
"Erich Meitinger",
"Leon Larimee",
"Jens Klein",
"Bjorn Bork",
"Heidrun Lovelace",
"Klaus Abraham",
"Ulla Jorgens",
"Volger Jenkings",
"Alexander Arm",
"Helmut Schmidt",
"Freja Larse",
"Larry Orkan",
"Andreas …
Maybe this will help you:
import string
allowed_alpha = string.ascii_letters + string.whitespace
# a test name
name = "Mark Zumkoff"
# gives False because of space
print(name.isalpha())
# this test allows spaces
if all(c in allowed_alpha for c in name):
print(name)
else:
print("not an allowed name")
Could be the start of a word game:
# a simple rotate cipher
from collections import deque
def rotate_right(text, n=1):
"""
use deque to rotate text n steps to the right
return rotated text
"""
rot_right = deque(text)
rot_right.rotate(n)
return "".join(rot_right)
def rotate_left(text, n=1):
"""
use deque to rotate text n steps to the left
return rotated text
"""
rot_left = deque(text)
rot_left.rotate(-n)
return "".join(rot_left)
# cipher the text by rotating 3 steps
text = 'peanuts'
n = 3
print(rotate_right(text, n)) # utspean
# decipher the text
text = 'utspean'
print(rotate_left(text, n)) # peanuts
"Deleted code is debugged code."
-- Jeff N. Sickel
I am not sure if the book
"Python for Idiots"
has been published yet.
I am waiting!
"Everyone thinks of changing the world, but no one thinks of changing himself."
-- Leo Tolstoy
Threading may solve your problem, here is an example:
'''threading_Timer1_sound.py
threading allows other program segments to run at the same time
threading.Timer() forms an interruptable sleep() function
t = threading.Timer(interval, function, args=[], kwargs={})
t.start() starts the thread
t.cancel() stops the thread
t.isAlive() checks active thread
winsound.Beep(frequency, duration) needs Windows OS
'''
import threading
import winsound
def action1():
print("We are being attacked!")
def alarm():
# 500 hz sound for 9 seconds
winsound.Beep(500, 9000)
def action2():
print("Wake up our troops!")
def action3():
print("Our troops are ready!")
# after 0.1 seconds do action1
t1 = threading.Timer(0.1, action1)
# after 3.5 seconds do action2
# and after 10.0 seconds do action3
t2 = threading.Timer(3.5, action2)
t3 = threading.Timer(10.0, action3)
# this will wake the troops after action2 has been called
t4 = threading.Timer(4.5, alarm)
t1.start()
t2.start()
t3.start()
t4.start()
If you smoke you are honest, at least it shows the rest of us that you are not very smart.
Rednecks only have to count to 10.
"Pain is temporary; pride is forever!"
Does anybody have experience with Python on the iPad?
Is it easy to get and use Python?
“There are only two kinds of programming languages: those people always bitch about and those nobody uses.”
-- Bjarne Stroustrup
"I will not be a lemming and follow the crowd over the cliff and into the C."
Execution speed is probably of limited interest for a beginner. Concentrate on learning the basics of Python rather thoroughly. Any program that has display updates and disk access in it, is limited a lot by those operations anyway! Either Python 2.6 or Python 2.7 will do fine for you. Why not use Python 2.7, the most advanced of the Python2 versions.