I read somewhere that you should avoid using a leading underline in a variable name. It is supposed to have a special meaning in Python. I can't find anything more detailed. Does anybody know?
I read somewhere that you should avoid using a leading underline in a variable name. It is supposed to have a special meaning in Python. I can't find anything more detailed. Does anybody know?
Does Python have a static variable like C has? I like to avoid a global variable for the usual reasons.
Note: A static variable in a C function will retain its last value.
I guess I must be a geek, since I would rather use my computer to write programs and surf the net than watch TV.
The international forces act as police, training cadre for the Iraqi armed forces, and as construction crews to rebuild damage done to Iraqi infrastructure during the war.
I have buddies in the US Army that tell me that the few Dutch soldiers are too busy with their hairnets to do any good! You must be sponsored by the Shell Oil Company that has huge interests in Iraq.
Is that the endangered feline with the short tail?
We went into Iraq without real goals. Well, the original goals (removal of WMD) were fake.
If we would have spend the trillions of borrowed Dollars on alternative energy, we wouldn't have to worry about gas prices, home heating and home cooling. Research, development and manufacture of alternative energy like wind, solar, bio-diesel, ethanol, butanol, fusion (cold or hot) would have created a lot of good paying constructive jobs.
Well, now we don't have any money left, and future generations of hamburger flippers are stuck with paying off the debt! Just my limited opinion.
I just went through this one:
http://www.mcafee.com/us/support/index.html
Any question will send you into a perfect circle!
When I grew up, our neighborhood was so poor, that even the rainbow came only in black and white!
I have been in Las Vegas with some friends on the weekend, and the beer or shots are free as long as you play the penny slots. Of course, these folks want you to loosen up and waste your money on their machines or the tables.
Can you show us the batch file?
You can use a global variable within a function by prefixing it with the word "global". Here is an example:
# keep track of how many times a function has been accessed
# using a global variable, somewhat frowned upon
def counter1():
global count
# your regular code here
count += 1
return count
# test it
count = 0 # a global variable
print counter1() # 1
print counter1() # 2
print count # 2 variable count has changed
print
The trouble with a global variable is with using it somewhere else in a large program. Everytime you call this function its value will change and may lead to buggy code.
One solution is to use the namespace of the function, making the variable more unique. It gives you a hint where it is used, for example:
# avoid the global variable and use the function namespace
def counter2():
# your regular code here
counter2.count += 1
return counter2.count
# test it
counter2.count = 0 # now count has counter2 namespace, notice the period
print counter2() # 1
print counter2() # 2
print
Write a Python function that creates a box outlined by stars/asterisks (*). The function should display a box of x stars width and y stars height.
The next step would be to put some text into the box maintaining the star outline.
The ultimate function should take a text string and auto-outline it with the star box.
*****************
* *
* Happy coding! *
* *
*****************
Thanks Henri,
I needed not only the day of the week, but also the day of the month, so I searched the Python code snippets and found an old snippet from vegaseat called "Date and Time handling in Python" at:
http://www.daniweb.com/code/snippet218.html
He talks about the timetuple, and this tuple contains both data. So I put this in the days of year loop:
# timetuple = (year,month,day,hour,min,sec,weekday(Monday=0),yearday,dls-flag)
day_of_month = next_day.timetuple()[2]
day_of_week = next_day.timetuple()[6]
# Friday is 4th day of the week
if day_of_week == 4 and day_of_month == 13:
print next_day
and it works. My first real project! Smooth!
Thanks, that works well. Now I need a hint, how do I check if the day is a Friday?
How do you loop through an entire year showing each day's date?
Make a crayon drawing or coloring program for the younger relatives. Python and Tkinter should have all the things you need. I know I have seen a doodle program somewhere, that could be the start.
A note from vegaseat: The wxPython docs and demo download has a doodle program you can build upon.
How about a program to calculate the phase of the moon. I have seen a C program to do this, Python should be a lot easier, once you know the formula. Google for the formula, do a console version or embellish with some graphics if you want to. Both Tkinter and wxPython allow you to draw on a canvas.
Make a Molecular Weight calculator. The user enters for instance the formula for salt NaCl and the program looks up the atomic weight of sodium and chlorine and adds them up.
A dictionary with element:weight pairs would make it easy. You also have to design some kind of parser that figures out molecules like water H2O. Here you have to add up hydrogen twice and oxygen once.
Things get a little more challenging for the parser with toluene, since the user could enter C7H8 or C6H5CH3. Elements like silicon Si have to be entered that way and not as SI, since your parser would look at it as a combination of sulfur S and iodine I.
Since the right data is already there, you can expand the program to do elemental analysis, giving the percent of each element in the formula. Happy coding!
Thanks, I will check the panels and the sizers out next!
Thanks Vega,
I can use your code sample as a template, as I play around with the capabilities of the wxPython GUI.
You have used the frame directly to put your button widgets on. Other code samples seem to use a panel on a frame to put their widgets on. Any reason for that?
Also, why are you using self.button1 = Button( ... ) and not just button1 = Button( ... )?
What is the best way to establish a wxPython event handler for a mouse click, button and so on? I have looked at a number of sample codes and the event handlers differ all over the place.
I was just playing around with string functions. String.lower() converts all upper case letters in the string to lower case letters.
string1 = "Fahrenheit"
print string1.lower() # result: fahrenheit
This way the user can enter Fahrenheit or fahrenheit or F or f and the if compare works.
// I think clock() is only available for Windows, a tick is ~ 1 ms
// if you need time like the string returned by ctime(), then you have to do some processing
#include <iostream>
#include <ctime> // clock(), time(), ctime(), time_t
using namespace std;
int main()
{
time_t t;
time(&t);
cout << "Today's date and time: " << ctime(&t) << endl;
int clo(clock()); // start clock
// put your function to be timed here
int clo2(clock() - clo); // difference end clock - start clock
cout << "time elapsed = " << clo2 << " ticks" << endl;
cin.get(); // wait for key press
}
Sorry, I am on a borrowed computer. There is a code snippet here on DaniWeb that uses a BGI for C++. You may check the web site referenced in the snippet.
This is my first experience with Python's Tkinter GUI. I want to write a program where the result of an interim calculation is displayed on a label. Later in the program I want to use this result in another calculation by simply clicking on the label.
This is what I have set up for a test:
from Tkinter import *
root = Tk()
label1 = Label(root, text='')
label1.pack(side=TOP)
# do some caculation and format result
pi_approx = 355/113.0
str1 = "%.4f" % (pi_approx) # 3.1416
# show result in label text
label1.config(text=str1)
# more code here
mainloop()
I can bind the label to a mouse click, but can't figure out how to retrieve the label's content. Any advice how to do this? There must be some Tk mavens out there.
Vega,
your are right! In the real world it is more important to be out on the market with a working program at the right time. There are a few cases, where it is critical to milk the speed of program execution for every microsecond.
An electronic version of an Index Card File would be interesting, like a collection of recipes for cooking. You could search quickly using a limited set of keywords/titles, or slower using the general text of each card.
If you want to be fancy, you can add a feature to cook for two people, five people or even 12.
I have a hunch that driving a printer depends a lot on the operating system and the installed drivers.
Thank you all,
I will be trying all suggestions after I download version 2.5, to see which one I am most comfortable with.
Tuple indexing looks much like C, but then one should not copy C style into Python.
I am fairly familiar with C, but new to Python. Does Python have something like the handy C conditional expression? For example:
// C conditional expression x = a ? b : c;
// if a is true then x = b else x = c
// here used to print 10 numbers in each row
// the numbers are separated by tabs, each row ends with a '\n'
#include <stdio.h>
int main()
{
int k;
for(k = 0; k < 100; k++)
{
printf("%3d%c", k, (k % 10 == 9) ? '\n' : '\t');
}
getchar(); // make the console wait
return 0;
}
Looks a lot like the hex digest of NIST's secure hash algorithm, known as SHA-1. Might also be the competing MD5 algorithm. These things are used to send passwords on in e-mail and are tough to crack!
Remember one of the basic rules of computing, ideally the flow in a program should be:
get data
process data
show result
After I said this, I got interested myself to write the flow, here is my overblown code:
# find cost of a square inch of pizza given cost and size/diameter
# a small program to show flow of data via functions
def main():
# get data
cost = get_cost()
size = get_size()
# process data
area = calc_area(size)
cost_sqinch = cost_per_area(cost, area)
# present result
show_result(cost_sqinch)
def get_cost():
# avoid using input(), raw_input() gets a string, so convert to float
return float(raw_input("Enter the cost of the pizza: "))
def get_size():
# again, avoid using input()
return float(raw_input("Enter the diameter of the pizza: "))
def calc_area(diameter):
"""calculate the area of a circle"""
pi = 3.1416 # good enough
radius = diameter/2.0
return pi * radius * radius
def cost_per_area(cost, area):
return cost/area
def show_result(cost_sqinch):
print "The cost per square inch of pizza is $%0.2f" % (cost_sqinch)
main()
Dani,
I find the popularity order rather goofy!
If some stranger looks at the snippets, she expects the titles to be ordered, as imperfect as they are!
Take a look at the C++ code snippets here on Dani Web. The snippets are in a goofy order, but you can search them.
This one might do for drawings:
http://www.daniweb.com/code/snippet176.html
If its just text:
http://www.daniweb.com/code/snippet83.html
Okay children, stop the name calling!
grunge man, you forgot to iclude <iostream>
#include <cstdlib> // system()
#include <iostream> // cout, cin, endl
using namespace std;
int main()
{
int k, n;
cout<<"type a number: ";
cin >> k;
n = k*3;
cout << "\ntimes three = " << n << endl;
system("PAUSE");
return EXIT_SUCCESS; // optional with C++
}
For some existing C code take a look at:
ftp://ftp.simtel.net/pub/simtelnet/msdos/graphics/jpegsr6.zip
I would set up a vector of doubles, load it with the resistance values using push_back(). This will take care of size too. You can load from a file or user input.
Now loop through the vector and invert all the resistance values. You can sum up the inverted resistance values with accumulate(). The result needs to be inverted to get the parallel resistance.
When I look at code snippet there is no little poll located to the right of the snippet description!
This must be for a different grade of people?
I had posted a small C snippet a while ago and wanted to show it to a friend. I couldn't find it, so I searched for my name, but it didn't come up. There is good news however, I finally found it by searching for my name on Google.
Have you ever defragmented your hard drive?
User rating? How does a user rate a snippet?
Also, if I look at all the "five star ratings" the second criteria "views" is not in order!
What is the order of the code snippets, they used to be in alphabetical order by title. Now I can't even figure it out, and it is very hard to find anything.
Does PP2E refer to the examples in the book "Programming Python 2nd Edition" by Mark Lutz? I just borrowed a copy from a friend. This book spends a lot of space on the Tkinter GUI. I am a little frustrated with the inadequate index.
I will avoid using the input() function then. How would you write a custom numeric_input function using raw_input()?
I am starting to learn Python and have a good crasp of C++ from school. I must say, that I find this thread very interesting information. Thanks all of you who contributed!
Python uses the directories listed in PYTHONPATH to find a module. How can I assure that the module I am importing is on this list of paths?
I keep hearing that the eval() function is unsafe. It is a nice function, because you can use it like
print eval("2.5*49.7/(23+3.14)")
and it will solve the math.
Is there any way to protect against some nasty minded person to enter a "os.system(command)" where the command will erase a file or all files?
I am here because I find the members of DaniWeb an interesting bunch of nonconforming individuals. Do I here a violin in the background?
I am tired of the many lockstep (goose step) folks trained by FOX News.
Where can you find more info on the tkinter text widget?
I have played with Tkinter GUI just a little and find it very nice.
I have the following code, for example:
price = 50.00
tax = price * 0.08
print "Tax = $",tax # Tax = $ 4.0
As you can see there is a space between $ and 4.0. Is there a way to avoid this? I haven't done much Python coding.