I think you are looking for subprocess.call() if you just want to run the program "tasklist.exe", instead of using "print". See here http://blog.doughellmann.com/2007/07/pymotw-subprocess.html
I think you are looking for subprocess.call() if you just want to run the program "tasklist.exe", instead of using "print". See here http://blog.doughellmann.com/2007/07/pymotw-subprocess.html
Report: Flip Flops Can Kill You http://www.ktla.com/news/landing/ktla-flip-flops,0,1421175.story
"Two New York Daily News reporters recently tested their flip flops after walking around the city for four days and found that the rubber shoes picked up about 18,100 bacteria of the five most prevalent varieties found. Among the bacteria detected was the potentially deadly Staphylococcus aureus."
"Dr. Charles P. Gerba -- professor of microbiology at the University of Arizona -- says that 93 percent of flip flops will have fecal bacteria after three months of wear, and 20 percent will have E. coli."
Please post the error message to avoid this type of "looking for 'not in' as bad syntax when it is really a colon" errors. Same thing for "not in" is a bad descriptor. The error message probably has other info which possibly points to "never_save.readlines()" as the real problem.
tuple (4,22,51) = 1515 so this means i have 1515 lines in my file that have the above tuple init
How do you know this is accurate? Have you counted them, or tested on a smaller sample and counted those to make sure it is correct? It is impossible to test with huge amounts of data. You have to create a small sub-set and work with that. The following code stores record numbers for each key tuple using a dictionary of lists, and then prints all of the associated records. You can, of course, pick and choose which ones you want to print using random numbers, etc.
tuple_test = (("a", "b", "c"), ("d", "e", "f"), ("g", "h", "i"))
##--- create some test data
records_test = []
records_test.append(tuple_test[0])
records_test.append(tuple_test[2])
records_test.append(tuple_test[1])
records_test.append(tuple_test[0])
records_test.append(tuple_test[0])
records_test.append(tuple_test[1])
##--- a dictionary with the tuple as key, pointing to a
# list of record numbers
record_num_dic = {}
for rec_num, tuple_rec in enumerate(records_test):
print "processing", tuple_rec, "rec number =", rec_num
if tuple_rec not in record_num_dic:
## add a new key pointing to an empty list
record_num_dic[tuple_rec] = []
record_num_dic[tuple_rec].append(rec_num)
for key in record_num_dic:
print key, record_num_dic[key]
rec_num_list = record_num_dic[key]
for rec_num in rec_num_list:
print " ", rec_num, records_test[rec_num]
I would suggest using lsusb, but this will list all usb devices, so if you have a printer or mouse, or possibly an sda drive, you will have to weed them out.
It has only 37 characters and not 100001.
Of course it does as that is the default. Changing to 110,000 significant digits meant that it took as long to convert to decimal as it did to convert to a string (of course). Oh well.
You could try cypes and convert via C, which should be a lot faster. Also note the surprising difference when using the decimal class below.
import decimal
import datetime
#**setup part**
j = 0
myint = 1
while j < 100000:
j = j + 1
myint = myint * 10
#** end setup section**
#****** start relevant section ******
start_time = datetime.datetime.now()
mystring = str(myint)
print "str =", datetime.datetime.now() - start_time
start_time = datetime.datetime.now()
mystring = "%s" %(myint)
print "% s =", datetime.datetime.now() - start_time
#****** end relevant section ******
j = 0
myint = decimal.Decimal(1)
while j < 100000:
j += 1
myint = myint * decimal.Decimal(10)
start_time = datetime.datetime.now()
mystring = "%s" % (myint)
print "decimal =", datetime.datetime.now() - start_time
# -----------------------------------------------------------------------
# my results
# str = 0:00:06.853879
# % s = 0:00:06.828796
# decimal = 0:00:00.000054 (if you are using MS Windows, this
# will come out as zero because Windows
# only goes down to milli-seconds)
Effbot is a good resource. You might want to bookmark it and New Mexico Tech's site http://infohost.nmt.edu/tcc/help/pubs/tkinter/ for future reference. Please mark this post "Solved" so no one wastes their time on a solved post.
thanks woooeee im going to try all this out thanks for the advice i'm goona try this out i want to have one key with numerous values which are my record numbers uuff im just getting myself in a muddle :( thank you i will post back soon
What are you going to try? Take Gribouillis' advice and use just a part of the file for testing. First, read the records one at a time and print each one so you know that part is correct, as you are only using 20 records or so.
Then, create the tuple and add it to a dictionary and print the dictionary after each add so you know that part is correct. Once that is done, post your code, and state what you want to do next for some more advice. You also have to define "random" in more concrete terms. What if you want the second record that contains the tuple (a, b, c) and there was only one record with that tuple? Or do you want to choose any random record? Why must it have a specific tuple and how do you decide which tuple to use?
According to effbot, you can use wrap=NONE http://www.google.com/search?client=opera&rls=en&q=tkinter+wrap+text&sourceid=opera&ie=utf-8&oe=utf-8 I've never used it though.
Please don't double post. Stick with one thread and mark the other "Closed" or "Solved". And a title like "someone please help!!!!!!!!!!" will get less responses not more. It does not state a specific problem and indicates someone who is looking for someone to write free programs for them. The few who donate some time answering questions would soon be overwhelmed if we allowed that to happen.
Try some print statements,
match={}
for rec_num, v in enumerate(a):
rec_num+=1
print "\n Next rec: rec_num is now", rec_num
for values in a:
print " values =", values[0], values[2], values[3])
triple=(values[0], values[2], values[3])
if not match.has_key(triple):
match[triple] =0
print " triple is now", values
print " second dictionary add", triple, rec_num
match.setdefault(triple,[].append(rec_num))
Since the dictionary contains zero for every key, it appears that this line
match.setdefault(triple,[].append(rec_num))
is not working correctly. Are you getting error messages? Also, read up on dictionaries and decide if you are going to use "if not triple in match" (which you define as a dictionary of one integer), or "setdefault" (which you define as a dictionary of lists). When you get a clean dictionary, you can use the rec_num associated with each key to access that record, although you might want to allow for duplicate keys, i.e. use a dictionary of lists instead of a dictionary of one integer. You appear to have just copied code and do not understand what is happening. It is almost impossible to get something to work if you don't understand it, so add print statements and anything else that helps clear up the picture.
Notice the duplicate line
for i in range(x):
You should be able to use
def initialiseGrid(x,y):
grid = []
for h in range(x):
grid.append([0])
for j in range(y-1):
grid[h].extend([0])
return grid
Generally, it is considered bad practice to use "i", "l", or "o" as single digit variable names as they can look like numbers.
Post any code you're having problems with. I as said earlier, it is fairly straight forward, so don't waste too much time reinventing the wheel.
The problem is here
rows = [0] * x
run the following code and see what you get
rows = [0] * x
for row in rows:
print id(row)
##
## you should see that all of the memory addresses are the same
## meaning that you have the same object in the list several times,
## so when you change one, they all change because they are
## the same object. Instead, try the following
##
rows = [[0] for x in range(0, 3)]
for row in rows:
print id(row)
Also, you don't allow for errors, as in these lines for example.
z = raw_input("Enter '1' to play the computer or enter '2' to play another human: ")
if z.isdigit():
Do this instead:
z = 0
while z not in ["1", "2"]:
z = raw_input("Enter '1' to play the computer or enter '2' to play another human: ")
z = int(z)
if z == 1:
etc.
And your input for x and y can be done the same way, but consider using one function and passing the string literal "How wide would you like your game? (4 - 8) ", and the check list ["4", "5", "6", "7", "8"] and letting it return the choice, instead of the redundant code.
The final thing that I see, and I didn't take a close look at your code, is
def drawGrid(grid):
for element in grid:
print element
for i in range(x):
print …
See the last post in this thread http://www.daniweb.com/forums/thread210760.html It has links to reading files and online starter books for Python.
What is in entry_list, class instances? The simple solution is to create a list of lists with each sub-list containing [field_to_sort, class_instance] and just use the built in sort method.
sorted_ent_list = entry_list.sort(key=entry_T.get_word())
If entry_list is a list of class instances, then you would have to use something like
sorted_ent_list = [ entry_list[x].get_word(), entry_list[x] for x in range(0, len(entry_list))]
sorted_ent_list.sort()
but that is untested and highly suspect.
LadderMills, developed by Professor Wubbo Ockels – perhaps most famous for being the first Dutch astronaut in space - are rotating loops of kites which catch the wind at a height of 10 kilometres. The wind is twenty times more powerful at this height than at ground level. The LadderMills are attached to a generator on the ground by means of a cable.
A picture is here http://www.lr.tudelft.nl/live/pagina.jsp?id=8d16d19a-e942-45aa-9b52-48deb9312e92&lang=en
I have a log which keeps IP of the visitors of my blog
Start with file open and readlines to get the file into memory. Then decide how you are going to identify an IP address. If it is the only thing on the line that has digits, or is always in the same string such as "IP Address 123.34.789" then it is easy to filter out. Here is a simple example that you should be able to use to start with http://pythonstarter.blogspot.com/search/label/python%20readlines http://pythonstarter.blogspot.com/2009/04/python-readline-example-for-newbie.html This is a link to (mostly) online books and tutorials http://linkmingle.com/list/List-of-Free-Online-Python-Books-freebooksandarticles
woooee: I've seen you mention this before. What makes you choose multi-process over multi-threads? I don't use either, so I'm just wondering if you see a particular advantage in one over the other.
Laziness partly. I only wanted to learn one, and wanted a way to kill a process and be able to pass data back and forth. Multiprocessing/pyprocessing has a kill function and uses a list or dictionary to store common data, so game over from my perspective.
ok now the count and GUI works fine because aim using root.update() in the loop. but for some reason the label just wont update
You would use a StringVar and update it with the new time or whatever. The following code is an example, where the entry box and the label widget both have access to the same StringVar, so when you change the value in the entry box, the label box is automatically updated.
import Tkinter
class EntryTest:
def __init__(self):
self.top = Tkinter.Tk()
self.str_1 = Tkinter.StringVar()
label_lit = Tkinter.StringVar()
label_1 = Tkinter.Label(self.top, textvariable = label_lit )
label_1.pack()
label_lit.set( "Test of Label")
label_2 = Tkinter.Label(self.top, textvariable = self.str_1 )
label_2.pack()
entry_1 = Tkinter.Entry(self.top, textvariable=self.str_1)
entry_1.pack()
self.str_1.set( "Entry Initial Value" )
cont = Tkinter.Button(self.top, text='PRINT CONTENTS',
command=self.getit, bg='blue', fg='white' )
cont.pack(fill=Tkinter.X, expand=1)
exit= Tkinter.Button(self.top, text='EXIT',
command=self.top.quit, bg='red', fg='white' )
exit.pack(fill=Tkinter.X, expand=1)
entry_1.focus_set()
self.top.mainloop()
##-----------------------------------------------------------------
def getit(self) :
print "getit: variable passed is", self.str_1.get()
##===============================================================
if "__main__" == __name__ :
ET=EntryTest()
"after" is just a timer, so it won't help you here as it will just stop the program for a period of time and then continue. I use multiprocessing/pyprocessing, not threading so can't help you there. To make the picture appear when someone clicks something, you would use a callback. I used the following program to test callbacks and it does something similiar to what you want. This program uses a checkbutton to copy a string to the right-hand box, and remove it if checked again which should give you a framework which you can adapt to your program. It also uses the Pmw extension to Tkinter becuase Pmw has scrolled widgets built in. If you don't want to install Pmw you can still see how a callback works when a specific button is pressed from the source code [the buttons() function]. http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm
from Tkinter import *
import Pmw
class CB:
def __init__(self, master):
master.geometry("290x200+5+10" )
self.master = master
self.button_num = 0
self.button_dic = {}
self.maps_list = self.retrieve_maps()
print self.maps_list
self.var_list = []
self.cb_list = []
self.choice_list = []
## frame to contain the list boxes
self.frame = self.scrolled_frame('Available', 150)
self.exit_button()
self.label_box()
self.buttons()
##-------------------------------------------------------------------
def buttons(self):
""" one checkbutton for each item in the list
"""
for map_c in self.maps_list:
self.button_dic[self.button_num] = map_c
var = IntVar()
var.set(0) ## off=default
self.var_list.append(var)
b = Checkbutton(self.frame, text = map_c, variable=var)
b.pack()
self.cb_list.append ( b )
def handler ( event, self=self, button_num=self.button_num ):
return self.cb_handler( event, button_num )
b.bind ( "<Button-1>", …
is there a way to make a scrollbar widget automatically scroll to the bottom?
Use scrollbar.config ()
scrollbar.config( command = listbox_widget.yview )
listbox_widget.see(listbox_widget.size())
I think it is something like this for a text widget
Text.see(Text.END)
in a Text widget, how would I be able to make everything...colored
Most all of Tkinter's widget's have a background and foreground option. See the docs.
You'll have to post the Tkinter part of the code. There is no root.mainloop() in the code you posted.
I just read this again and it probably should be more like the following (which seems clumsy), but like I said earlier, you'll have to work out the details.
port_read = True
data = read_the_port()
while True:
if port_read:
## print the 'Null' to see what it contains and what
## length the program will see it as
print "'Null' found " , len(data), data
while len(data.strip()) > 2: ## (same data) may have to adjust the "2"
data = read_the_port()
port_read = False ## Null found
if not port_read:
if len(data) > 2:
process_the_data( data )
port_read = True ## don't process again until the
## next piece of data, i.e. Null is found
data = read_the_port()
(like green, or hasPerson) that I'd like to be able to filter the list with.
Use a dictionary of lists, with the key being "green" or whatever, pointing to those pictures. You can then send all of the lists in the dictionary, or just the list for one key, to the Tk widget.
I might want to load something like ten members, then start the window, then load the rest if possible.
You would have to use threading or multiprocessing. That is read 10 pictures, start the Tk program in one thread and load the rest of the pictures in another process or thread. Note that the container that is holding the pictures would have to be common to both processes or threads.
Computers are faster than serial ports, so you are probably getting several reads (and processing) the same data more than once, and reading and trying to process the null between each piece of data. For serial reads you want to do something like this pseudo code:
port_read = False
data = read_the_port()
while True:
if port_read:
## print the 'Null' to see what it contains and what
## length the program will see it as
print "'Null' found " , len(data), data
if len(data.strip()) < 2: ## may have to adjust the "2"
port_read = False ## Null found
if not port_read:
process_the_data( data )
port_read = True ## don't process again until the
## next piece of data, i.e. Null is found
data = read_the_port()
This all depends on what and how data is being sent to the serial port of course.
2. Is there any way to convert it to read only? Normally the user is able to modify the text but I want it to be read only.
Use the codebox
"Display some text in a monospaced font, with no line wrapping.
This function is suitable for displaying code and text that is
formatted using spaces.
The text parameter should be a string, or a list or tuple of lines to be
displayed in the textbox."
http://easygui.sourceforge.net/current_version/pydoc/easygui.html#-codebox
So you can send a list of lines to be printed. Sweet.
myapp = MyGUI()
There is no MyGUI() class or function so who knows what myapp contains. I don't see an import Tkinter either. Also, try a myapp.mainloop() right after the myapp = MyGUI to test if the mainloop() is working properly, and then print myapp in the GUILoop class and where it is created, to see if it is being passed correctly. HTH.
There is no difference, as far a calling a function goes, between calling a function within or without a program. The following works for me with the calc() function contained in the same program file.
from Tkinter import *
def calc(one, two, result):
def addition():
add = one + 1
print(add)
result.insert(END, 'first='+str(one)+' second='+str(two)+' addition='
+str(add))
def subtraction():
subs = two - 1
print(subs)
result.insert(END, 'first='+str(one)+' second='+str(two)+' subtraction='
+str(subs))
result.insert(END, 'first='+str(one))
addition()
result.insert(END, 'second='+str(two))
subtraction()
class App:
def __init__(self, parent):
frame = Frame(parent.title("primary window"))
frame.pack()
self.lbfirst = Label(frame, text="First number:")
self.lbfirst.grid(row=0,column=0)
self.first = Entry(frame)
self.first.grid(row=1,column=0)
self.lbsecond = Label(frame, text="Second number:")
self.lbsecond.grid(row=2,column=0)
self.second = Entry(frame)
self.second.grid(row=3,column=0)
self.number=Button(frame, text="calc", fg="red", \
command=self.call_calc)
self.number.grid(row=4,column=0)
self.result = Listbox(frame)
self.result.grid(row=5,column=0, columnspan=5, sticky=N+S+E+W)
def call_calc(self):
calc(float(self.first.get()), float(self.second.get()), \
self.result)
root = Tk()
app = App(root)
It works fine for me.
mlist = [ "first = 3", "second =", "third = 1"]
item_list = ["third = 1", "second = 2", "junk"]
for item in item_list:
x = -1
print "\ntesting", item
if item in mlist:
x = item[-1]
print "if: x is now", x
else:
x = 0
print("else")
print x
x is being set to one in both of your examples. The only place that can come from is the file, so you changed the wrong file or something similiar. Post the output of the print mlist statement.
Run this piece of code and then take a look at where you can add some print statements to your code so you will know what is actually happening.
item = "third = 1"
if item.find("third"):
print "item found at position", item.find("third")
else:
print "item NOT found, value returned =", item.find("third")
#
if item.find("first"):
print "item found at position", item.find("first")
else:
print "item NOT found, value returned =", item.find("first")
You also want to take a look at the "startswith" string method as that is more in line with what you are doing.
Note the quotation marks, so it is just a string so you can substitute anything you like.
SQL_str="CREATE TABLE %s (name_last VARCHAR(20), age INT)" % (name_to_use)
cur.execute(SQL_str)
You would use a variable like "table_name" in the first line here, and pass that to the connect function. If you are creating a new table, then you would also have to input the field names and type, or use a standard layout for all databases.
table_name = "people_db"
con = sqlite.connect(table_name )
# Get a Cursor object that operates in the context of Connection con
cur = con.cursor()
##--- ONLY CREATE FIRST TIME
cur.execute("CREATE TABLE people (name_last VARCHAR(20), age INT)")
You should state what you are trying to accomplish and perhaps someone will help with that. We are not your personal answering machine. Please don't waste everyone's time.
Store the record number in the dictionary, (this code was not tested)
match={}
for rec_num, values in enumerate(lines):
truple=(values[0], values[2], values[3])
if not match.has_key(truple):
match[truple] =[]
match[truple].append(rec_num)
for key in match.keys():
if len(match[key]) > 1:
print "more than one record found for", match[key]
for rec_num in match[key]:
print " ", lines[rec_num]
print
It;s just personal preference, but I prefer multiprocessing to threading (If you are using Python2.5 or lower, then you will have to download pyprocessing and substitute "processing" for "multiprocessing" in the code below). http://pyprocessing.berlios.de/ This is just something used to test a dictionary and a list as a way to pass variables to one of the two processes that are running.
import time
from multiprocessing import Process, Manager
def test_f(test_d, test_l):
test_d['2'] = 2
test_d["QUIT"] = False
while test_l[0] == "False":
print "test_f", test_d["QUIT"], test_l
test_d["ctr"] += 1
time.sleep(1.0)
def test_f2(name):
for j in range(0, 10):
print " test_f2", j
time.sleep(0.5)
if __name__ == '__main__':
manager = Manager()
test_d = manager.dict()
test_list = manager.list()
test_list.append("False")
test_d["ctr"] = 0
test_d["QUIT"] = False
p = Process(target=test_f, args=(test_d,test_list,))
p.start()
## p.join()
p2 = Process(target=test_f2, args=('P2',))
p2.start()
#--- Change the dictionary/list so the first process ends
time.sleep(2.0)
test_d["QUIT"] = True
test_list[0] = "True"
print "\ntest_d/list changed"
time.sleep(3.0)
print "terminate first process just to be sure"
p.terminate() ## p terminated here
print "data from first process", test_d, test_list
please has anyone got any suggestions im still stuck
Suggestions about what? If you want 100 random samples, then you can select the dictionary's keys randomly.
import random
##--- create dictionary with 1000 keys
test_data_d = {}
for j in range(1001, 2001):
test_data_d[j] = "data for key %d" % (j)
##--- keys_list is in hash order (appears random) and not
## numerical order which actually works better for randomness
keys_list = test_data_d.keys()
##--- 10 random keys is enough
stop = len(keys_list) - 1
for j in range(0, 10):
random_num = random.randint(1, stop)
this_key = keys_list[random_num]
print j+1, test_data_d[this_key]
Note that any random number can appear more than once, so might want to store the numbers in a list and if that random number has already been used, choose another one.
You can use the decimal module if you want very, very precise results http://docs.python.org/library/decimal.html#quick-start-tutorial
One of the hits from a search on this forum
http://www.daniweb.com/forums/thread95473.html
There are two problems
while True:
x=f.readlines()
You read the entire file on every loop, so you willl always get the first rec of the newly read list.
if not x: break
x.next()
This may exit if you have any blank lines in the file.
Instead, you want to loop through all of the records with a for() loop
input_list=open("cmd.batch.txt").readlines()
for rec in input_list:
print rec
if len( rec.strip() ) < 1:
print " that rec was an empty line"
I tried last night (about 12 hours ago) and it was down then. It is still down this morning. It is hosted in the Netherlands, so I doubt it's connected to the Twitter/Facebook stuff. I also Googled for mirrors, but Python doesn't host mirrors anymore. Too bad.
Of course this is the weekend that I was going to install 3.X and start converting. I could use Active State's version, but I think I'll wait until python.org comes back up.
It's just
self.conn = sql.connect(dbname)
Here's some code (just a bunch of crap really) from when I was first testing SQLite that shows how to add, change and delete recs. Note that when you retrieve records you have to test for None, i.e. no records found in db. That threw me for a curve when first starting out.
import sqlite3 as sqlite
##----------------------------------------------------------------------
def add_rec(cur, con):
##cur.execute("INSERT INTO people (name_last, age) values ('Yeltsin', 72)")
cur.execute("INSERT INTO people (name_last, age) values ('Putin', 50)")
cur.execute("INSERT INTO people (name_last, age) values ('Putin', 50)")
cur.execute("INSERT INTO people (name_last, age) values ('Putin', 50)")
cur.execute("INSERT INTO people (name_last, age) values ('Yeltsin', 70)")
##--- add using a tuple instead
person_tuple = ('Barisinov', '30')
cur.execute("insert into people (name_last, age) values (?, ?)", person_tuple)
con.commit()
##----------------------------------------------------------------------
def change_recs_test(cur, con):
cur.execute("UPDATE people SET name_last==:who_dic WHERE age==:age_dic",
{"who_dic": "Chg_Yeltsin", "age_dic": 70})
con.commit()
##----------------------------------------------------------------------
def del_recs_test(cur, con):
who = "Putin"
age=50
cur.execute("DELETE from people where name_last==:who_dic and age==:age_dic",
{"who_dic": who, "age_dic": age})
con.commit()
print "-" * 30, "AFTER Delete"
print_all_recs(cur)
print
##----------------------------------------------------------------------
def print_all_recs(cur):
# Execute the SELECT statement:
print "Printing all recs"
cur.execute("select * from people order by age")
# Retrieve all rows as a sequence and print that sequence:
print cur.fetchall()
#==========================================================================
if __name__ == "__main__":
# Create a connection to the database file
table_name = "people_db"
con = sqlite.connect(table_name )
# Get a Cursor object that operates in the context of Connection con
cur = con.cursor()
##--- ONLY CREATE FIRST TIME
cur.execute("CREATE TABLE people (name_last VARCHAR(20), …
You have to commit
self.conn.commit()
after the adds
the next job is to create a search function which would allow someone to search for flights which fly on a certain day, and then it would bring up all the corresponding flights and thier details (e.g flight times etc)
How are you going to do this? You have a list of dictionaries so you will have to parse the list and check each dictionary, in which case the list is redundant, since you could achieve the same result just parsing a dictionary with one entry per flight. Perhaps you want two dictionaries, the first has the flight number as key, since that is unique, pointing to a tuple with all of the oher info. A second dictionay would be indexed on date and point to a list of filght numbers for that date, so you could then print all of the infro from the first dictionary for all the the filght numbers found. In a large scale database, you would use SQL, but I am assuming that you want to do it with dictionaries.
Edit: I don't use a csv parser either, but you should be able to do this:
for data_tuple in csvParser:
print len(data_tuple), type(data_tuple)
if len(data_tuple) > fields_used:
## now Origin=data_tuple[0], Destination=data_tuple[1], etc
## and you can just ignore the field created by the last comma
Break the file into groups that start with the "define host" record
So, you want to append each record to a list, but first:
If "define host" is found in the record then send the list to a function to process it (test for 'nod3001' and/or the IP address, and write to a file if that's what you want to do with this group).
Re-define the list as empty, i.e. ready for the next group.
Now append the record to the list
Finally, you will have to process the last list as there was no next record with "define host" to process it.
If you want further help, post the code as you have it so far, and we can help with that. The general rule is that words get answered with words and code gets answered with code. Sorry, but there are too way many people who want freeprograms.com to even consider writing code from scratch.
Here is an example that checks for a correct choice based on the contents of the choice dictionary, and only prints body parts that have not already been chosen. Generally, a dictionary is used in Python to create a menu because you can define everything in one place, and only have to change the dictionary if you want to add or subtract options. I have not tested this much so it is up to you. Also. you should decide what happens when someone runs out of choices/body parts. In this example it would be
limbs_dic["game_over"] = True
You would have to have a while() loop or
if limbs_dic["game_over"] == False:
before each question.
def answers( correct_answer, choice, limbs_dic ):
if choice.upper() != correct_answer:
print "The real answer was ", correct_answer
print
limbs_dic = chooseLimb(limbs_dic)
limbs_dic["angerRate"] += 1
else:
limbs_dic["correctAns"] += 1
print "Correct"
return limbs_dic
def ask_questions(limbs_dic):
######################## DISPLAY INTRO #########################
print " Mr. Taylor vs The BattleBot! v1.0"
print
print "In order to prove yourself worth sparing to the universe, you must answer the following questions correctly."
print "Failure to do so will result in the teacher losing a limb by the battle bot!"
print "Your teacher's hard work is at stake!"
print
print "Each incorrect answer will raise the BattleBot's hatred towards you, the student!"
print "After the BattleBot loses his temper, he will stab you!"
print
print "<BattleBot> Good luck, earthling. You are going to need it..."
print
################### QUESTION 1 ###################### …
I hope you understand why it works. There are some good books online that may help with your programming like http://diveintopython.org/toc/index.html
This may or may not help. First you want to find out if 2 circles do intersect. You can find the distance from the center of circle A to the center of circle B by constructing a right triangle. If (radius_A + radius_B) is greater than the distance you have an intersection.
A line perpendicular to the line that connects the two centers will intersect the two points where the circles intersect, so you can use the divide by two method. Start by drawing a line from the center of one circle to the edge (one radius) on a point that you know is outside of the intersecting parts (or try in increments of 90 degrees). The distance from that point to the center of the second circle should be the radius of the second circle if you are at the intersecting point. You now divide the angle in half that was used to draw the line to the edge of the first circle and see if it is inside or outside the intersecting portion (distance to the center of the second circle is greater or less than the radius). You then know which half to use to divide in half again. You can look at one million numbers in 21 passes using the divide by two method.
This link has a good picture of what I was clumsy in describing. You want to find BA and BD. It also says you can use the law of cosines …
The problem is in
loseLimb(choice, armRight, armLeft, legRight, legLeft, head)
You return one of the booleans but don't catch any returns at the calling statement.
loseLimb(choice, armRight, armLeft, legRight, legLeft, head)
#
def loseLimb(choice, armRight, armLeft, legRight, legLeft, head):
if choice == 1:
print "The BattleBot destroys Mr. Taylor\'s right arm!"
print "Mr. Taylor screams in pain and doesn't like you anymore."
print
armRight = True
## return is here *******************************
return armRight
#---------------------------------------------------------------------
# The problem is that you have no idea which variable is being
# returned. You want to pass and return a list or a dictionary instead.
#----------------------------------------------------------------------
# with a dictionary
limbs_dic = {}
limbs_dic['armRight'] = False
limbs_dic['armLeft'] = False
limbs_dic['legRight'] = False
limbs_dic['legLeft'] = False
limbs_dic['head'] = False
#
#--- pass the dictionary and keep the returned dictionary
limbs_dic = loseLimb(choice, limbs_dic)
print "limbs_dic =", limbs_dic ## test that the changes were made
#
def loseLimb(choice, limbs_dic):
if choice == 1:
print "The BattleBot destroys Mr. Taylor\'s right arm!"
print "Mr. Taylor screams in pain and doesn't like you anymore."
print
limbs_dic['armRight'] = True
return limbs_dic
You can also change chooseLimb() so that it only returns a correct answer and do away with the
while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
but I don't have any more time until tonight. Start with Shadwickman's suggestion and have one funtion do all the work, which will get the code …