Save it to a text file:
f = open('my_file.txt', 'w')
#
f.write( '%s\n%s\n' % ( usr_name, usr_number ) )
f.close()
Save it to a text file:
f = open('my_file.txt', 'w')
#
f.write( '%s\n%s\n' % ( usr_name, usr_number ) )
f.close()
print p.Hi #This prints the location...
get <__main__.add instance at 0x00A98FD0>
Um... why?
Because you asked for it ;)
print p.Hi() #This prints the location...
HTH
What errors are you getting and where?
I've used this in the past for splitting a Status Bar and writing text to the last section (ie [ Index 0 | Index 1 | Index 2 ] ):
self.sb = self.CreateStatusBar(3)
self.sb.SetStatusWidths([-2, -1, 150])
self.SetStatusText('My Text', 2)
SetStatusText is not a function of the status bar but of the frame containing said status bar, which may be the reason for your error.
HTH
if prompt == "look around" or prompt == "look":
Another solution for this problem that will help if you had a third option would be this:
if prompt in [ 'look around', 'look', 'observe', 'admire' ]:
So if you use the in
keyword, it'll match it to any value within the iterable container (list). This can clean up a lot of statements like that.
fraction1 = float(fraction) * 2
fraction1 = str(fraction1)
binfrac1 = fraction1[0]
if "1" in binfrac1:
fraction1 = float(fraction1)
fraction1 - 1
binfrac1 = str(binfrac1)
This logic is flawed. All you're doing is doubling the "fraction" portion of the number, and checking to see if the first number is a 1, at which point you subtract "1" from the number... I haven't done fractional binary conversions in a long time, but can't you just multiply the fraction by ten until it's a whole number, and then push that numberthrough the same logic that you use for the binint portion? Then you'll only need to adjust for decimal at the end.
Sometimes, if the module isn't in the same place, it is a matter of the path. At the begging of your progam you can do something like:
import sys
sys.path.append('/path/tomy/module')
from MyMod import moduleA
However I don't know how Eclipse as an IDE differs in terms of working directory...
I did this and had a hell of a time figuring it out!
Go to Run -> "Run...", then type in C:\PythonXX\pythonw.exe "$(FULL_CURRENT_PATH)"
** Note I use pythonw.exe, you can just as easily use the standard python.exe (I just hate that console window), and when you've got that hit the "Save..." button for a dialog where you can name it and assign a shortcut to it.
*Note: Ctrl + R was already taken (and I'm too used to it from CodeEditor) so I went to Settings -> "Shortcut Mapper..." to give my python run command the Ctrl + R and moved whatever that used to be occupied to something else
Just dug this out of my bookmarks: Notepad++ Run external tools
you need to use the file handle and not the loaded object when you dump. You should just reopen the file for reading or writing and not worry about a+.
#User Access for Password.py
import cPickle as p
import sys
my_file = 'systemaccess.txt'
file_handle = open( my_file, 'r' )
temp = p.load( file_handle )
file_handle.close()
def EP(self):
if self.lower() == 'exit':
print 'Exiting Program.'
sys.exit()
print 'Welcome to the System Account Setup.'
print 'Enter Exit to end the program at any time.'
Username = raw_input('Please enter the username you desire: ')
EP(Username.lower())
Password = raw_input('Enter your desired password: ')
EP(Password.lower())
if Username.lower() in temp:
print 'That username already exists.'
else:
temp[Username.lower()] = Password.lower()
file_handle = open( my_file, 'w' )
p.dump(temp, file_handle)
file_handle.close()
temp = p.load('systemaccess.txt')
I think what you're trying to do is:
for item in metlist:
data1[2].append(item)To see what you did won't work, try typing data1[2]. It gives you ..thus there is only one element, and nothing at position 1.
While I agree with you that he should be using append instead of insert, I don't believe that his error is being caused by there only being one element:
>>> d = ['a']
>>> d.insert(1,'b')
>>> d
['a', 'b']
An even easier workaround for being able to import modules from ANY directory is to modify the sys.path variable at run time. So at the beginning of your code do something like this:
import os,sys
sys.path.append('/path/to_my/module')
import my_custom_module
And if you're working with a hard-coded windows path make sure you escape your escape characters (ie, C:\\Documents and Settings\\Administrator\\My Documents )
A better way to handle paths is using os.path.join()
>>> import os
>>> os.path.join('C:\\', 'Documents and Settings', 'Administrator', 'My Documents')
'C:\\Documents and Settings\\Administrator\\My Documents'
>>>
This is from the RichTextCtrl demo in the wx Docs and Demos package.
self.rtc = rt.RichTextCtrl(self, style=wx.VSCROLL|wx.HSCROLL|wx.NO_BORDER);
wx.CallAfter(self.rtc.SetFocus)
self.rtc.Freeze()
self.rtc.BeginSuppressUndo()
self.rtc.BeginParagraphSpacing(0, 20)
self.rtc.BeginAlignment(rt.TEXT_ALIGNMENT_CENTRE)
self.rtc.BeginBold()
self.rtc.BeginFontSize(14)
self.rtc.WriteText("Welcome to wxRichTextCtrl, a wxWidgets control for editing and presenting styled text and images")
self.rtc.EndFontSize()
self.rtc.Newline()
self.rtc.BeginItalic()
self.rtc.WriteText("by Julian Smart")
self.rtc.EndItalic()
self.rtc.EndBold()
self.rtc.Newline()
The code is too large to post here, but if you just look into RichTextCtrl you'll find your answers.
Here's the code for the and other formatting options on the toolbar/menubar:
def OnBold(self, evt):
self.rtc.ApplyBoldToSelection()
def OnItalic(self, evt):
self.rtc.ApplyItalicToSelection()
def OnUnderline(self, evt):
self.rtc.ApplyUnderlineToSelection()
def OnAlignLeft(self, evt):
self.rtc.ApplyAlignmentToSelection(rt.TEXT_ALIGNMENT_LEFT)
def OnAlignRight(self, evt):
self.rtc.ApplyAlignmentToSelection(rt.TEXT_ALIGNMENT_RIGHT)
def OnAlignCenter(self, evt):
self.rtc.ApplyAlignmentToSelection(rt.TEXT_ALIGNMENT_CENTRE)
Description from the vpython homepage:
VPython is a package that includes:
- the Python programming language
- the IDLE interactive development environment
- "Visual", a Python module that offers real-time 3D output, and is easily usable by novice programmers
- "Numeric", a Python module for fast processing of arrays
VPython is free and open-source.
Is anyone else getting a little tired of the "I Googled it and couldn't find anything" lie. "python sum list" brings up "total = sum(list_name)" as the second hit. Searching for "python adding list" gives both the sum() and a for() loop as examples on the fourth hit. But is it a complete waste of time to call them on it? Perhaps we should start posting the Google link. I am more than willing to help anyone with a real programming problem, but this wasting everyone's time can lead to fewer programmers who help because of all of the cruft that one has to wade through.
It is increasingly rare to find anything else on this forum. I left a forum before coming here solely based on this fact. Endless "I couldn't find the answer anywhere else..." and "I have a problem: I'm trying to make a program that '<copy_and_paste from Instructions for homework' and I'm stuck, don't have any code, so how would I go about this? And it's super urgent PLS help"
I wish I could just delete these posts and stop wasting our collective time.
Here's a comparison:
>>> a = [1,2,3,4,5,6]
>>> reduce(lambda y,x: x+y, a)
21
>>> sum = 0
>>> for i in a:
... sum+=i
...
>>> sum
21
>>>
Reduce is a way to perform a function cumulatively on every element of a list. It can perform any function, so if you define your own modulus function, it will repeatedly perform that function on each element of the list. In order to avoid defining an entire function for performing x+y, you can instead use a lambda function; which would benefit you more if you googled it, because I'm terrible at explaining them.
If you open up a python interpreter and type help(reduce), this is what you get:
>>> help(reduce)
Help on built-in function reduce in module __builtin__:
reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
>>>
HTH
I don't know if there is a module to simply find factors, but it is such a simple operation that you can make your own function... from the psuedo-code I posted eralier:
>>> def get_factors( inp ):
... ret = [ 1, inp ]
... for i in xrange( inp + 1 ):
... for j in xrange( i, 1, -1 ):
... if i * j == inp:
... ret += [ i, j ]
... ret.sort()
... return ret
...
>>> get_factors(6)
[1, 2, 3, 6]
Yes you should figure out the factors portion of your code first... one obvious problem might be that you never change b? So you're always multiplying h*1 ... and secondly, if h*b == n; wouldn't that make h and b both factors of n ??
You can do something like:
inp = user input
for i in (1, inp+1):
for j in (i, 1, -1):
if i*j == inp:
i and j are factors
return factors
>>> reduce(int.__mul__, L) 362880 >>>
Wow, I really like that.. never used reduce.
A suggestion for the OP: so that the above isn't so cryptic maybe it'll be easier to wrap your head around in this form:
>>> L = range(1,10)
>>> reduce(lambda x, y: x*y, L)
362880
>>>
You might want to rethink what the line c = factors [0:] * factors [:40]
is doing...
Look at this example for what happens using * on lists:
>>> [ 1, 2, 3 ] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> [ 1, 2, 3 ] * [ 2, 3 ]
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'list'
Yar. I actually looked at what your code does and it is extremely over complicating the matter... here's a much simpler method:
import string
letters = list(string.letters) + list(string.digits) + ['\n','\r',' ']
letters.sort()
numbers = [ ord(i) for i in letters ]
# Ascii values in the following list
result3=[83,97,109,117,101,108,32,83,109,105,116,104,13,10,13,10,84,\
104,97,110,107,32,121,111,117,32,102,111,114,32,108,111,111,\
107,105,110,103,32,116,104,101,32,111,116,104,101,114,32,119,\
97,121,32,111,110,32,116,104,101,32,105,110,99,114,101,97,115,\
101,100,32,108,101,118,101,108,115,32,111,102,32,116,111,120,\
105,99,32,99,104,101,109,105,99,97,108,115,32,105,110,32,116,104,\
101,32,114,105,118,101,114,32,114,117,110,110,105,110,103,32,97,\
108,111,110,103,115,105]
out_str = ''
for i in result3:
if i in numbers:
idx = numbers.index(i)
out_str += letters[idx]
print out_str
Oh!! also for the ascii values use another string comprehension!!!
>>> [ ord( lett ) for lett in string.letters ]
[97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90
PSST! Secret:
>>> import string
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
And PSST!!! To turn them into lists use list comprehension:
>>> [ lett for lett in string.letters ]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
>>> [ dig for dig in string.digits ]
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>>
If you search this forum for pygame you will find tons of examples of games that our forums members have creating using said module.
Either that or google.
Also, have you tried self.SetAutoLayout(True)
?
Ah, now it makes slightly more sense...
First things first: to remove an item from a list:
>>> mathches = [ 1,2,3,4,5 ]
>>> mathches.remove(3)
>>> mathches
[1, 2, 4, 5]
>>>
also, instead of nothing = 0
; which I'm assuming is just there for the syntax you could use pass
. Or simply reverse your logic and do away with a second case:
if not letter in matches[c]:
matches.remove(c)
That way you don't even need to worry about an else case. Because really you should never need a "do nothing here" line in your code.
If you look at the top right-hand side of the page you will find this white box contained in a larger green box. It's called a search box and it's very useful...
Also, vegaseat gave us all a very nice example of using fancy text and the like in the sticky post about wxPython... Take the time to do a little digging and you'll find your answer.
It's not exactly clear what this example is doing.. Plus this isn't a stand-alone example of the problem that you are seeing since we don't know what possible and matches are (ie, are they lists, tuples, dictionaries, strings?) ...
If you could provide us with an idea of exactly what you're trying to do with an example of input -> output it would help greatly!
For the many of you who still want to know the solution, make variable 'a' a global:
That or simply pass a to test:
words = ["aero", "aesthet", "andr", "arch", "arch", "ast", "baro",\
"biblio", "bio", "cardi", "chron", "cosm", "crat", "cycl", "dem", "dont",\
"dogma", "dox", "esth"]
answers = ["air", "sense", "man", "man", "chief", "ancient", "star", "weight",\
"book", "life", "heart", "time", "universe", "rule", "circle", "people",\
"tooth", "opinion", "belief", "feeling"]
a = 0
def test(a):
a = a + 1
print "What does", words[a], "mean?"
ans = raw_input("> ")
if ans == answers[a]:
print "Correct!"
test()
else:
print "That is incorrect. Try again."
a = a - 1
test()
test(a)
You're never reading your file... you're literally trying to read from sys.stdin. This is wrong and I think you may have misunderstood your prof.
You need to open the file via open(file_name, mode)
... then read from there....
Yes, what vegaseat suggested... either that or use an escape (a la \) before the text as in:
>>> t = '!,.?\'$%'
>>> print t
!,.?'$%
>>>
Same thing goes for double quotes within double-quoted string:
>>> t = "!,.?\"$%"
>>> print t
!,.?"$%
>>>
...Adding on to the previous posts; another thing to keep in mind is that EVERYTHING in python is an object; meaning that the file handle (object) has methods and members that facilitate line-by-line iteration.
To get a list of the contents of a folder you can use the os module's listdir() function.
Then loop over each item, and use split('.') on the name to add '_output' before opening the output file.
Looking through the Date Parsing section of the feed parser reference page reveals the following: that the dateHandler functions "return a single value, a 9-tuple Python date in UTC".
Which means that the time that is returned is standardized to GMT (I still don't like the UTC naming convention)... If you would like to display it as a different timezone you will need to get the utc offset value and simply add it to the hours. Otherwise, I would just leave it in UTC so that all posts are standardized.
I think your best bet would be to simply print the value of contents and then ask the user for a new value. Otherwise you will need to figure out how to prompt for input and then subsequently write to the stdin ... you can access stdin/stdout via sys.stdxxx, which will allow you to use write, read, etc. Perhaps you can make use of those to create a custom text input function.
Please use code tags when posting blocks of code, and icode tags when posting small snippets. This will make sure your formatting is not lost to the ether; and will also make your posts easier for us to read; thereby making it easier for us to help you. You can read up on code tags here
It depends heavily on the format that you are receiving the time data in. Could you provide us with an example of EXACTLY what you are getting?
If it is coming in as a string with the Time Zone then iyou simply use time.strptime(), which will make it very easy for you.
By getting rid of your infinite loops (ie, while p == 0:
. You need to realize that since p is never changed within that loop, it will continuously run. I assume that you really want an if statement. Here is an example of how you would use an if:
>>> a = 0
>>> if a == 1:
... print 'The value of a is a 1!'
... elif a == 2:
... print 'The value of a is a 2!'
... else:
... print 'The value of a is neither 1, nor 2. It is', a
...
The value of a is neither 1, nor 2. It is 0
>>>
You have to realize that 9 times out of 10 when you have a syntax error it's actually at the line above. So if you peer at the line above n = raw_input("what is the persons name")
you'll notice that you're missing a trailing parenthesis, as I mentioned in my last post.
There are 7 syntax errors that I found in your code. 4 of which are infinite loops.
You're missing a parenthesis at the end of the v = float(raw_input(
line.
Also close = print "thank you for using a George Lee program"
is incorrect syntax. You can either print that string or save it using close =
. Which is it?
You are right as to why this is happening; a variable and a function sharing the same name.
From within the class scope, self.number is the variable and self.number() is the function. When you initialize the class, it goes through and recognizes each function then calls __init__ (at least that's how I understand it). Since init is assigning something to self.number (which is already defined as a function), the reference to this method is over-written by the value of the passed-in parameter. Why not use self._number = number
?
makeSentence is a function of the class App. It should be called as such App.makeSentence
c = t.open_session()
if timeOut != None:
c.settimeout(timeOut)
This is an excerpt from a function that sends a command to the Server. Keep in mind that I'm using paramiko here, so it probably won't work for you unless you too are using paramiko.
The usage depends on what interface you're using to make your client/server (I've only ever used paramiko); however you could probably make use of a global timeout setting. This way after a set amount of time the recv() operation will throw a timeout exception, which you can catch and handle however you would like.
I am the same way. Before coming to this forum I used to prowl another forum, which has degraded into abysmal territories and I will never again return to; however, I used to ask a question, and simply by typing out my queries I would in fact brainstorm with myself and solve the problem before a single member was able to reply.
So I'm right there with you ;)
What are you using to connect to your server? I've worked with paramiko and know that it provides a universal timeout, which will throw a TimeoutException when any transaction with the server/client goes beyond the desired limit... Perhaps something along those lines would get you what you need.