jlm699 commented: Great articles. I like the authors' points of view on Python. Inspiring! +3
mn_kthompson commented: Very elegant solution to palindrome problem +2
Ahh when user input is should be like this off course.
comp = random.choice(choices) #comp
human = choice #human
Ok make it simpler.
import random
choices = ['rock', 'paper', 'scissors']
while True:
choice = input("please enter your choice(rock-scissors-paper): ")
if choice in choices:
print(choice) #test print
print (type(choice)) #se what input returns,you can make it a integer later if you need that
break #and break out of the while loop
else:
print("Invalid colour '{0}'.".format(choice))
print("Possible values are {0}".format(tuple(choices)))
comp = random.choice(choices) #comp
human = random.choice(choices) #human
print ("Comp: %s\nHuman: %s" % (comp, human)) #test print
#now figuere out how to define winner
Tips you can use index.
>>> choices = ['rock', 'paper', 'scissors']
>>> choices.index('rock')
0
>>> choices.index('paper')
1
>>> human_rand = choices.index(human)
>>> human_rand
2
>>>
New style class python 2.2--> you should use
class(object):
Old style pre python 2.2
class:
So object is a build in,let`s test it.
IDLE 2.6.2
>>> object
<type 'object'>
>>>
For more deeper explanation.
http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html
You know that this code is for python 3.x?
For python 2.x
n = input('Enter an interger >= 0: ')
fact = 1
for i in range(2,n+1):
fact = fact*i
print n, 'factorial is', fact
print 'The factorial off %d is %d' % (n, fact) #Or like this is better
Python 3.x has only input(that return a string)
That why it`s used int(input())
I take opp this for in your post #3 you use print i <-- this will not work for python 3
Print has become a function in python 3,and only this will work print(i)
That why i think you use python 2.x
Yes you use python 3.x i see(when you post make a note that you use python 3.x)
Python 3 has no raw_input only input.
return choice you can not use return if you dont make a function.
So this is how it should bee.
import random
choices = set("""1 = rock, 2 = scissors, 3 = paper""".strip().split())
while True:
choice = input("please enter your choice(1 = rock, 2 = scissors, 3 = paper): ").strip()
if choice in choices:
print(choice) #test print
print (type(choice)) #se what input returns,you can make it a integer later if you need that
break #and break out of the while loop
else:
print("Invalid colour '{0}'.".format(choice))
print("Possible values are {0}".format(tuple(choices)))
import random
def rockPaperScissors():
#choice = raw_input("please enter your choice: ") #I take away this to make a point
computerIndex = random.randint(0,2)
if computerIndex == 1:
computer = "rock"
print computer #test print
elif computerIndex == 2:
computer = "scissors"
print computer #test print
else:
computer = "paper"
print computer #test print
rockPaperScissors()
Think of what your function should do,now user input has no function.
There is no point in just get it to work,what to learn by that?
That bad design is ok.
here you make board global.
global board
This wont draw 1 X as you want,you known why?
board[0][playchip] = 'X'
So board is global then the for loop for board get run every time.
And make many X and O.
def dot_blank():
for i in range(columns):
for i in range(rows):
if board[0][playchip] == '.':
return True
return False
Dont use global variables.
Any name (variable) defined inside a function is local to that function,and should always stay that way.
If you need access to a function's local variables outside that function use argument and return variables out off function.
No are pollutioning the global namespace and you get problem like you have now
And finding problem it`s must hardere now that you use global variabls.
I really think you should redesign your code without global variabels(never ever use global variables is a god rule)
And import <module> is always first never inside a function.
Use 4 space for indent(never 2 or 8)
but it doesn't seem to be working... it still gives 11.50 when i input 10...
Yes as it should do,is should not be so hard to understand.
<= 10 means that less than 10 or equal to 10 it will add 1.50.
Then off course if you input is 10 it will add 1.50 and print 11.50.
< 10 all values under 10 it will add 1.50
>>> suits = ['diamonds', 'clubs', 'hearts', 'spades']
>>> rank = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King']
>>> # This is what we need to make a hole deck
>>> # Now we loop trough (rank and suits) and append the result.
>>> deck = [] # Empty deck
>>> for n in numbers:
for s in suits:
card = '%s of %s' % (n, s)
deck.append(card)
>>> deck # Will print the whole deck
>>> # Make it look better
>>> from pprint import pprint
>>> # Now let us print 10 card
>>> pprint(deck[:10])
['1 of diamonds',
'1 of clubs',
'1 of hearts',
'1 of spades',
'2 of diamonds',
'2 of clubs',
'2 of hearts',
'2 of spades',
'3 of diamonds',
'3 of clubs']
>>> # The for loop can be written in 1 line like this
>>> deck = ['%s of %s' % (n, s) for n in numbers for s in suits]
>>> # A little python sugar with list comprehension
Now you can to shuffle the deck,use random module.
Deck is a list now,so to take out 1 card should be easy,look at pop() method.
To se all method for list do this dir(deck)
It`s not the best example of python class masterofpuppets.
You put in lot effort to help wish is fine.
Hope this makes it a bit clearer....I haven't actually worked a lot with classes in Python but I guess it is not that much different to Java. So I am sorry if I didn't explain something properly... still learning as well
Python is not java,it`s a lot better:cool:
http://dirtsimple.org/2004/12/python-is-not-java.html
Just to point it out that you could have dropped all that getters method.
Form article.
don't write getters and setters. They are a waste of CPU time, but more important, they are a waste of programmer time. Not just for the people writing the code and tests, but for the people who have to read and understand them as well.
Look at this and then think of how you code could have been shorter and better.
http://tomayko.com/writings/getters-setters-fuxors
Yes,i should have think of that you need floating point number to get correct sum.
%.2f(give you 2 decimal float number)
is %.2f pounds" % (order + x)
total price... is 8pounds or £8 and not just 8..
order = input("Please enter the price of the order: ")
x = 1.50
if order < 10:
print "the total price including the delivery charge is %d pounds" % (order + x)
else:
print "The toal price including delivery charges is %d pounds" % (order)
>>> #Is rounds greater than player_point or cpu_point
>>> #It will print Victory
>>> #Test
>>> rounds = 5
>>> player_point = 4
>>> cpu_point = 3
>>> while rounds > player_point or cpu_point:
print 'Victory'
break
else:
print 'Lose'
Victory
>>> #So if we change player_point to 8
>>> player_point = 8
>>> while rounds > player_point or cpu_point:
print 'Victory'
break
else:
print 'Lose'
Victory
>>> #It still print Victory because of "or"
>>> #If we change to "and" then Lose
>>> while rounds > player_point and cpu_point:
print 'Victory'
break
else:
print 'Lose'
Lose
>>> player_point = 4
>>> while rounds > player_point and cpu_point:
print 'Victory'
break
else:
print 'Lose'
Victory
>>> #Last one Victory beacause now both player_point and cpu_point are less than rounds
Edit a little to late i see:icon_wink:
Yes good.
Or shorter.
a = [raw_input('>')for x in range(5)]
A for loop is easier for this.
for i in range(4):
for item in ['a,b,c,d']:
item = raw_input("something: ")
something: 7
something: 8
something: 9
something: 2
>>> item
'2'
>>> #If you whant to store all values put them into a list
>>> l = []
for i in range(4):
for item in ['a,b,c,d']:
item = raw_input("something: ")
l.append(item)
something: 8
something: 9
something: 6
something: test
>>> l
['8', '9', '6', 'test']
>>>
call the functions circumferenceOfCricle and areaOfCircle
circumferenceOfCricle is not a function as you should see.
To make circumferenceOfCricle to a function
def circumference(radius):
return float(2*math.pi*radius)
Then try to figure out function call yourself.
Some error in your print line,look at this.
import math
radius = input("please enter the radius of the cirle: ")
area = float(math.pi*radius**2)
circumference = float(2*math.pi*radius)
print "With an input off %s area is %.2f\nand circumference is %.2f" % (radius, area, circumference)
'''My output-->
With an input off 4.78 area is 71.78
and circumference is 30.03
'''
It`s ok.
>>> import math
>>> def AreaOfCircle(radius):
return math.pi * radius**2
>>> AreaOfCircle(5)
78.539816339744831
>>> AreaOfCircle(5.4587)
93.611310811738718
>>> AreaOfCircle(.4589)
0.66158551506127805
>>> print math.pi
3.14159265359
>>>
Next time if you post here try to post some code.
That will show that you but some effort in to it.
With homework we will not just post finish code.
Here is one soultion,as extra i put number odd/even number in a list.
Try to understand what going on,ask question if you not sure an we break it down.
import random
count_odd = 0
count_even = 0
odd_list = []
even_list = []
for i in range(0,100):
rand_n = random.randint(0,100)
if rand_n % 2 == 1:
count_odd += 1
odd_list.append(rand_n)
else:
count_even += 1
even_list.append(rand_n)
print 'Out off 100 random number %d was odd\nHere are the numbers->\n' % (count_odd)
print odd_list
print
# Here we do a check that it`s 100 number
print 'Out off %d random number %d was even\nHere are the numbers->\n' % (count_even + count_odd, count_even)
print even_list
'''my output->
Out off 100 random number 44 was odd
Here are the numbers->
[53, 67, 27, 37, 97, 75, 89, 87, 65, 81, 31, 85, 85, 33, 13, 13, 27, 5, 75, 37, 73, 39, 53, 71, 53, 27, 23, 1, 13, 19, 29, 9, 13, 45, 19, 31, 63, 27, 33, 43, 51, 61, 35, 35]
Out off 100 random number 56 was even
Here are the numbers->
[2, 2, 16, 16, 34, 14, 70, 22, 30, 2, 74, 90, 28, 36, 100, 74, 48, 8, 40, 64, 54, 94, 54, 56, 16, 4, 94, 66, 18, 12, 36, 100, 8, 18, 54, 16, 72, 16, 20, 60, 28, 6, 38, 10, 62, 88, 98, 90, 54, 26, 50, 38, 66, 76, 42, 12]
'''
One more,now start to think how to put this together.
>>> count = 0
>>> a = 55
>>> if a % 2 == 1:
count += 1
print 'odd', count
else:
print 'even'
odd 1
>>>
You should try to post some code yourself.
Can give you some tips.
>>> for i in range(0,7):
a = random.randint(0,100)
print a
79
21
69
60
28
68
0
>>>
>>>
>>> 1 % 2
1
>>> 2 % 2
0
>>> 3 % 2
1
>>> 4 % 2
0
>>>
To make it short with python list comprehensions.
Not that this make code better or more readable in many cases.
But think this line is not so bad to understand.
>>> f = [line[0] for line in open('ab.txt')]
>>> f
['a', 'c', 'e', 'g']
>>>
Read every characters.
So colum 2 will be line[2]
But how could we test if the given string is pallindrome or not. I need a syntax that returns true if the string is pallindrome otherwise false.
>>> def is_palindrome(s):
... return s.lower() == s[::-1].lower()
...
>>> is_palindrome('test')
False
>>> is_palindrome('racecar')
True
>>> is_palindrome('RACECAR')
True
pygame and the livewires package but was unable to get the program to run
Forget about livewires package,it is outdatet and not smart to use at all if you what to learn pygame.
If you want to look pygame you have to do as everyone else.
All tutorials on net are for pygame,none for livewires package.
A simple window with som graphics.
import pygame
#----| Initialize PyGame |---#
pygame.init()
#---| Create window |---#
screen = pygame.display.set_mode((615, 400))
#---| Window color |---#
screen.fill((100, 0, 0)) #Red
#---| Set name window |---#
pygame.display.set_caption('My pygame window')
#---| variabler color(r, g, b) and size/placement |---#
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
yellow = (255, 255, 0)
#---
radius = 50
center = (150, 150)
center_1 = (450,150)
#---| draw white circles |---#
pygame.draw.circle(screen, white, center, radius)
pygame.draw.circle(screen, white, center_1, radius)
#---| draw a yellow square |---#
pygame.draw.rect(screen, yellow,(220, 250, 150, 100))
#---| Display screen graphics|---#
pygame.display.flip()
while True:
event = pygame.event.poll()
if event.type == pygame.QUIT:
break
Lets break it down.
IDLE 2.6.2
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in a:
print i
Mary
had
a
little
lamb
>>> for item in a:
print item
Mary
had
a
little
lamb
>>> #So it can be anything you whant(i,item,element.....)
>>> #The for loop iterates over elemen in a
>>> i = 'Mary'
>>> i
'Mary'
>>> i = 'had'
>>> i
'had'
>>> i = 'a'
>>> i
'a'
>>> #So the for loop assigning each element in a to i
>>> for i in range(5):
print i
0
1
2
3
4
>>> len(a)
5
>>> #So the last part that you have combine this 2
>>>
How did you make those images?
Du you mean the Attached Thumbnails?
Thats just screenshot capture with free program jing.
http://www.jingproject.com/
BeautifulSoup stores everything as unicode strings.
In order to convert BeautifulSoup's unicode strings to human readable strings, you have to encode() them; and when you encode() a unicode string, you have to specify a "codec". Some examples of codecs are "ascii" and "utf-8".
Se if this help.
divs = soup.findAll("div", {"class": "treff"})
for div in divs:
outfile.write (div.encode('utf-8','replace'))
print div #test print
pass
outfile.close()
div.p.contents[0] this i dont get to work.
And use code tags.
like the dir( x ) - really useful
Doc string and help is ok to know about to.
>>> l = []
>>> type(l)
<type 'list'>
>>> dir(l)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> #Now let get help for method in list class
>>> l.pop.__doc__
'L.pop([index]) -> item -- remove and return item at index (default last).\nRaises IndexError if list is empty or index is out of range.'
>>> #Better to use print because of new line(\n)
>>> print l.pop.__doc__
L.pop([index]) -> item -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
>>> print l.insert.__doc__
L.insert(index, object) -- insert object before index
>>> #With help
>>> help(l.insert)
Help on built-in function insert:
insert(...)
L.insert(index, object) -- insert object before index
>>> help(l.append)
Help on built-in function append:
append(...)
L.append(object) -- append object to end
>>>
Think maybe you are confused about calling a function and calling a method.
def my_func(name, greeting = 'Hello'):
print '%s, %s' % (greeting, name)
#Call a function
my_func('tom') #output <Hello tom>
#-----------------------------------#
class myClass(object):
# Inside a class this is called a method
def my_method(self,name,greeting = 'Hello'):
print '%s, %s' % (greeting, name)
a = myClass() #Class instance
# Call a method
a.my_method('tom') #output <Hello tom>
So do this.
>>> x = 'a string'
>>> dir(x)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> # Now we se method for string
>>> # And calling a method x.<name of method>
>>> x.upper()
'A STRING'
>>> x.split(' ')
['a', 'string']
>>>
i just added little spacing here and there to see more easy what im doing.
Always use 4 space for indent.
Read PEP 8.
http://www.python.org/dev/peps/pep-0008/
Tutorial look like it come from sthurlow
http://www.sthurlow.com/python/lesson05/
And some strange code confusing for beginner.
add(raw_input("Add this: "),raw_input("to this: "))
This call function add with 2 argument.
So a more simpler way to understand this.
>>> def add(a,b):
print a, '+', b, '=', int(a) + int(b)
>>> a = raw_input("Add this: ")
Add this: 5
>>> b = raw_input("to this: ")
to this: 9
>>>
>>> # now let us call add() function in a more normal way
>>> add(a, b)
5 + 9 = 14
>>>
PyQt support python 3.x
http://www.riverbankcomputing.co.uk/software/pyqt/intro
This post has many PyQt example.
http://www.daniweb.com/forums/thread191210.html
There are also example of new function for Tkinter.
Tkinter version that comes with the Python 3.1 installation includes expansion module ttk.
Look at Vegaseat example in link over.
Just as a notice there no problem to have both python 2.x and python 3.x installed.
I use wxpython so i stay with python 2.x for now.
Have off course python 3.x installed to.
Or if you stay with raw_input,you can convert to integer later in the function.
def add(a,b):
print a, '+', b, '=', int(a) + int(b)
#print '%s + %s = %d ' % (a, b, int(a)+int(b)) # Try this line to
choice = menu()
So now choice take take the variable that get returned for menu() function.
So if user choice 1,what will choice be integer or string?
Choose your option: 1
>>>choice = menu()
>>> choice
'1'
Yes it return a string.
Will this line work correct then? if choice == 1:
>>> '1' == 1
False
>>> 1 == 1
True
>>>
So now you now what to change in that line.
how to connect Notepad++ with python.exe but i like notepad++ more than Python GUI)
Use a edtior that that you can just run your code on the fly.
Just paste inn code and push run button.
Pyscripter is god.
http://code.google.com/p/pyscripter/
And use code tag when you post code.
Look like cx-freeze has come out with a version for python 3.
http://cx-freeze.sourceforge.net/
Or just use python 2.x and python 3., there is no point just to use python 3.x for now.
I will not stay for python 2.x til most of the 3 party modules i use a lot is rewritten for python 2.x eksp:wxpython, p2exe.
I have python 2.5.4 - 2.6 and 3.1 installed,no problem switching between them.
Hi here are som changes.
Done some work on this,i was thinking making somthing simelar as this for fun.
So helping you a little is no problem,set my self as co-developer in about box if you dont mind.
Here are changes.
----------| Change log |---------
* Change on size and design | New headerpicture
* Take away maximize window (wx.MINIMIZE_BOX)
* Ico for Frame and about box
* New about box style
* Picture buttons
* Bigger message Box and multiline enable(wx.TE_MULTILINE)
* Exception handling on mail sent with new StaticText message
* Better documentation of code
----------| idèe for future development |--------
* Email attachment(file)
* Contact list load
* Save default login
http://www.esnips.com/doc/c2e05e06-508b-4dbd-a678-110819cb05ed/py-mailer
import smtplib
import time
import os
import wx
from wx.lib.wordwrap import wordwrap
window = wx.App()
class pymailer(wx.Frame):
'''
Program to send gmail message
'''
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY,"Py-mailer",size=(330,520),
style = wx.DEFAULT_DIALOG_STYLE | wx.MINIMIZE_BOX)
#----| Window color |---#
self.SetBackgroundColour("#d8d8bf")
#---| Add a panel so it looks the correct on all platforms |---#
self.panel = wx.Panel(self, wx.ID_ANY)
#---| Ico for window |---#
ico = wx.Icon('email1.ico', wx.BITMAP_TYPE_ICO)
self.SetIcon(ico)
#----| Gmail server |---#
self.info = {}
self.s = smtplib.SMTP("smtp.gmail.com",587)
self.s.ehlo()
self.s.starttls()
self.s.ehlo()
#---| Menu bar |---#
menubar=wx.MenuBar()
filem=wx.Menu()
filem.Append(201,"Quit")
self.Bind(wx.EVT_MENU,self.Quit,id=201)
viewm = wx.Menu()
viewm.Append(202,"About")
self.Bind(wx.EVT_MENU,self.About,id=202)
menubar.Append(filem,"File")
menubar.Append(viewm,"Help")
self.SetMenuBar(menubar)
#---| Picture Buttons |---#
self.send = wx.BitmapButton(self.panel,107,wx.Bitmap("py_email1.png"),
pos = (7,430), size = (65,26))
self.Bind(wx.EVT_BUTTON,self.Send,id = 107)
self.login = wx.BitmapButton(self.panel,103,wx.Bitmap("py_email2.png"),
pos …
>>> import urllib.request, re
>>> from html.parser import HTMLParser
>>> main_page = urllib.request.urlopen("http://www.stats.gov.cn/english/").read(20000).decode('gb2312')
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
main_page = urllib.request.urlopen("http://www.stats.gov.cn/english/").read(20000).decode('gb2312')
UnicodeDecodeError: 'gb2312' codec can't decode bytes in position 1-2: illegal multibyte sequence
It will return none because of error with decode('gb2312')
So the Chinese data encoded GB2312 format give som problem.
Search google python decode('gb2312')
>>> main_page = urllib.request.urlopen("http://www.stats.gov.cn/english/").read(20000)
>>> main_page
<now it work>
If this give you what you need i am not sure.
I have made an alramclock with wxpython before with stopclock(countdown) as one of the function.
So wxpython has this function build in "wxStopWatch"
http://www.tnir.org/~rae/wx/manuals/2.4.2/wx364.htm
You can set size so the text get overwrite.
And som color look better.
try:
self.s.login(self.user,self.passw)
wx.StaticText(self.panel,-1,"Logged in...",pos=(10,200),size = (150,20)).SetForegroundColour('blue')
except:
wx.StaticText(self.panel,-1,"Failed",pos=(10,200),size = (150,20)).SetForegroundColour('red')
For me i have to have this put in this lines or it dont work for me.
self.s.ehlo()
self.s.starttls()
self.s.ehlo()
And your design need some work,can give som tips later if you want that.
I dont know why you marked it solved,but write some abought the problem you have.
So think you got a assignment about Top-Down Design.
You are on the right path.
Top-Down Design u call main and you work your way down one function/problem at the time.
Gone show how to break this opp.
The you see problem more clearer.
Part 1
import math
def main():
intro()
def intro():
#print explination to the user
print "Program to calculate the area and cost"
print "per square inch of a pizza."
print "You will be asked to enter the diameter"
print "of the pizza in inches and the cost in dollars."
print
main()
First part we just test the the intro() function.
Work fine.
Part 2 we test getInputs() and that it print correct(printResults())
#!/usr/bin/env python
import math
def main():
intro()
diameter, cost = getInputs()
printResults(diameter, cost)
def intro():
#print explination to the user
print "Program to calculate the area and cost"
print "per square inch of a pizza."
print "You will be asked to enter the diameter"
print "of the pizza in inches and the cost in dollars."
print
def getInputs():
#prompt for the diameter and cost from the user
diameter = input("Enter the diameter (in inches): ")
print
print
cost = input("Enter the cost (in dollars): ")
print
print
return diameter, cost
#create printResults function
def printResults(diameter, cost):
print "For a diameter of ",diameter ," inches"
print "and a cost of …
And a shorter version that uses the reverse string metod in a smart way.
>>> def is_palindrome(s):
... return s.lower() == s[::-1].lower()
...
>>> is_palindrome('test')
False
>>> is_palindrome('racecar')
True
>>> is_palindrome('RACECAR')
True
Vegaseat gave you an answer in your own post last time.
http://www.daniweb.com/forums/showthread.php?t=224869&highlight=pymailer&page=5
I have used py2exe and wxpython many times it`s works fine.
Some more info if you need it.
http://wiki.wxpython.org/py2exe
http://stackoverflow.com/questions/323424/py2exe-fails-to-generate-an-executable
http://article.gmane.org/gmane.comp.python.wxpython/71929
This is really starting to annoy me
I did this just to show an alternative way of thinking,because you ask about OO.
It is not to put your code down.
One the best way to learn is to get input from other.
So you shoul not be annoyed but rather look at it as a good way to learn.
If someone told me that writing a function for +-*/ rather than use eval() is a good thing for safe code.
I would not argue about that.
Because eval() can be used in a bad way.
>>> eval("__import__('os').remove('file')")
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
eval("__import__('os').remove('file')")
File "<string>", line 1, in <module>
WindowsError: [Error 2] Systemet finner ikke angitt fil: 'file'
So it get an error that it dont find the file.
If correct path it had removed that file from my system.
The prevent this add __builtins__
print eval("__import__('os').remove('file')", {"__builtins__": {}})
This code had been better without a class,and this is not the OOP way of thinking.
One function for Addition/Division....... can be shorten by eval()
>>> a = eval('5+8886/45*4554545')
>>> a
899370824.3333334
Here an example with class.
import math
class Calculator(object):
'''Doc_string info about class'''
def calculate(self, expression):
self.value = eval(expression)
def square(self, sqrt1):
'''This look like a function,but inside a class is called a method'''
self.b = math.sqrt(sqrt1)
def __str__(self):
return self.value
return self.b
#here a make the method of class short
#and i do user_input and printing outside of the class(you can of course make a menu but not in the class)
a = Calculator()
print('Calculate +-*/ and Square Root')
b = input('values')
a.calculate(b)
print('The sum of %s is %d' % (b, a.value))
c = int(input('Enter Square Root value'))
a.square(c)
print('The square Root of %d is %d' % (c, a.b))
''' my output-->
Calculate +-*/ and Square Root
The sum of 45+78*4545/56 is 6375
The square Root of 25 is 5
'''
Look at this,and se if inherits from other classes make it clearer.
What you are doing is not the way to this.
>>> class Test:
def a(self):
self.var1 = 5000
print 'i am a'
>>> class Test1(Test):
def b(self):
print 'i am b'
print 'value from class Test method a is %d' % (self.var1)
>>> c = Test1()
>>> c.a()
i am a
>>> c.b()
i am b
value from class Test method a is 5000
>>>
It easier to help if you post some code and explain what the problem is.
I call your code mail.py
Testet with python 2.5.4 and 2.6 run exe with no error.
If it send mail i dont know because of email2.php i guess only works for you.
from distutils.core import setup
import py2exe
import sys
if len(sys.argv) == 1:
sys.argv.append("py2exe")
setup( options = {"py2exe": {"compressed": 1, "optimize": 2, "ascii": 1, "bundle_files": 1}},
zipfile = None,
# data_files = ['apple.jpg', 'cheese.jpg'],
#Your file.py can use windows or console
windows = [{"script": 'mail.py'}])
import shall not be inside a function(always first) an 8 space indent(in python we use 4 always),and long functions a.
Sorry but i dont se the point in just post this code without any question.
And this code dos not help beginners at all,maybe to show how python code not shall look.
>>> class Stuff:
def __init__(self):
self.a = 0.02
>>> x = Stuff
>>> x
<class __main__.Stuff at 0x012007E0>
>>> # you are not instance the class
>>> x = Stuff()
>>> x
<__main__.Stuff instance at 0x011FF0F8>
>>> # Here you you instance the class
>>> x.a
0.02
>>> y = Stuff()
>>> z = Stuff()
>>> a = []
>>> a.append(x.a)
>>> a.append(y.a)
>>> a
[0.02, 0.02]
>>> # here you only get 0.02 what you maybe whant to do is this
>>> class Stuff:
def __init__(self, a):
self.a = a
>>> # Now we can pass argument to the instance
>>> x = Stuff(0.02)
>>> y = Stuff(0.5)
>>> z = Stuff(40)
>>> a = []
>>> a.append(x.a)
>>> a.append(y.a)
>>> a.append(z.a)
>>> a
[0.02, 0.5, 40]
>>> b = sum(a)
>>> b
40.520000000000003
>>> print 'the sum is %.2f' % (b)
the sum is 40.52
dint work anyway what code should i write to open the pygame window
is it import pygame?
No "import pygame" you only make pygame libary available
This code to get a pygame window open.
Seek google for pygame tutorials.
#! /usr/bin/env python
import pygame
screen = pygame.display.set_mode((640, 400))
while True:
event = pygame.event.poll()
if event.type == pygame.QUIT:
break
Think input(python 3) can not take 2 values.
You can do it this way.
>>> score1 = int(input('Enter first number: '))
Enter first number: 5
>>> score2 = int(input('Enter second number: '))
Enter second number: 8
>>> average = (score1 + score2) / 2.0
>>> average
6.5
>>>