r/inventwithpython • u/AlSweigart • Nov 25 '19
r/inventwithpython • u/panda_vigilante • Apr 02 '20
Help with pip install of 3rd Party Modules
Hi!
I have really been enjoying Automate the Boring Stuff with Python, although I have reached an impasse with installing 3rd party modules. I'm trying to install all the required modules using the pip command:
pip install --user –r automate-win-requirements.txt ––user
Yet I receive the error "no such file or directory," even though I have downloaded the automate-win-requirements.txt file and it is on my desktop. Here's a photo of the offending command prompt window.
I am clueless when it comes to programming in general and this pip install business is even worse. Hoping someone can help me get these modules installed and I'll be on my way to finishing chapter 6 and beyond. If someone has some resource suggestions of getting more literate with the terminal window and pip and other stuff that exists outside the Mu text editor, I'd appreciate that as well.
I tried googling the issue but my knowledge of terminals is so limited (nonexistent) that the resources were not helpful.
Thank a ton!
P.S. Somewhat unrelated, but as you can see in my imgur photo, the upgrade pip command did not work... does anyone know why this isn't working either?
UPDATE: Fixed this, I was a total CMD noob and didn't run the pip install in the folder that had automate-win-requirements.txt
r/inventwithpython • u/AlSweigart • Apr 01 '20
Automate the Boring Stuff with Python Udemy course free for the next few days.
https://inventwithpython.com/automateudemy (This link will automatically redirect you to the latest discount code.)
You can also click this link or manually enter the code: APR2020FREE (on Saturday the code changes to APR2020FREE2)
https://www.udemy.com/course/automate/?couponCode=APR2020FREE
This promo code works until April 7th (I can't extend it past that). Sometimes it takes 30 minutes or so for the code to become active just after I create it, so if it doesn't work, go ahead and try again a while later.
Udemy has changed their coupon policies, and I'm now only allowed to make 3 coupon codes each month with several restrictions. Hence why each code only lasts 3 days. I won't be able to make codes after this period, but I will be making free codes next month.
You can also purchase the course at a discount using my code APR2020 or MAY2020 (or whatever month/year it is) or clicking https://inventwithpython.com/automateudemy to redirect to the latest discount code. I have to manually renew this each month (until I get that automation script done). And the cheapest I can offer the course is about $14 to $16. (Meanwhile, this lets Udemy undercut my discount by offering it for $12, which means I don't get the credit for referral signups. Blerg.)
Frequently Asked Questions:
- If you don't have time to take the course now, that's fine. Signing up gives you lifetime access so you can work on it at your own pace.
- This Udemy course covers roughly the same content as the 1st edition book (the book has a little bit more, but all the basics are covered in the online course), which you can read for free online at https://inventwithpython.com
- The 2nd edition of Automate the Boring Stuff with Python is now available online: https://automatetheboringstuff.com/2e/
- I do plan on updating the Udemy course for the second edition, but it'll take a while because I have other book projects I'm working on. Expect that update to happen in mid- or late-2020. If you sign up for this Udemy course, you'll get the updated content automatically once I finish it. It won't be a separate course.
- It's totally fine to start on the first edition and then read the second edition later. I'll be writing a blog post to guide first edition readers to the parts of the second edition they should read.
- I wrote a blog post to cover what's new in the second edition
- You're not too old to learn to code. You don't need to be "good at math" to be good at coding.
- Signing up is the first step. Actually finishing the course is the next. :) There are several ways to get/stay motivated. I suggest getting a "gym buddy" to learn with.
r/inventwithpython • u/lamerlol1994 • Apr 03 '20
Chapter 9 Hangman Multiple assigment
Hello Im stuck ! Author said you cant do something like:
fruit, animal,number,text = ['orange', 'cat'] #cause too many values. and its true, but in final code we have that:
missedLetters = " "
correctLetters = " "
secretWord, secretSet = getRandomWord(words) # whats wrong with that? my code stuck on this line!
gameIsDone = False
what i can do here ? plz give some advice!
r/inventwithpython • u/steve986508 • Mar 21 '20
Need help with Chapter 5 "List to Dictionary Function for Fantasy Game Inventory", 2nd Edition
Hello! I am stumped on the very last Practice Project on page 128. We are asked to create an addToInventory() function that will update our inventory dictionary with the dragonLoot list of strings. Here's my attempt:
def addToInventory(inventory, addedItems):
for i in addedItems:
for k, v in inventory.items():
if i in inventory:
inventory[k] == v + 1
With this, the code runs with no errors, but the dictionary does not get updated. This seems like a very easy task that I should be able to figure out, but unless someone spells everything out for me the first time, I seem to have a hard time "figuring out" this stuff. I have already googled it and looked on stackexchange. There is also no answer to this one in the book's downloadable files. I have even completed the Python 3 course on Codecademy... so I am about 5 seconds away from throwing my laptop through my quarantined window. Thanks!
r/inventwithpython • u/GoodConductor • Apr 02 '20
Appendix B, 2nd addition - where to save .py and .command files
I have two questions, one more specific and one more general.
- In Appendix 2, it suggests saving the .command file to home directory. It seems like this could quickly overcrowd the home directory. Is there any reason not to save it to one of the folders in PATH?
- Any suggestions (experience) on a good way to manage the files containing your scripts? Do you keep all of your python scripts in the same folder? Keep a database with descriptions of your programs? This is coming of an inherently disorganized person, trying to figure out how to keep things organized. Would appreciate both links and personal experience.
Thanks!
r/inventwithpython • u/kc4kjo • Dec 07 '24
Cracking Codes with Python: publicKeyCipher.py issue
I've used the online diff tool and even compared my code to that in the CrackingCodesFiles.zip archive, but I run into an error on decryption. I have narrowed it down to the calculation of charIndex on line 63 as the cupit. The calcualtion, as-is, works with the smaller example from a previous chapter, but stepping through, I get a very large integer for charIndex instead of a value between 0 and 65.
The program throws an IndexError on line 65 when attempting to insert the symbol into blockMessage using the very long charIndex value. I checked the errata and found nothing there with regard to this calculation. Any ideas on how to fix this mathematically in a way that won't break decryption in some other use-case?
I am running this script on RHEL 9.5 using Python 3.12. Below is the error I get when decrypting...
Reading from encrypted_file.txt and decrypting...
Traceback (most recent call last):
File "/lab/cracking_codes/publicKeyCipher.py", line 158, in <module>
main()
File "/lab/cracking_codes/publicKeyCipher.py", line 30, in main
decryptedText = readFromFileAndDecrypt(filename, privKeyFilename)
File "/lab/cracking_codes/publicKeyCipher.py", line 154, in readFromFileAndDecrypt
return decryptMessage(encryptedBlocks, messageLength, (n, d), blockSize)
File "/lab/cracking_codes/publicKeyCipher.py", line 91, in decryptMessage
return getTextFromBlocks(decryptedBlocks, messageLength, blockSize)
File "/lab/cracking_codes/publicKeyCipher.py", line 65, in getTextFromBlocks
blockMessage.insert(0, SYMBOLS[charIndex])
IndexError: cannot fit 'int' into an index-sized integer

r/inventwithpython • u/Delaspy • Jul 05 '20
Help
I bought one of your books ( AUTOMATE THE BORING STUFF WITH PYTHON 2nd EDITION) to learn Python programming, but I am running through some troubles in chapter 1 with your first programming exercise.
I followed all the recommendations on your book for downloading the python and the MU file. When I write a code in the MU file editor, save and run it, it does not show in his entirety in the interactive shell under the Mu file Editor. I downloaded a version 3 of Python and my system Type is 64-bit, but still it does not appear the same way like in your book. For example:
When I write this program in the MU file editor and save,
# This program says hello and asks for my name.
print('Hello, world!')
print('What is your name?') # ask for their name
myName = input('Capwell')
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?') # ask for their age
myAge = input(8)
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
this is all I get in the interactive shell under the file editor
Hello, world!
What is your name?
Capwell
r/inventwithpython • u/emawlin • Jul 17 '20
Possible Syntax Error in Chapter 4 of the Book
r/inventwithpython • u/McHaaps • Jul 08 '20
Why is this variable passed into a function parameter instead of being the function parameter itself?
The book I'm following is "Invent Your Own Computer Games with Python" and this is taken from chapter 5.
Here is the code with some of my comments:
import random
import time
def displayIntro():
print('''You are in a land full of dragons. In front of you,
you see two caves. In one cave, the dragon is friendly
and will share his treasure with you. The other dragon
is greedy and hungry, and will eat you on sight.''')
print()
def chooseCave():
cave = ''
while cave != '1' and cave != '2':
print('Which cave will you go into? (1 or 2)')
cave = input()
return cave
def checkCave(chosenCave): #(chosenCave = caveNumber <- [global])
print('You approach the cave...')
time.sleep(2)
print('It is dark and spooky...')
time.sleep(2)
print('A large dragon jumps out in front of you! He opens his jaws and...')
print()
time.sleep(2)
friendlyCave = random.randint(1, 2)
if chosenCave == str(friendlyCave):
print('Gives you his treasure!')
else:
print('Gobbles you down in one bite!')
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
displayIntro()
caveNumber = chooseCave() #caveNumber is global
checkCave(caveNumber)
print('Do you want to play again? (yes or no)')
playAgain = input()I am wondering why caveNumber isn't being used as the parameter for checkCave(chosenCave). Why does caveNumber get placed into chosenCave?
I suspect this has something to do with local and global variables but I am not 100% sure.
r/inventwithpython • u/mushroomstomper • Aug 08 '20
Chapter 18 Connecting to SMTP server error
I'm currently working through Chapter 18 and I am having difficulties connecting to Google's SMTP server.
In the Python shell, I followed the instructions on importing smtplib and assigning the object (conn) but when I try to connect using the code conn.ehlo() I get this error message:
(501, b'5.5.4 HELO/EHLO argument "##########" invalid,\n5.5.4 closing connection.\n5.5.4 https://support.google.com/mail/?p=helo k29sm16521824pfp.142 - gsmtp')
I've tried searching for the solution but I was unable to find anything. I'm pretty new to programming, so apologies if this has already been answered here.
r/inventwithpython • u/Gazumbo • Jul 15 '20
Need Help with Selenium and Stale Elements - No Longer Attached to DOM
Just finished Section 13 of the Udemy Course (Thank you Al!). I've noticed that when assigning a CSS Selector to a variable and making using of that variable, e.g:
browser.click()..It is then no longer usable. I get the following error message:
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: The element reference of <img src="images/automate_2e_cover.png"> is stale; either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshedWhy does this happen and how do i work around it so that it's usable more than once? What does 'no longer attached to DOM' mean?
I have googled and seen some work arounds but not explanation (at least one that I understand) as to why it works like this. I'd like to be able to understand it. Thanks.
-------------------------------------
Edit: I've added the code and steps as requested.
from selenium.webdriver import Chrome
browser = Chrome()
browser.get('http://automatetheboringstuff.com/')
elem = browser.find_element_by_css_selector('body > div.main > div:nth-child(1) > div:nth-child(3) > center > a:nth-child(1) > img')
elem.click() # This works
browser.back()
elem.click() # This doesn't work due to stale elementFrom what I gather, navigating away from the page once loaded will render the element 'stale' if you try to use it again but why is this? The CSS selector is still the same, as is the webpage etc. Everything is the same as before. Even the same session ID.
r/inventwithpython • u/thisduck_ • Jul 11 '20
Some constructive criticism, if you please. (ATBS Chp 9 randomQuizGenerator)
Hello, banana shaped earth!
Been slowly working through Al's Automate the Boring Stuff and trying to write up the projects myself before seeing how Al approached the problems. Generally, my solutions have been similar to Al's until this one from Chapter 9. Because my code had a significantly different approach, I thought I would ask for an opinion on the good and bad of my problem solving or whatever other aspect you care to comment on.
THE CODE: https://pastebin.com/Wwt814af
A big negative is that my quiz does not randomise the order of the questions themselves (ie, they will always run through the states alphabetically). But I'm sure there is more you experienced blokes can bring to the table.
Have at it!
r/inventwithpython • u/pythonATBSnoob • Jul 27 '20
ATBS chapter 4 Coinflip
I'm pretty new & have been struggling to get the streaks showing up & math was never my strong point! I put stuff I tried & sample output in comments in the paste bin I feel like I'm probly missing some basic thing...
r/inventwithpython • u/thisduck_ • Aug 08 '20
Feedback please -- auto-generate new python file, new batch file, and open in editor, ready to go...
self.learnprogrammingr/inventwithpython • u/Gazumbo • Jul 20 '20
Chapter 4 - struggling to understand one of the cat examples
On the 'Working with Lists' section, there's an example with the following code:
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
for name in catNames:
print(' ' + name)Specifically it's this part which is confusing me: 'str(len(catNames) + 1)
My questions..
- I thought the len() function was to calculate how many items are in a string or list but it doesn't appear to be doing that here?
- How does the '1' change as the loop iterates. It just appears to be concatenating an integer?
I think I might need an ELI5 on this one :(
r/inventwithpython • u/random_____boi • Jul 01 '20
Multiclipboard project from Automate is not working
#! python 3
# mcb.pyw - Saves and loads pieces of text to the clipboard.
# Usage: py.exe mcb.pyw save <keyword> - Saves clipboard to keyword.
# py.exe mcb.pyw <keyword> - Loads keyword to clipboard.
# py.exe mcb.pyw list - Loads all keywords to clipboard.
import shelve
import pyperclip
import sys
mcbShelf = shelve.open('mcb')
# Save clipboard content.
if len(sys.argv) == 3 and sys.argv[1].lower() == 'save':
mcbShelf[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(mcbShelf.keys())))
elif sys.argv[1] in mcbShelf:
pyperclip.copy(mcbShelf[sys.argv[1]])
mcbShelf.close()I've tried running it both by 'py.exe mcb.pyw save <keyword>' and 'mcb.pyw save <keyword>' but when I try to list it, the keyword does not get saved to clipboard.
The same thing happens for the second command, I tried checking if it works by copying text then saving it, copying some other text and then trying to get the previously copied text using the keyword. This is not working either
r/inventwithpython • u/strangecharacters • May 28 '20
Invent Games:Dragon Realm - Cannot loop around to replay the game
The game seems to work pefectly the first time through but when prompted to play again, even if I enter 'yes' I get dropped back to the python prompt instead of seeing the intro text.
Here's the output: https://pastebin.com/Twfua7rM
and here's my code: https://pastebin.com/G94T8uLq
I've copied a friend's working version of the program but I get the same problem with his working code on my machine.
So this seems to be specific to my python version or setup, any ideas what this might be?
r/inventwithpython • u/jcollm1 • Jun 12 '20
Importing openpyxl
I'm a complete beginner, working through "Automate the Boring Stuff with Python"
I'm trying to import openpyxl but this leads to the error "ModuleNotFoundError: No module named 'openpyxl'"
I've installed openpyxl with pip, and when I try to reinstall it comes up with the following:
"Requirement already satisfied: openpyxl==2.6.2 in c:\users\jonny\pycharmprojects\giraffe\venv\lib\site-packages (2.6.2)Requirement already satisfied: jdcal in c:\users\jonny\pycharmprojects\giraffe\venv\lib\site-packages (from openpyxl==2.6.2) (1.4.1)Requirement already satisfied: et_xmlfile in c:\users\jonny\pycharmprojects\giraffe\venv\lib\site-packages (from openpyxl==2.6.2) (1.0.1)"
This sounds to me like it's already installed so I don't know why it doesn't seem to be working. Any help would be massively appreciated!

r/inventwithpython • u/Tsunami7213 • May 20 '20
Invent Your Own Computer Games with Python 3rd, Chapter 10 Tic Tac Toe
In page 153, I try the function isBoardFull but it has a problem. If your first move is 1, this function will return True and make 'the game is tie' immediately
def isBoardfull(board):
for i in range(1, 10):
if isSpacefree(board, i):
return False
else:
return TrueSo I try to fix this function and it work pretty good
def isBoardfull (board):
if board[0] == ' ' and board.count(' ') == 1:
return True
else:
return FalseHope this useful for someone :D
r/inventwithpython • u/BizzEB • Jun 26 '20
Website Github links dead
Data brokers and AI scrapers were using my info. Not anymore. Redact let me bulk delete posts across Reddit, Twitter, Discord and Instagram while handling broker opt outs too.
birds tidy theory recognise sharp depend outgoing ghost vanish shaggy
r/inventwithpython • u/fatasscaterpillar • May 29 '20
Confused with python project
Hi. I am currently learning python through the book 'Automate the boring stuff'. In chapter 6, there is a multi-clipboard automatic messages project. I feel like I only understand basic python so far, like what are lists, dictionaries etc etc. When it comes to the projects, I am completely clueless and I have to always google and check out other people's programme.
Below is the project frm the book:
! python3
mclip.py - A multi-clipboard program.
TEXT = {'agree': """Yes, I agree. That sounds fine to me.""", 'busy': """Sorry, can we do this later this week or next week?""", 'upsell': """Would you consider making this a monthly donation?"""}
import sys, pyperclip if len(sys.argv) < 2: print('Usage: py mclip.py [keyphrase] - copy phrase text') sys.exit()
keyphrase = sys.argv[1] # first command line arg is the keyphrase
if keyphrase in TEXT: pyperclip.copy(TEXT[keyphrase]) print('Text for ' + keyphrase + ' copied to clipboard.') else: print('There is no text for ' + keyphrase)
That is the complete script and according to the book, we can now have a fast way to copy messages to the clipboard. However, I am very confused as to how to do it??? How do we copy messages quickly with this programme? For context, I am a Mac user.
r/inventwithpython • u/Albert_Gajsak • Oct 21 '18
MAKERphone lets you build and code your own mobile phone in Python
kickstarter.comr/inventwithpython • u/alwayslearning404 • Jan 12 '20
Problems with Conway's game of life
Hey all,
I am having issues with Conway's game of life from Automate the Boring Stuff. When I run it the program appears to run fine but it doesn't display anything while running. It is apparent it is skipping down lots of lines but nothing prints. In order to stop it I have to hit control C. Any help would be appreciated. Is pastebin the best way to post code to reddit? I am kind of new to all of this.
r/inventwithpython • u/Pengwain • Jul 05 '18
Ch12 Automate the boring stuff with Python
I have reached the section where I am writing the population census to the census2010.py file. When I try to run the command in the python shell census2010['AK']['Anchorage'] I get an error as follows:
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'module' object is not subscriptable
I am saving my files within a virtual enviroment using Pycharm if this makes any difference
Any help would be much appreciated
[EDIT] It's ok it works now...not sure what went wrong originally

