r/inventwithpython • u/Brianwuz • Jul 12 '17
r/inventwithpython • u/How_2_Python • Jul 04 '15
Collatz Try and Except Clauses
I'm wondering if this is right. The try and except clause will run through smoothly if I type in a non-integer. But since I ran the program and typed in a non-integer the except clause will continue the code and run into an error with the while clause because a non-integer was typed in the first place. Is this the way the exercise was intended? Thanks for any help.
r/inventwithpython • u/erickxon • Jul 09 '15
Having trouble importing modules when running from Command Line
I'm at the end of chapter 6 where I'm making the password manager... When I run 'import pyperclip' with IDLE everything works fine, but when I try to access the .py file with the 'import pyperclip' line from the terminal I always get this message: "ImportError: No module named pyperclip" no idea why it works when using it with IDLE, but not with the command line, any solutions? edit: it's only with 3rd party modules.
r/inventwithpython • u/[deleted] • Aug 30 '16
Having the hardest time installing pygame
I've tried so many ways to install and not sure what I've done now. Running Mac OSX 10.6.8 Intel Core Duo Using Python3.5.1 Used homebrew. Downloaded the dmg file. Not sure anymore.
unk-426d047e:Desktop USER$ pip3 install pygame
Collecting pygame
Could not find a version that satisfies the requirement pygame (from versions: )
No matching distribution found for pygame
unk-426d047e:Desktop USER$ brew install python3
/usr/local/Library/brew.sh: line 126: /usr/bin/xcode-select: No such file or directory
Warning: You are using OS X 10.6.
We (and Apple) do not provide support for this old version.
You may encounter build failures or other breakages.
==> Installing dependencies for python3: pkg-config, sqlite, openssl
==> Installing python3 dependency: pkg-config
Error: Permission denied - /usr/local/opt/pkg-config
unk-426d047e:Desktop USER$ sudo chown -R "$USER":admin /usr/local
Password:
unk-426d047e:Desktop USER$ sudo chown -R "$USER":admin /Library/Caches/Homebrew
unk-426d047e:Desktop USER$ pip3 install pygame
Collecting pygame
Could not find a version that satisfies the requirement pygame (from versions: )
No matching distribution found for pygamer/inventwithpython • u/lazybum93 • Jul 13 '15
Chapter 9 - Practice Problem: Filling the Gaps
Is there a way to create a regex that can find a gap/gaps (i.e. example001, example002, example004, example005) and then subsequently renaming the filenumbers after the gap to make the filenumbers all consecutive.
What I've tried
I created a regex with a group for the numbers following the prefix (e.g. example, spam). I would then convert the group to an integer and check whether the following filename's numbering was n + 1. The issue is that for numbers such as '001', it will always convert to and integer of '1'. Is there a better way to check whether the numbers are in proper sequence without converting the string to an integer? Thansk!
Original Question: Filling in the Gaps:
Write a program that finds all files with a given prefix, such as spam001.txt, spam002.txt, and so on, in a single folder and locates any gaps in the numbering (such as if there is a spam001.txt and spam003.txt but no spam002.txt). Have the program rename all the later files to close this gap.
r/inventwithpython • u/Samkio_ • Oct 06 '14
Chapter 4. Line 143 - Strange code?
When creating the board structure there is some fancy code to reset the counter to be the top number of the grid.
counter -= BOARDWIDTH * (BOARDHEIGHT - 1) + BOARDWIDTH - 1Which to me looks confusing, couldn't you just use:
counter = x + 2Which appears random but to me makes more sense as you need to move the counter to be two larger than the current value in the width.
r/inventwithpython • u/How_2_Python • Jul 03 '15
Collatz Sequence. Need some help.
Ch. 3 of the book on the Collatz Sequence. The program is supposed to stop once the collatz function returns one. My program returns "1" but continues another past that, for example: 3, 16, 8, 4, 2, 1, 4 Could someone look over my code?
r/inventwithpython • u/jkibbe • Oct 08 '13
Caesar Hacker for lazy folks...
My students have been working on the various Caesar Cipher programs in the 'Hacking' book. Today one student decided they didn't want to show Key #0 when showing the results of the Caesar Hacker program, since he knew that was the same as the original ciphertext. We accomplished this easily by modifying the range. He wanted to take it to the next level by using a dictionary lookup so the program reports only the correct plaintext. We realize that one only needs to look at the 25 or 26 lines of output, but I wanted to use this as a teachable moment fi we could make it work. The problem is that we couldn't figure out how to do it!
We imported detectEnglish and added
if detectEnglish.isEnglish(translated): #and len(translated) == len(message) print('Key #%s: %s' % (key, translated))
but the program prints to screen as soon as it gets a word/partial result: Key #9: THIS
As you can see above (it is commented out and needs to be moved to the 'if' line), we added a line to also ensure that the length of the message and translated arethe same, but then nothing is returned.
Any hints or tips to push us in the right direction? Thanks!
Caesar Cipher Hacker
http://inventwithpython.com/hacking (BSD Licensed)
import detectEnglish
message = "cqrbfjbqjamnaknljdbncqnanfnanwxbyjlnbkncfnnwfxamb" LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' message = message.upper()
loop through every possible key
for key in range(1, len(LETTERS)):
# It is important to set translated to the blank string so that the
# previous iteration's value for translated is cleared.
translated = ''
# The rest of the program is the same as the original Caesar program:
# run the encryption/decryption code on each symbol in the message
for symbol in message:
if symbol in LETTERS:
num = LETTERS.find(symbol) # get the number of the symbol
num = num - key
# handle the wrap-around if num is 26 or larger or less than 0
if num < 0:
num = num + len(LETTERS)
# add number's symbol at the end of translated
translated = translated + LETTERS[num]
else:
# just add the symbol without encrypting/decrypting
translated = translated + symbol
# display translated when words are found in dictionary
if detectEnglish.isEnglish(translated):
#and len(translated) == len(message)
print('Key #%s: %s' % (key, translated))r/inventwithpython • u/bahnzo • Feb 10 '16
Automate the Boring Stuff - Chapter 7 Strong Password Protection.
I wanted to post my code and see if there was a better way I could've used regex w/o using a positive lookahead. That concept wasn't introduced in the chapter but every solution for this practice project uses it.
Also, love the book so far. For some reason I've never understood regex, but Ch. 7 just clicked for me.
import re
capReg = re.compile(r'.*[A-Z].*')
lowerReg = re.compile(r'.*[a-z].*')
digitReg = re.compile(r'.*\d.*')
def checkPassword(text):
if capReg.search(text) and lowerReg.search(text) and digitReg.search(text):
return True
else:
return False
pw = 'kenIsgreat99'
print(checkPassword(pw))Edit: Instructions from the book. Write a function that uses regular expressions to make sure the password string it is passed is strong. A strong password is defined as one that is at least eight characters long, contains both uppercase and lowercase characters, and has at least one digit. You may need to test the string against multiple regex patterns to validate its strength.
r/inventwithpython • u/stussll • Dec 06 '17
Small typo in Automate Boring Stuff Ch. 9
r/inventwithpython • u/shrugsnotdrugs • Aug 23 '16
[Automate] Problem with Selenium & Firefox
I'm going through Chapter 11 - Web Scraping, and I just began the section that introduces Selenium. The chapter instructs us to enter the following into the python interpreter:
>>> from selenium import webdriver
>>> browser = webdriver.Firefox()
>>> type(browser)
<class 'selenium.webdriver.firefox.webdriver.WebDriver'>
>>> browser.get('http://inventwithpython.com') Right after I enter "browser = webdriver.Firefox()" Firefox opens, but disables (Im not sure if this is the right word) my terminal. I am no longer prompted with the ">>>" in the interpreter, and therefore unable to continue with the "type(browser)" command.
After maybe 30 seconds - 1 minute, Firefox closes and I get this error:
selenium.common.exceptions.WebDriverException: Message:
Can't load the profile.Dir [file path]...If you specified a log_file
in the FirefoxBinary constructor, check it for details.Im using OSX, selenium version is 2.53.6, and python version is 3.5.2.
Thanks for the help.
r/inventwithpython • u/erickxon • Jul 06 '15
Appendix B: Running programs on Terminal on Mac
I keep getting the message: env: python3\r: No such file or directory whenever i try to run a script from the command line. i checked if /usr/bin/env exists and it does, so i'm not really sure what's wrong...
r/inventwithpython • u/[deleted] • Nov 02 '13
Taking text input and setting it as a variable...
I have the code below to take a text input but when I try and use 'players' in a string it is always giving me a None value. Is there a better way of doing this? Also I only want to allow an integer to be accepted as the input. I have tried Try/Exept but I think the first issue is the stumbling block.
def textbox(words, x, y):
txtbx = eztext.Input(maxlength=45, color=(255,0,0), prompt=words)
txtbx.set_pos(x,y)
while True:
txtbx.draw(screen)
events = pygame.event.get()
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN:
return
txtbx.update(events)
txtbx.draw(screen)
pygame.display.update()
return txtbx
players = textbox("How many players are there? ", 100,200)r/inventwithpython • u/Cardzilla • Jun 27 '15
Please help me with running python programs from the command line.
Hi guys,
Sorry if this is a silly question. I've followed Appendix B and added C:\Python34\MyPythonScripts to the path.
I added a shebang line to the first hello world program (hello.py). And made a batch file for it and placed it in the same folder. I tested them by running those and they worked fine.
Then I tried going to start and run and tried typing in hello and it returns "Windows can not find 'hello'. Make sure you typed the name correctly and try again"
When i try to run it from CMD, I get "'hello' is not recognized as an internal or external command, operable program or batch file."
When I type "python" in cmd it launches python. When I then type 'hello', it returns "Traceback (most recent call last): File "<stdin>" line 1 in <module> nameError: 'hello' is not defined "
I'm on chapter 11 and was trying to run the mapIt program.
Also I installed the latest python 3.4.3. which also has the add python to path.
Please help! I'm a newbie and aside from Al's books, have no computing expertise.
r/inventwithpython • u/[deleted] • Feb 10 '16
Automate The Boring Stuff - Chapter 6: Table Printer
It was quite challenging for me to do this one; I still feel quite lost with nested loops. Eventually I could do it as follows, but I think it's too much code.
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def printTable():
colWidths = [0] * len(tableData)
x = 0
y = 0
z = 0
for c in tableData:
for w in tableData[0]:
if len(w) > x:
x = len(w)
colWidths[0] = x
for w in tableData[1]:
if len(w) > y:
y = len(w)
colWidths[1] = y
for w in tableData[2]:
if len(w) > z:
z = len(w)
colWidths[2] = z
colWidths.sort()
maxWidth = colWidths[-1]
column = []
c = 0
for i in range(len(tableData[0])):
for j in range(len(tableData)):
column.append(tableData[j][i])
for i in tableData[0]:
for j in tableData:
print(column[c].rjust(maxWidth), end='')
c += 1
print()
printTable()It works, but I'm sure it should be much shorter. What am I not getting?
r/inventwithpython • u/broken_gains • Jul 11 '17
Shelve error in chapter 8
I got a shelve error when running the multi clipboard code that was explained in chapter 8. I'm not sure what is wrong with my code as I copied it from the exercise and looked it over for typos. I pasted both the code and the error I'm getting below. I'd really appreciate some guidance as I'm really left scratching my head here!
Error:
Eds-Macbook-Air:Multiclipboard eduardtepes$ Python3 mcb.pyw save greeting
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/shelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'greeting'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "mcb.pyw", line 15, in <module>
mcb_shelf[sys.argv[2]] == pyperclip.paste()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/shelve.py", line 113, in __getitem__
f = BytesIO(self.dict[key.encode(self.keyencoding)])
KeyError: b'greeting'Code:
#! python3
# mcb.pyw - Saves and loads pieces of text to the clipboard.
# Usage: Python3 mcb.pyw save <keyword> - Saves clipboard to keyword.
# Python3 mcb.pyw <keyword> - Loads keyword to clipboard.
# Python3 mcb.pyw list - Loads all keywords to clipboard.
import sys
import pyperclip
import shelve
mcb_shelf = shelve.open('mcb')
# Save clipboard content.
if len(sys.argv) == 3 and sys.argv[1].lower() == 'save':
mcb_shelf[sys.argv[2]] == pyperclip.paste()
elif len(sys.argv) == 2:
# List keywords and load content.
if sys.argv[1].lower() == 'list':
pyperclip.copy(str(list(mcb_shelf.keys())))
elif sys.argv[1] in mcb_shelf:
pyperclip.copy(mcb_shelf[sys.argv[1]])
mcb_shelf.close()Thanks,
Ed
r/inventwithpython • u/Cardzilla • Jul 02 '15
Chapter 13. Problems installing Docx
Hi Guys,
I'm working my way through chapter 13. I've installed PyPDF2, but can't install python-docx.
When I install it I get the error message as below.
building 'lxml.etree' extension
C:\Python34\lib\distutils\dist.py:260: UserWarning: Unknown
distribution option: 'bugtrack_url'
warnings.warn(msg)
error: Microsoft Visual C++ 10.0 is required (Unable to find
vcvarsall.bat).
----------------------------------------
Command "C:\Python34\python.exe -c "import setuptools,
tokenize;__file__='C:\\Users\\Ystan\\AppData\\Local\\Temp\\pip-
build-j393xz49\\lxml\\setup.py';exec(compile(getattr(tokenize,
'open', open)(__file__).read().replace('\r\n', '\n'), __file__,
'exec'))"
install --record C:\Users\Ystan\AppData\Local\Temp\pip-
wctjdi_k-record\install-record.txt --single-version-externally-
managed -- compile" failed with error code 1 in
C:\Users\Ystan\AppData\Local\Temp\pip-build-j393xz49\lxmlI'm a real newbie who's only previous experience was Al's 2 other python books and am having trouble trying to google an answer.
I did try installing microsoft network framework 4 and visual studio (but that took a ton of hard drive space!) and it didn't seem to help.
Please help!
Thanks
YS
r/inventwithpython • u/xX_Tea_Time_Xx • Jul 05 '15
Ch 6 Password Locker project
I don't understand how to run pw.py with the required arguments from the command line. Since this is the first time we do that in the book it would be helpful to have more clear instructions. There are several references to Appendix B but there the word "argument" is not even mentioned.
r/inventwithpython • u/xyz135711 • Dec 07 '17
[automate] inaccurate range in project Multithreaded XKCD Downloader
Line 72 of the code for project Multithreaded XKCD Downloader in Chapter 15 reads
downloadThread = threading.Thread(target=downloadXkcd, args=(i, i + 99))I believe that 99 has to be 100. Otherwise, every 100th picture is skipped in the function downloadXkcd in the same code.
There seem to be a few more small issues with the example code given in the book / web site for this project that prevent the project code running successfully at this time as is. That is probably because the adresses or the HTML code at the XKCD web site have changed slightly since this book has been published. So I am not sure if these are worth mentioning here as these issues may present themselves differently a year from now. Pls let me know if anyone is interested in.
r/inventwithpython • u/Sesori • Feb 15 '16
Automate Boring Stuff With Python. How good is it for beginners ?
Let me clarify my question a little more...
I was originally learning Python LPTHW, the author was strongly against using Python 3. However, after doing more research, it appears that the community agrees that LPTHW is outdated, and it is better for beginners to start learning Python 3 (or... the future).
I came upon this book, Automate Boring Stuff With Python. Thought that it might help me learn the ropes. The book came with one disclaimer in the introduction, "The coding style sometimes goes against best practices ... Sophisticated programming concepts—like object-oriented programming, list comprehensions, and generators—aren’t covered... this book is mostly concerned with getting programs to work with the least amount of effort."
I'm afraid that not learning best practices from the start would be bad for me down the road.
Thanks in advance for your advice.
r/inventwithpython • u/How_2_Python • Jul 07 '15
Comma Code, Ch.4 Not sure if I'm doing this right
This is a practice problem from Ch. 4 of the Automate book. I've attached my code here. I'm not sure how I can insert ', and' before the last word in any entered list value. I'm also not sure of the exact mechanics by which we approach how the list value is entered. For example, is it supposed to just be entered specifically as a sequence of words with commas between each word? I'd appreciate any help.
Comma Code
print('Please enter Newlist value') Newlist = [input()] Newlist.insert(-2, ', and ') print(Newlist)
r/inventwithpython • u/eggiewaffles92 • Oct 25 '16
[Automate] Chapter 16 Project - Auto Unsubscriber
I'm having a hard time with this project and was looking for any help. The prompt is: "Write a program that scans through your email account, finds all the unsubscribe links in all your emails, and automatically opens them in a browser. This program will have to log in to your email provider’s IMAP server and download all of your emails. You can use BeautifulSoup (covered in Chapter 11) to check for any instance where the word unsubscribe occurs within an HTML link tag."
My idea was to login into my imap server and get the html message content from one message and pass that to a beautiful soup object. I then can parse through and find the unsubscribe links/elements. However, there appears to be an issue finding the elements I need or any elements I look for. It only picked up <div>.
So here is my code:
imapObj = imapclient.IMAPClient('imap.gmail.com', ssl=False)
imapObj.login('<email>', '<password>')
imapObj.select_folder('INBOX', readonly=True)
UIDs = imapObj.search(['ALL'])
rawMessages = imapObj.fetch([<UID>]), [b'BODY[]'])
message = pyzmail.PyzMessage.factory(rawMessages[<UID>][b'BODY[]'])
htmlObj = message.html_part.get_payload().decode(message.html_part.charset)
soup = bs4.BeautifulSoup(htmlObj)
EDIT: If anyone's curious, I was able to figure out using BeautifulSoup and passing emails downloaded with pyzmail. I then selected the element with soup.select and used example_list[x].get('href') to get the URL.
r/inventwithpython • u/playinmyblues • Sep 22 '15
Chapter 17 Animation not Working
By the way, I run the author's code from the file he provides and it works the way it is supposed to work.
At first I typed in the animation.py program with an underscore in the constants where there were two words. My code looks almost identical except for a header with some comments about what the program is and what it does.
I run the program and the red and blue rectangles move and the green square stays still. Once the red and blue rectangles hit the right side, they stop.
I checked my code with the diff tool on the website but it shows no real differences. I took out the underscores, run it, same results as before. I remove all differences, run with the same results. The diff tool shows absolutely no differences between the programs. I even took out the header.
import pygame, sys, time
from pygame.locals import *
# setup pygame
pygame.init()
# setup the window
WINDOWWIDTH = 400
WINDOWHEIGHT = 400
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Animation')
# set up direction variables
DOWNLEFT = 1
DOWNRIGHT = 3
UPLEFT = 7
UPRIGHT = 9
MOVESPEED = 4
# set up the colours
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# set up the block data structure
b1 = {'rect':pygame.Rect(300, 80, 50, 100), 'color':RED, 'dir':UPRIGHT}
b2 = {'rect':pygame.Rect(200, 200, 20, 20), 'color':GREEN, 'dir':UPLEFT}
b3 = {'rect':pygame.Rect(100, 150, 60, 60), 'color':BLUE, 'dir':DOWNLEFT}
blocks = [b1, b2, b3]
# run the game loop
while True:
# check for the QUIT event
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# draw the black background onto the surface
windowSurface.fill(BLACK)
for b in blocks:
# move the block data structure
if b['dir'] == DOWNLEFT:
b['rect'].left -= MOVESPEED
b['rect'].top += MOVESPEED
if b['dir'] == DOWNRIGHT:
b['rect'].left += MOVESPEED
b['rect'].top += MOVESPEED
if b['rect'] == UPLEFT:
b['rect'].left -= MOVESPEED
b['rect'].top -= MOVESPEED
if b['dir'] == UPRIGHT:
b['rect'].left += MOVESPEED
b['rect'].top -= MOVESPEED
# check if the block has moved out of the window
if b['rect'].top < 0:
# block has moved past the top
if b['dir'] == UPLEFT:
b['dir'] = DOWNLEFT
if b['dir'] == UPRIGHT:
b['dir'] = DOWNRIGHT
if b['rect'].bottom > WINDOWHEIGHT:
# block has moved past the bottom
if b['dir'] == DOWNLEFT:
b['dir'] = UPLEFT
if b['dir'] == DOWNRIGHT:
b['dir'] = UPRIGHT
if b['rect'].left < 0:
# block has moved past the left side
if b['dir'] == DOWNLEFT:
b['dir'] = DOWNRIGHT
if b['dir'] == UPLEFT:
b['dir'] = UPRIGHT
if b['rect'].right > WINDOWWIDTH:
# block has moved past the right side
if b['dir'] == DOWNRIGHT:
b['dir'] = DOWNLEFT
if b['dir'] == UPRIGHT:
b['dir'] = UPLEFT
# draw the block onto the surface
pygame.draw.rect(windowSurface, b['color'], b['rect'])
# draw the window onto the screen
pygame.display.update()
time.sleep(0.02)Any ideas?
r/inventwithpython • u/libertydvp • Feb 15 '14
New to Python problems
I installed Python 3.3 on my macbook pro (10.6.8) last week and was following the tutorials in the INVENT WITH PYTHON book. All was going well until I used IDLE to run the hello.py script. When I OPEN the file using IDLE mfile -open it appears for a second and then I get the IDLE QUIT UNEXPECTEDLY window. I installed 3.3 on another macbook and I get the same exact problem. I thought I'd give it another try today. I reinstalled python several times and now in addition to the original problem I have found I can't open a new file in IDLE. As soon as I do, I get a white window without text and the IDLE freezes. I have to force quit to close it. Any advice would be appreciated.
r/inventwithpython • u/Lickin_Windows • Jan 20 '15
Problems in Chapter 7 - The Debugger.
When I do what I'm told and use the debugger to step through the Dragon Realm program, I get to the point when I step into the functions I've created (correctly, it is identical to the sourcecode in the book and it executes flawlessly) the debugger does its job on the first line but on the second line, which is identical to the first one just with a different string, it suddenly decides to open Pyshell.py and debug that instead.
I tried using the step out button on the debugger and that brough it back to the correct place only to return to Pyshell.py on the next step.
I tried to skip to the next program that I'm supposed to write. One that has a bug in it for debugging purposes and the debugger didn't even reach the bug. When it checked the randint function call it opened up random.py to check out randint. After stepping out of that it again decided to go to Pyshell.py and not wanting to stay where I wanted it to be. I don't know what the hell it's doing...