Wow, why is Python so specific about the 3 being a float in order for it not to round the answer? Thanks though Gribouillis, as I now learned something new today :)
Wow, why is Python so specific about the 3 being a float in order for it not to round the answer? Thanks though Gribouillis, as I now learned something new today :)
Yeah, I don't know what's wrong with this. I tried print float(3/4*3)
and only recieved 0.0
... So now we know that it's not a problem of your code per se, but just the way the math is being done.
I don't have the pygame module, but can you put a print
statement saying anything (just something to check for) into the if
statement with the line ballSpeed[1] = ((-ballSpeed[1]/4*3))
to make sure that the if
statement is actually being executed? And why is that segment encapsulated within two pairs of brackets? Wouldn't it be fine as just ballSpeed[1] = -ballSpeed[1]/4*3
?
Why don't you just loop a function that opens each file one at a time and writes the processed information to the corresponding output file? Have an array of the .cvs files and for every one in the array, call the processing/writing function.
Oh, tkinter. I can't really help you there then. I've only used wxPython before.
Let me get one thing straight: Are any of the array values ever going to be more than one word long? Because earlier in this thread you asked how to deal with it in that situation...
If you don't fully understand the re
module (I don't), you could always have it look for the first word in that two-word value (in the array), and then if it found the first one, see if the word following it in the input is the same as the second word in the two-word value. Sorry if I didn't make that very clear. But anyways, I think that Gribouillis' idea would be the best, as it's straight-forward and clean looking.
Can you post your current code so that I can check it? Thanks :)
If you're using wxPython, then I wrote a heavily commented snippet below showing it. There might be a better way, but this is all I could come up with at the moment. If any other users have a different idea, please post it too!
import wx
# First screen
class Screen1( wx.Panel ):
def __init__( self, parent, id ):
wx.Panel.__init__( self, parent, id )
self.parent = parent # Make 'parent' accessible to all functions on this screen
# Widgets
self.szr = wx.BoxSizer( wx.VERTICAL )
self.btn = wx.Button( self, 100, "Change Screen" ) # Make a button to change screens
self.Bind( wx.EVT_BUTTON, self.OnChange, id=100 ) # Bind an event to it
# Layout
self.szr.Add( self.btn, 0, wx.ALIGN_CENTER )
self.SetSizer( self.szr )
self.SetSize( parent.GetSize() ) # Set this panel to take up the whole frame
# Button event to change screens
def OnChange( self, event ):
parent = self.parent # Save the 'parent' variable before being destroyed
self.Destroy() # Destroy the current panel
Screen2( parent, -1 ) # Set the new screen suing the saved parent variable
# Second screen
class Screen2( wx.Panel ):
def __init__( self, parent, id ):
wx.Panel.__init__( self, parent, id )
# Widgets
self.szr = wx.BoxSizer( wx.VERTICAL )
self.txt = wx.StaticText( self, -1, "Panel 2" )
# Layout
self.szr.Add( self.txt, 0, wx.ALIGN_CENTER )
self.SetSizer( self.szr )
self.SetSize( parent.GetSize() ) # Set this panel to take up the whole frame
# Run the app
app = wx.App()
frame = wx.Frame( None, -1, "MyGUI", size=(200, 150) ) # Make …
Phew, I just figured out an answer to your first question. It also easily solves that second one.
def P():
a = "a"
aa = "aa"
b = "b"
bb = "bb"
text = raw_input( "Enter Text: " )
temp = []
for character in text:
if character == "a":
temp.append( aa )
if character == "b":
temp.append( bb )
OutputText = " ".join( temp )
print OutputText
P()
This takes the inputted string, and goes though each character in it. When it finds an "a" or a "b", it adds the values "aa" or "bb" (respectively) to a list (temp). Then, it just adds all the items in this list together with a space inbetween each of them. This new string (OutputText), in the end gets printed out. Hope that helps :)
I'm gonna try looking at how to fix the first problem, but as for the second one, if you use print aa,
and print bb,
(note the comma at the end), it'll print the aa on the same line as the bb, but will automatically add one space in between them by doing so. The normal print
without the comma prints the specified value and then adds a carriage return, so when print
is called next time, it'll be on a new line.
Right now though, I'll try to figure out that first issue you're having :)
Oh, are you running this on Linux? I'm just using the default .exe that came on the download for Windows. My laptop (which has my Linux on it) is down at the moment, so I can't try it on there.
I was able to run it with my website and it told me all the links were fine and dandy, but I have no idea how to find the output file on the windows version. I'll try to look around for it and get back to you about it though.
So can I see this VB script? Then I'll try and see what I can do about it :)
Hmm... I just downloaded the linkchecker module and tried to figure it out for myself, but I don't even know how to use it in my own scripts. Can you give me an example of the code you're using right now? Then I might be able to help with your problem. Thanks
I know your English isn't too great, and it is a hard language to learn, but I can't really understand what it is you're asking. Sorry, but could you maybe clarify it?
Hello EAnder - welcome to DaniWeb. I myself only got into Python about a year ago, after deciding to give up on Java and C++; luckily I found that Python is fast, easy, and most importantly, fun.
Anyways, to get back on topic, I created the basis for a sort of artificial intelligence a while back, but gave up on it after a little bit. I hadn't gotten into making the computer give feedback/sentences to the user, but it's able to recognize around 2500 words (plurals, all conjugations, etc.) based on word lists it reads from/writes to. I've always really been interested in AI and such, and after looking at Eliza, decided I'll try rebuilding my old AI and try to figure out ways to streamline/advance it.
I don't know of any tutorials on AI or AL, but just started programming my AI from my own ideas. Due to this, my system might be badly designed, but if I make any significant advances in the next while, I'll post my source here on DaniWeb for you to look at.
Good luck with your programming!
Ah, thank you VERY much for that! :)
Hi, just a quick question but I couldn't find an answer to it. Say I have 3 variables, "a", "b", and "c". I want to assign each one a value of None. The only way I know of doing this is:
a, b, c = None, None, None
Is there a way to cut it back to just one instance of None because it's the same for all? Like:
a, b, c = None
The only problem is that this returns the "Too many values to unpack" error. Thanks for any help you can give!
Oh thank you so much! I don't know why I got the original idea to move through every row when I could've done it like that.
Yes that's right. Sorry if I'm not too clear. I only got in PHP and MySQL 2 days ago.
Hmm.. if it spares all the rows, then it's ok, but if it deletes one row it gives me the same error. The correct row gets deleted and everything, but it gives the error anyway. When I made my table, I only specified NOT NULL for the id column, but should I have specified it for the other columns I was making (such as 'usern', which I used VARCHAR(20) for)? Is that causing the problem?
It's good because by changing my SQL query to what you suggested, it only clears that one row and leaves the others. The only problem left is that it still gives me the error output:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /www/99k.org/s/h/a/shadwick/htdocs/db/delete_data.php on line 28
I have this page on my site: shadwick.99k.org/ in my folder called db. Where it says the error originates is line 28 which is this one:
while( $row = mysql_fetch_array( $result ) ) {
Any ideas?
Hi, I couldn't get this to work, but I was using a PHP script to go through the rows in a table in my database and if it found a specific value, to delete that row. However, it deletes ALL the rows no matter what I do and throws an exception after. Any help is appreciated:
// connect (host, usr, and pwd are previously defined, correctly)
$cid = mysql_connect( $host, $usr, $pwd );
// get all columns from the table 'accounts', $db was previously defined (database name)
$query = "SELECT * FROM accounts ORDER BY id";
$result = mysql_db_query( $db, $query, $cid );
// run through each row looking for column 'usrn' with the value 'caughtusername'
while( $row = mysql_fetch_array( $result ) ) {
if( $row['usern'] == "caughtusername" ) {
$id = $row[ 'id' ];
$query = "DELETE FROM accounts WHERE id=$id";
// execute the deletion statement
$result = mysql_db_query( $db, $query, $cid );
echo "<b>Deleted: </b>" . $row['usern'] . "<br>";
}
else {
echo "<b>Spared: </b>" . $row['usern'] . "<br>";
}
}
Oh awesome - I got it working using exec
. I never knew that it existed... Thanks for solving my problem!
I no longer got an error about the import function, but now, however, when I call a function from the "primary" module, it gives me an error saying: NameError: name 'primary' is not defined.
So when I call function "draw()" from module "primary", it gives me the above error. Any ideas?
Hi, I was wondering how to get around a problem I was having with eval(). I have a list of strings and each one is the name of a python file found in the same directory as the current script. I was it to import these modules to use in the current script, but: eval( "import" + modname ), where 'modname' is the script's name, causes an error. Is there any way to have the script import any found scripts or would I have to explicitly add "import <name>" for each script? Thanks!
names = [ "main", "secondary", "tertiary" ]
for item in names:
eval( "import " + item )
The code above makes sense, but python gives me this instead:
import primary
^
SyntaxError: invalid syntax
Hi, I'm using wxPython (the latest version) and was wondering how to get rid of the scrollbar on the wx.TextCtrl (multiline) object. I couldn't find anything with Google or the search on the forums. Thanks!
Oh, it works! Thank you so much for the help.
Hi, I was wondering if it's possible to call a function using a string that is the exact same as the name of the function. Here's an example in which I wanted to make 4 bitmap buttons using a for loop, and the event bound to each one would be named similarly to the name of icon on it:
self.buttons = []
self.buttonBitmaps = [ "New", "Edit", "Delete", "About" ]
for i in range( 0, 4 ):
self.image = wx.Image( "images/" + self.buttonBitmaps[ i ] + ".png",
type=wx.BITMAP_TYPE_ANY ).ConvertToBitmap()
self.tempButton = wx.BitmapButton( self.panel2, ID_BUTTON + i,
self.image, size=( 30, 30 ), pos=( i * 30, 5 ) )
self.buttons.append( self.button )
self.tempButton.Bind( wx.EVT_BUTTON,
"self.On" + self.buttonBitmaps[ i ] + "()" )
As you can see, the first button I wanted to call the function "self.OnNew()" when clicked. I know that this isn't working because I put a string in the event function, whereas it wants a function. Is there any sort of way I could turn the string into a reference to the function?
>>>
eval("2*2/4")
1
Ok thank you so much!
Hi, I have a string that I want converted to an integer. I tried int() but it doesn't work because of what my string (as an example) is "2*2/4". I want it to make that into an integer and just put the answer (1).
Is there a simple way to do this? Thanks.
I was just going to print normal text anyway, so thanks very much for the help!
Python often -- very often! -- has slick ways of doing things. In this case, the .count() method is a slick way of optimizing your function:
Oh - that's quite a handy function! There are so many more little helpful things like count() in Python than there is in Java. Thank you for the enlightenment :)
This is how your script should look:
def Numero(name):
alpha = { 'a': 1, 'b': 2, 'c': 3, 'd': 4}
counter1 = 0
counter2 = 0
while counter1 != len(name):
for key, value in alpha.items():
if key in name[counter1]:
counter2 += value
counter1 += 1 # Indented into the while loop
return counter2
# This line calls the function and sets myFunc' to counter2
myFunc = Numero("abcd")
# Print the function to see what it equals...
print myFunc
I'm pretty new to Python aswell, and am still very confused with the way for loops are structured (as opposed to Java or C++). I think the issue you have is with the indentation. The second to last line, 'counter1 += 1' should be within the while loop shouldn't it? Otherwise the loop will keep going and be infinite. If you just indent that line so that it's within the while loop, it should fix the problem. :)
I was wondering if it is possible in Python to send a job to the user's printer. I have a string, and I wanted to be able to print it out on a piece of paper. I have wxPython installed and imported into the app if that makes any sort of difference... Thanks in advance!
SOLVED: I see what I did wrong. I finally found a tutorial on building an application like this, and got it all figured out. Thanks anyway to anyone who looked at this.
I was making a simple application with a GUI built with wxPython. I have created and layed out the main menu, and when the user clicks a button, it is *supposed* to make a different set of controls appear, getting rid of/hiding the main menu. I was wondering how to do this. The function fires, but the results appear behind the main menu, and if I click again, they appear on top. This means the set of controls that the main menu is made of don't actually go away. Does anyone know what's wrong? Here's my entire code (It is my first attempt at wxPython, so if it looks badly strutured, please tell me - I'm not sure how it's supposed to be typed i.e. def or class...):
import os
import wx
import wx.html
class MainWindow(wx.Frame):
def __init__(self, title):
super( MainWindow, self ).__init__( None, size=(475,400), title=title )
self.SetBackgroundColour( "white" )
self.MainMenu()
self.Show( True )
def MainMenu(self):
# Title image panel
self.panel1 = wx.Panel( self, 1, (0,0), (475,175) )
titleImgLoc = wx.Image( "Images/Title.png", wx.BITMAP_TYPE_ANY ).ConvertToBitmap()
self.titleImg = wx.StaticBitmap( self.panel1, -1, titleImgLoc, (0,0), (475,175) )
self.sizer1 = wx.BoxSizer( wx.VERTICAL )
self.sizer1.Add( self.titleImg, 0 )
self.panel1.SetSizerAndFit( self.sizer1 )
# Buttons panel
self.panel2 = wx.Panel( self, 2, (20,250), (425,90) )
self.newBtn = wx.BitmapButton( self.panel2, 100, wx.Image("Images/Icons/add button.png", wx.BITMAP_TYPE_ANY).ConvertToBitmap(),
wx.EVT_BUTTON( self.panel2, 100, self.AddRecipe ) )
self.newBtn.SetToolTip( wx.ToolTip("Add a new recipe.") )
self.viewBtn = wx.BitmapButton( self.panel2, 200, wx.Image("Images/Icons/view button.png", wx.BITMAP_TYPE_ANY).ConvertToBitmap(),
wx.EVT_BUTTON( self.panel2, 200, self.ViewRecipe ) )
self.viewBtn.SetToolTip( wx.ToolTip("View your list of recipes.") )
self.searchBtn = …
Python is quite an exceptional language, and although powerful, you can learn how to make simple applications quite easily. I got a basic education of Python just by searching Google for tutorials, and asking questions on DaniWeb. Once you understand how it works, you can then get into more complicated stuff like Tkinter and wxPython for GUIs. Just get Python 2.5 and you can start programming/learning. Have fun :) !
Thank you so much. I completely forgot about closing it. Thanks again!
I don't know if this idea has already been added, but beginners can create an address book. That was the first real project I undertook. Ask the user for: name, address, phone, cell, fax, etc. Then store the data in a .txt file. Let the user search people in the list, create new listings, delete listings, and edit existing ones.
I just started learning Python about 2 days ago, and I threw this program together, just to get the hang of it. The program just creates a file named "PythonTest.txt" in the same directory as the .py file. The user can then enter lines that are written to the .txt file. When they stop, it reads the file back to them. The only part giving me trouble right now is that when I call the function I created to read the file, none of the lines from the file show up. I know the file has text because I've opened up the .txt file and seen the text in it. Can anyone help with it? Here's all the code in the .py file:
filename = "PythonTest.txt"
# Define the readFile function
def readFile():
print filename + ":\n\n"
infile = file(filename, "r")
for line in infile.readlines():
print line # Should print line from file but doesn't...
# Define the changeFile function
def changeFile():
cont = "y"
outfile = file(filename, "w")
while cont == "y":
intxt = raw_input("Enter line:\n\t")
outfile.write(intxt + "\n")
cont = raw_input("Keep writing?\t(y/n)\n\t")
readFile() # Call the readFile function
# Change file lines
change = raw_input("Do you want to change/create data in " + filename + "?\t(y/n)\n\t")
if change == "y":
changeFile() # Call the changeFile function
else:
print "Closing..."
# Make the program close here...