You could insert the length of your secret message string as the first value.
jephthah commented: ahah +6
vegaseat commented: nice catch +11
You could insert the length of your secret message string as the first value.
There are at least two ways to write this. The first example puts the condition to not exit the while loop into the while statement:
n = 1
while n != 0:
try:
# works on Python2 and Python3 versions
n = int(input("Enter a number (zero to exit): "))
print("You entered integer %d" % n)
except:
print("Enter a number only!")
print("Done")
The second way is to make an endless loop and then exit via break in an if statement within the loop. I find that syntax easier to read:
while True:
try:
# works on Python2 and Python3 versions
n = int(input("Enter a number (zero to exit): "))
print("You entered integer %d" % n)
if n == 0:
break
except:
print("Enter a number only!")
print("Done")
The try/except traps the entry of a non-numeric value and gets back into the loop.
Have fun with Python!
Thanks jlm699!
Going to the terminal and running command
sudo apt-get install python-pygame
works like a charm.
I downloaded file pygame_1.8.1release.orig.tar.gz from the Ubuntu site. My silly newbee question is: "What Linux command do I use to install/setup it to Python?"
I finally solved the pesky Vista problem, I bought a used Dell notebook with Linux/Ubuntu on it. I enjoy the new OS a lot, goodbye Vista! No more endless waiting on startup and shutdown, no more silly security popups! It was easy to download/intsall all the open source software I needed from the Ubuntu site. Things like Open Office, Python, SPE, DrPython and some good graphics software.
I would avoid using the Python shell to write multiline programs. Use one of the Python editors like IDLE, wirte your program, save it and run it. This would have given you an error message like:
NameError: name 'timesflipped' is not defined
Using FengG's advice your program should look like this:
import random
coin_heads, coin_tails, timesflipped = 0,0,0
while timesflipped <100:
coin_flips = random.randrange(2)
if coin_flips == 0:
coin_heads = coin_heads + 1
else:
coin_tails = coin_tails + 1
timesflipped += 1
print "Out of 100 flips " + str(coin_heads) + " were heads and " + \
str(coin_tails) + " were tails."
I don't remember if SQLite is installed by default or not. A test is of course
import sqlite3
Even though you may not use it, there are various apps that do. Also, check out the programming forum there http://ubuntuforums.org/forumdisplay.php?f=39
Module sqlite3 works just fine. I have successfully tested a fair number of Python programs from my collection.
I am also getting used to the Mozilla Firefox web browser.
I just bought an inexpensive used Dell notebook that has Ubuntu/Linux as an operating system. Compared to Vista this is sweet.
It came with Python25 installed, but it was easy to use the Add/Remove application feature to get open source software from the Ubuntu site. I downloaded/installed Stani's Python Editor (SPE) IDE with just a click of a button, that also installed wxPython.
In the Ubuntu application list I also found the Eric4 IDE. I clicked the button and it downloaded and installed. This also installed the PyQT4 package. Now I got interested in the PyQT4 GUI toolkit.
There are tons of programming applications on the list, it's like a candy store. So next was QTdesiger, BOA and Sun's Open Office. Yes, I like Ubuntu and Linux, learning to use it quickly.
If anyone alse uses Ubuntu (or other Linux packages) and Python, please share your experiences, tips and wisdom. I am just an Ubuntu newbee.
... the professor told them that socialism would also ultimately fail because when the reward is great, the effort to succeed is great; but when government takes all the reward away; no one will try or want to succeed.
Could not be any simpler than that….
Great story, makes a lot of sense. So who are the lazy socialists? The 13 million Americans that are unemployed, the companies that laid them off, or the fat bankers that ran off with the money?
Computers are definitely female, here are the male reasons:
1) Most men who have one don't understand them.
2) Amongst themselves they talk in an incomprehensible language at high speed.
3) You need to tell them every trivial thing you want from them.
4) All of a sudden they refuse to cooperate, and you can't figure out what you did wrong. They refuse to give you any meaningful error message.
5) You always have to buy new stuff for them.
6) If you keep a computer for too long it becomes old and you will constantly wish you could just dump it somewhere.
We need some actual examples of your lists and the sort order you want.
Now it doesn't work because '/' gives a result of type float. You got to use another criterion like the modulus operator.
See the recent thread:
http://www.daniweb.com/forums/post849602-2.html
From the US Bureau of Labor Statistics, somewhat sobering ...
Looks like the curve is mildly exponential in nature, reflecting the fact that unemployment creates unemployment. I should go out and buy a Hummer to help GM.
Never vote for anybody, and you won't be disappointed!
If they ask for money up front, then it is most likely a ripoff!
An intelligent insect species could take over. Survivors of a galactic gamma ray burst.
In Python versions before Python3 if you use '/' for division and divide two integers, the result will always be an integer.
It looks like you only want a 2D matrix, since you are talking about rows and columns.
First of all, do not use list as a variable name since list is a builtin function in Python. Lists have a function append(), so use it. Commonly a basic matrix is populated with zeroes, which you then can replace as needed.
Here is a working example:
# create a 2D matrix of zeros and populate it
def make_list(size):
"""create a list of size number of zeros"""
mylist = []
for i in range(size):
mylist.append(0)
return mylist
def make_matrix(rows, cols):
"""
create a 2D matrix as a list of rows number of lists
where the lists are cols in size
resulting matrix contains zeros
"""
matrix = []
for i in range(rows):
matrix.append(make_list(cols))
return matrix
mx = make_matrix(3, 3)
print(mx)
print('-'*34)
# now populate the zero matrix
# for instance put a 5 in row 0, column 0
mx[0][0] = 5
# put a 7 in row 1, column 1
mx[1][1] = 7
# put a 9 in row 2, column 2
mx[2][2] = 9
print(mx)
"""
my result -->
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
----------------------------------
[[5, 0, 0], [0, 7, 0], [0, 0, 9]]
if you pretty it up -->
[
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
----------------------------------
[
[5, 0, 0],
[0, 7, 0],
[0, 0, 9]
]
"""
I was known for my shooting skills.
Ah, I enjoy my cup of fresh brewed coffee!
I wonder if there is a religion that forbids coffee?
The CDC estimates that each year 76 million Americans get food poisoning, more than 300,000 are sick enough to be hospitalized and 5,000 die.
Right now, you are not to eat any products that contain pistachio nuts from California.
Hehehe! It's time to mint $100 coins so we can get cars, boats and , yes, goats from the vending machine.
If we create computers and robots with AI, will they eventually evolve to take us (the creators) over?
In the US alone the sky is full with 5000 airplanes on the average. In the winter time in places like Minesota, inhabitants discover unexplained patches of yellow snow at times.
Wow and ouch, debasisdas!
Glad you missed that, maybe a paperless society is your goal now?
The number of folks in US prisons is about 2% of the number of employed folks. However, minorities have been particularly affected: One in nine black men ages 20 to 34 is behind bars.
Here % is the modulo operator. It gives you the remainder of a division.
print(3 % 3) # 0 --> 3 is completely divisable by 3
print(6 % 3) # 0 --> 6 is completely divisable by 3
print(5 % 3) # 2 --> division leaves a ramainder of 2
Another thing, in your function you came up with -->
def int(start,finish):
using int would be a solid nono, since int() is a function built into Python and you would make that fuction inoperable!
Yes it's possible, you may have to consult the Python manual to understand it all:
# index the lines that contain given search words
data = """\
this test finds how many times
certain words like text
appear in the data
remember this is just a test
"""
filename = "logfile.txt"
# create the data file
fout = open(filename, "w")
fout.write(data)
fout.close()
# read the data file back in as a list of lines
logfile = open(filename, "r").readlines()
KEYWORDS = ['test', 'text']
index_dict = {}
for ix, line in enumerate(logfile):
for word in line.split():
if word in KEYWORDS:
index_dict.setdefault(word, []).append(ix+1)
print(index_dict) # {'test': [1, 4], 'text': [2]}
The function enumerate() gives you the line number and works like counter. Also, using the print() function makes this code work with Python25 and Python30.
With huge indentations like you have in your code my editor will go up in smoke! I will let someone else try it first! :)
Years ago I met a guy in downtown Minneapolis snapping his fingers to chase away flying elephants.
His answer: "Do you see any? See it works!"
Starfish don't have brains.
Not all of us get government pensions and government healthcare. There are plenty of hard working folks who used to make $40,000 a year and now have to support their family flipping hamburgers at $14,000 a year without health insurance. I would say that they are at least 50% unemployed.
Judging from the filth that food processing plants get by with, I don't think the FDA would be much of a threat! Being covered with raw hamburger could be considered a benefit.
May Vista die the death it deserves.
A handful of dried turkish apricots and bowl of multigrain Cheerios bathing in 1% fat milk.
( see: www.GeneralMills.com/Health )
You should have gotten a DaniWeb t-shirt!
In the US unemployment numbers are blatantly underestimated. The governmant just released a sugarcoated number (U-3) of 8.5%, being months behind, leaving out many folks.
A more honest number (U-6) at least considers the folks who have been unemployed long enough to drop out of official unemployment support, this number is 15.9% at present.
Another number also considers people who are stuck in a low paying or a partime job. They generally end up with less than half the pay they would get for their skill level in more normal times. So it seems to be fair to call them 50% unemployed. Then the unemployement number would stand at 19.8% right now (according to ShadowStats.com).
Where are unemployent numbers in your country?
One of your problems is that you named the button and the function the same! Name your button "button_update" or something.
Other problems are the '\' in Label and that name is not assigned a value.
Sometime it pays to write a short test code:
# set up a short test with Tkinter's
# Label, Entry, Button and Text widgets
# check some of the interactions
from Tkinter import *
def update():
data = entry.get()
# clear any old text
text.delete(1.0, END)
text.insert(INSERT, data)
# clear the entry
entry.delete(0, END)
root = Tk()
# for testing
name = "Franko"
s = name + " is:"
# create needed widgets
label = Label(root, text=s)
entry = Entry(root, width=25)
button = Button(root, text="Update", command=update)
text = Text(root, width=25, height=1)
# place the widgets in a grid
label.grid(row=1, column=1)
entry.grid(row=1, column=2)
button.grid(row=1, column=3)
text.grid(row=2, column=1)
# put the cursor into entry field
entry.focus()
root.mainloop()
If you are using Python30, please note that the module md5 is gone! The md5 algorithm has shown some obvious weaknesses and has been replaced with improved hashes, check the module hashlib. For those who need backwards compatibility there is hashlib.md5()
Well i think i can post the first one. Beautiful Soup!
http://www.crummy.com/software/BeautifulSoup/All you need to do is an automatic python 3 conversion on it and then it works fine with python 3. So enjoy :)
This will not work! Python30 does not have a module called 'sgmllib'. The error is:
Traceback (most recent call last):
File "<string>", line 248, in run_nodebug
File "C:\Python30\Atest30\Bull\BS_ParseHtml1.py", line 4, in <module>
from BeautifulSoup import BeautifulSoup
File "C:\Python30\Atest30\Bull\BeautifulSoup.py", line 54, in <module>
from sgmllib import SGMLParser, SGMLParseError
ImportError: No module named sgmllib
vidaj, wow! Thanks for letting us know why you were using Python30. Somebody mention the BeautyfulSoup conversion on a thread here, but it seems to be BS.
Anyway that you may want to show your code here?
Want to use a nice file dialog window to open files for your console program? Here is a way:
# use Tkinter's file dialog window to get a file name
# with full path, that you can use in a console program
# askopenfilename() gives one selected filename
# with Python25 use ...
import Tkinter as tk
from tkFileDialog import askopenfilename
# with Python30 use ...
#import tkinter as tk
#from tkinter.filedialog import askopenfilename
root = tk.Tk()
# show askopenfilename dialog without the Tkinter window showing
root.withdraw()
# default is all files
file_name = askopenfilename()
# now you can use the file_name in your program
print(file_name) # test
Ouch! My baddy!
BeautyfulSoup needs sgmllib.
If you are smart, stay away from Python30 and use Python version 2.5.4 the most stable production grade version.
Consider Python26 and Python30 experimental versions at best.
The error is in line 17
You can use this approach to get an input dialog without the Tkinter window:
# use Tkinter's dialogs to ask for input
# dialogs are askfloat, askinteger, and askstring
import Tkinter as tk
from tkSimpleDialog import askstring
root = tk.Tk()
# show askstring dialog without the Tkinter window
root.withdraw()
name = askstring("Name", "Enter your name")
print(name)
With Python 30 use:
# use Tkinter's dialogs to ask for input
# dialogs are askfloat, askinteger, and askstring
# mofified for Python30
import tkinter as tk
from tkinter.simpledialog import askstring
root = tk.Tk()
# show askstring dialog without the Tkinter window
root.withdraw()
name = askstring("Name", "Enter your name")
print(name)
Somebody mention this in another thread.
You can convert BeautifulSoup.py from Python25 to Python30 with 2to3.py and it will work with Python30. You can use this little utility program:
# convert a Python25 code file to a Python30 code file
# generates a backup file and overwrites the original
# file with the converted file
# to be safe copy the file to be converted into the
# working directory of this program
import subprocess
# the Python2x code file you want to convert ...
python2x_scriptfile = "BeautifulSoup.py"
subprocess.call([r"C:\Python30\Python.exe",
r"C:\Python30\Tools\Scripts\2to3.py",
"-w",
python2x_scriptfile])
]
yes it is if you use the string function (below) e.g.
b = "d" b.isupper() # will return false b.islower() # will return true
this is something i came up with in 5 mins that does it quicker and is easier to read:
def checker(): b = raw_input("enter a char") if b.isalpha(): print "%s, is a char" % b if b.isupper(): print "%s, is upper" % b else: print "%s, is lower" % b elif b.isdigit(): print "%s, is a digit" % b
Why are you using tabs for indents?
The simplest way would be to use Python's rot13 encoding to encode your password and then use the encoded password in your program.
First use this code to create the encoded password:
# example of simple encoding/decoding using Python's 'rot13'
# alphabet is shifted by 13 positions to nopqrstuvwxyzabcdefghijklm
# so original 'a' becomes 'n' or 'A' becomes 'N' and so on
# (non-alpha characters are not affected)
# pick a password (will be case sensitive)
pw = "Peanutbutter"
# encode your password
encoded = pw.encode('rot13')
# print the encoded password and copy to your program
print(encoded)
"""
my output -->
Crnahgohggre
"""
Now use the encoded password in your program, something like this:
# example for using a rot13 encoded password
def get_password():
# give it three tries
for k in range(3):
# copy from your encoding program
encoded = "Crnahgohggre"
password = raw_input("Enter your password: ")
if password == encoded.encode('rot13'):
return True
return False
def start():
if get_password():
print "Success!"
# do something here
else:
print "Wrong password!"
# do something else here
if __name__ == "__main__":
start()