r/inventwithpython • u/jnbutlerDrummer • Oct 18 '19
Link to download beeps.wav broken
The link in Making Games with Python & Pygame to download the beeps.wav is broken. Where do I get the downloads for this book?
Thank you.
r/inventwithpython • u/jnbutlerDrummer • Oct 18 '19
The link in Making Games with Python & Pygame to download the beeps.wav is broken. Where do I get the downloads for this book?
Thank you.
r/inventwithpython • u/somebody_11223344 • Dec 24 '19
r/inventwithpython • u/Kok_Nikol • Oct 20 '19
I saw accidentally that the second edition is almost out, and there are quite a few changes.
Was wondering is the first edition still relevant, as in should I wait for the second edition to come out?
EDIT: Another question (paging /u/AlSweigart):
If I go over the first edition, will I be able just cover the differences in the second edition? Is there like a diff.
Or should I just wait for the second edition?
r/inventwithpython • u/pygreen • Nov 29 '14
Very new to python here and using your books as entry point. I was trying to run Squirrel Eat Squirrel but the following warning is keeping it from running:
Warning (from warnings module): File "C:\Python34\squirrel\squirrel.py", line 71 BASICFONT = pygame.font.Font('freesansbold.ttf', 32) RuntimeWarning: use font: DLL load failed: The specified module could not be found. (ImportError: DLL load failed: The specified module could not be found.) Traceback (most recent call last): File "C:\Python34\squirrel\squirrel.py", line 396, in <module> main() File "C:\Python34\squirrel\squirrel.py", line 71, in main BASICFONT = pygame.font.Font('freesansbold.ttf', 32) File "C:\Python34\lib\site-packages\pygame_init_.py", line 102, in getattr raise NotImplementedError(MissingPygameModule) NotImplementedError: font module not available (ImportError: DLL load failed: The specified module could not be found.)
Similar warnings are preventing other programs like memorypuzzle.py, slidepuzzle.py, wormy.py and others from running as well. What's the fix for this?
Currently running Python 3.4.2 and Pygame 1.9.2a0 win32
r/inventwithpython • u/[deleted] • Dec 18 '13
Trying to figure out where I have a problem, and no access to internet on the computer I am coding on (Personal laptop at work). I have the program completed and it runs, but it fails to hack the example. Any direction on where to check for errors?
r/inventwithpython • u/Nick_Aaron • Dec 31 '17
I found it's hard to find mistakes in my program, so I install pylint to find errors. But it show me this:
E: 5, 0: Module 'pygame' has no 'init' member (no-member)
E: 13,25: Module 'pygame' has no 'QUIT' member (no-member)
E: 14,12: Module 'pygame' has no 'quit' member (no-member)
These are not errors at all!Please give some suggestions, any help will be appreciated!
r/inventwithpython • u/[deleted] • Mar 12 '16
I am on Ch.14 doing the JSON project using requests to get the JSON data but I am getting a error 401 on the raise_for_status()
I looked at the website and it seems you need to register for a key now? Is this a recent change? I tried multiple strings/cities, same 401 response every time
File "C:\Python 3.5\lib\site-packages\requests\models.py", line 840, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: http://api.openweathermap.org/data/2.5/forecast/daily?q=Eureka&cnt=3
r/inventwithpython • u/[deleted] • Nov 13 '14
I'm currently reading through the book and really enjoying it. It has given me some ideas that have been really helpful in refining my first few projects.
My question: in the Sonar Treasure Hunt game in Ch. 13, the getRandomChests method creates a list of treasure chest coordinates by randomly choosing x and y coordinates within the range of the game board. Is it not possible for the game to put two or more chests in the same place? Wouldn't this mess up the game?
Would it be easy to write some sort of check to see if the current random choice is already in the list, and if so, not add it? And the loop could be something like while len(chests) < 3. Or am I missing some built-in mechanism that will keep this from happening? This isn't a criticism, I'm just a beginner trying to learn. Answers greatly appreciated.
r/inventwithpython • u/FuzzyDunnloppp • Mar 04 '17
Ok so I bought the Automate the Boring Stuff with Python book and I am reading it and on Page 77 it asks you to write a program: This is right from the site, found here: https://automatetheboringstuff.com/chapter3/
"Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1.
Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1. (Amazingly enough, this sequence actually works for any integer—sooner or later, using this sequence, you’ll arrive at 1! Even mathematicians aren’t sure why. Your program is exploring what’s called the Collatz sequence, sometimes called “the simplest impossible math problem.”)
Remember to convert the return value from input() to an integer with the int() function; otherwise, it will be a string value.
Hint: An integer number is even if number % 2 == 0, and it’s odd if number % 2 == 1.
The output of this program could look something like this:
Enter number: 3 10 5 16 8 4 2 1"
I am obviously doing several things wrong - the problem is that I don't know what to ask because I keep confusing myself. Here's my code that, when I run it, runs the "RESTART:" error: http://pastebin.com/FvzZcbjV
This is my first programming language experience so go easy on me.
r/inventwithpython • u/The_Ironic_Badger • Aug 25 '15
Pressing step on line 5 opens up pyshell.py and when I click out, all the buttons on the debug get grayed out. This wasn't mentioned in the tutorial once. I literally copied the example code word for word, and I'm using python 3.4.3. Can someone please explain what's happening?
r/inventwithpython • u/[deleted] • Aug 11 '15
total=0
for num in range(101):
total=total+num
print(total)I'm having a hard time wrapping my head around the equation part. I 'get it' on a surface level, glancing at it, makes sense, but if I had to point out each step involved at arriving to 5050 using this one equation I can't visualize how it works.
There are 3 keywords 'total'. The very first one at the top is just a starting point for the equation. It also happens to be a global variable? which is why it is okay to have the same word 'total' on both sides of the equation because the left-side total is a local one (inside the for function) and the right-side 'total' is different because it is the global one, defined earlier at the top, am I right?
I just don't understand how this is enough for python to know to sum all those iterations together into one number, especially with so many totals. I tried substituting the lest-side 'total' with 'theSum' as a variable name, and printing that variable, but it only gives me 100 instead of 5050:
total=0
for num in range(101):
theSum=total+num
print(theSum)Why isn't it iterated a 100 times and added up like in the previous example? I just can't see the first several steps the program is doing and differentiating between different total variables and remembering to which to add again and which total reuse in the next iteration.
r/inventwithpython • u/ZKMetz1 • Sep 30 '16
After banging my head on the wall, I gave in and found this code written by another user:
def printTable(inputList):
colWidths = [0] * len(inputList)
for i in range(len(inputList)):
for j in range(len(inputList[i])):
if len(inputList[i][j]) > colWidths[i]:
colWidths[i] = len(inputList[i][j])
for x in range(len(inputList[0])):
for y in range(len(inputList)):
print(inputList[y][x].rjust(colWidths[y]), end = ' ')
print('')What I still don't understand is the "rjust(colWidths[y]", I know when the loops iterate it will print the [y][x] variable, but what I dont understand is how it doesnt right justify each and every time it prints. I feel like it should be adding 5-8 spaces to the left of each word and spacing them WAY out each time it prints. Maybe I'm missing something simple?
Also sorry for the formatting - I have no damn clue how to make it pretty
r/inventwithpython • u/Dysupes • Mar 21 '16
I'm working my way through the book and really liking it so far but I have a question about part of the Hangman code. You create a variable titled words and in it you put the words for the game. Then in the next block, you define the function 'getRandomWord' with the argument of 'wordList'. How does Python know that the words you want it to pick from are in the 'words' variable since you never call it or reference it again?
Here is a copy of the code:
words = '''mylittlepony fluttershy twilightsparkle pinkiepie
rainbowdash applejack celestia luna rarity cadence'''.split()
def getRandomWord(wordList):
wordIndex = random.randint(0, len(wordList) - 1)
return wordList[wordIndex]For the record, the program did work just fine but I'm just trying to understand how it knows those are the words it should be choosing from.
r/inventwithpython • u/Rhea_Starstorm • Aug 11 '17
I'm getting an error: The computer will go first.
Traceback (most recent call last):
File "tictactoe.py", line 156, in <module>
makeMove(theBoard, computerLetter, move)
File "tictactoe.py", line 34, in makeMove
board[move] = letter
TypeError: list indices must be integers or slices, not NoneTypeWhen the computer's first move happens. I've check my code against the book and can't find the error.
Here is my code for ref:
import random
def drawBoard(board):
# This function prints out the board that it was passed.
# 'board' is a list of 10 strings representing the board (ignore index 0)
print(board[7] + '|' + board[8] + '|' + board[9])
print('-+-+-')
print(board[4] + '|' + board[5] + '|' + board[6])
print('-+-+-')
print(board[1] + '|' + board[2] + '|' + board[3])
def inputPlayerLetter():
# Lets the player type which letter they want to be.
# Returns a list with the player's letter as the first item and they computer's letter as the second.
letter = ''
while not(letter == 'X' or letter == 'O'):
print('Do you want to be X or O')
letter = input().upper()
# The first element in the list is the player's and the second is the computer's letter.
if letter == 'X':
return ['X', 'O']
if letter == 'O':
return ['O', 'X']
def whoGoesFirst():
# Randomly choose which player goes first.
if random.randint(0, 1) == 0:
return 'computer'
else:
return 'player'
def makeMove(board, letter, move):
board[move] = letter
def isWinner(bo, le):
# Give a board and the player's letters, this function returns True if that player has won/
# We use "bo" instead of board and "le" instead of letter so we don't have to type as much.
return ((bo[7] == le and bo[8] == le and bo[9] == le) or # Across the top
(bo[4] == le and bo[5] == le and bo[6] == le) or # Across the bottom
(bo[7] == le and bo[4] == le and bo[1] == le) or # Down the left side
(bo[8] == le and bo[5] == le and bo[2] == le) or # Down the middle
(bo[9] == le and bo[6] == le and bo[3] == le) or # Down the right side
(bo[7] == le and bo[5] == le and bo[3] == le) or # Diagonal
(bo[9] == le and bo[5] == le and bo[1] == le)) # Diagonal
def getBoardCopy(board):
# Make a copy of the board list and return it
boardCopy = []
for i in board:
boardCopy.append(i)
return boardCopy
def isSpaceFree(board, move):
# Return True if passed move is free on the passed board.
return board[move] == ''
def getPlayerMove(board):
# Let the player enter their move.
move = ' '
while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board, int(move)):
print('What is your next move? (1-9)')
move = input()
return int(move)
def chooseRandomMoveFromList(board, movesList):
# Returns a valid move form the passed list on the passed board.
# Returns None if there is no valid move.
possibleMoves = []
for i in movesList:
if isSpaceFree(board, i):
possibleMoves.append(i)
if len(possibleMoves) != 0:
return random.choice(possibleMoves)
else:
return None
def getComputerMove(board, computerLetter):
# Given a board and the computer's letter, determine where to move and return that move
if computerLetter == 'X':
playerLetter = 'O'
else:
playerLetter = 'X'
# Here is the algorithm for our Tic-Tac_Toe AI:
# First check if we can win in the next move.
for i in range(1, 10):
boardCopy = getBoardCopy(board)
if isSpaceFree(board, i):
makeMove(boardCopy, computerLetter, i)
if isWinner(boardCopy, computerLetter):
return i
# Check if the player could win on their next move and block them
for i in range(1, 10):
boardCopy = getBoardCopy(board)
if isSpaceFree(boardCopy, i):
makeMove(boardCopy, playerLetter, i)
if isWinner(boardCopy, playerLetter):
return i
# Try and take one of the corners, if they are free
move = chooseRandomMoveFromList(board, [1, 3, 7, 9])
if move != None:
return move
# Try and take the center, if it is free
if isSpaceFree(board, 5):
return 5
# Move on one of the sides
return chooseRandomMoveFromList(board, [2, 4, 6, 8])
def isBoardFull(board):
# Return True if every space on th e board has been taken, Otherwise, reutrn False
for i in range(1, 10):
if isSpaceFree(board, i):
return False
return True
print('Welcome to Tic-Tac-Toe!')
while True:
# Reset the board
theBoard = [' '] * 10
playerLetter, computerLetter = inputPlayerLetter()
turn = whoGoesFirst()
print('The ' + turn + ' will go first.')
gameIsPlaying = True
while gameIsPlaying:
if turn == 'player':
# Player's turn
drawBoard(theBoard)
move = getPlayerMove(theBoard)
makeMove = (theBoard, playerLetter, move)
if isWinner(theBoard, playerLetter):
drawBoard(theBoard)
print('Congrats! You have won the game')
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('The game is a tie!')
break
else:
turn = 'computer'
else:
# Computer's turn
move = getComputerMove(theBoard, computerLetter)
makeMove(theBoard, computerLetter, move)
if isWinner(theBoard, computerLetter):
drawBoard(theBoard)
print('The computer has won!')
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('The game is a tie!')
break
else:
turn = 'player'
print('Do you want to play again? (yes or no)')
if not input().lower.startswith('y'):
break
r/inventwithpython • u/[deleted] • Mar 13 '16
On page 244 of 'Automate the Boring Stuff', there's a section with the heading 'Disabling Assertions'.
The final sentence of this section is: 'See Appendix B for details about how to launch your probably-not-insane programs with the -O option.'
However (in my copy, at least), there's no mention of this in Appendix B.
Is the information printed elsewhere in the book, or was it accidentally omitted?
r/inventwithpython • u/turicsa • Sep 29 '16
Is there any way to copy the clipboard in windows WITHOUT using pyperclip? (I love it, but in my job i can't have pyperclip module installed :( so i need a native python module or some code that gets the clipboard data (text).
Thanks
r/inventwithpython • u/StefanAlecu • Aug 12 '15
I'm currently at chapter 9, and I wrote the entire program, but I have a question: how can I replace the words string with a list? I ask it mainly because I tried to insert it as it is, but it said PEP 8: Line too long (using PyCharm) + that I also think super long lines are unreadable, so I want to span it across multiple lines. Tried to do it, but I don't know what to do with the .split(), so... is it possible? If yes, show me how, and the parts of the program that will need changing if I replace the string with a list.
r/inventwithpython • u/[deleted] • Mar 09 '17
I follow the steps in the lecture but I get to this conn.login('[email protected]','Password!21!') and I get an error message
error Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> conn.login('####gmail.com','Password') File "C:\Users\flatwoods\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 729, in login raise last_exception File "C:\Users\flatwoods\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 720, in login initial_response_ok=initial_response_ok) File "C:\Users\flatwoods\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 641, in auth raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbu0\n5.7.14 NKFUCpcSofwu-eYFpQLPYk16p6IDG7Yw_80luBxOCC_XkPWETsZ-KAfIUytctZYmVcHXvl\n5.7.14 DIcC_EqwIriGUrHrhvW5mYR2Ot_jD_nmK-wKZFZGmsusdB1JDJJfqkK6T_kPOYVxQOmR-c\n5.7.14 Le-oApg21W60tYt_3e8FY-mhkLGY5lfnxgYH0UGac89tZTlmMNP9hInDTUCGhL3gd6ZtUW\n5.7.14 dvjzuGsV-EBXBMSDcCOjwAQ2MYNuA> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 32sm1689645uaw.14 - gsmtp')
r/inventwithpython • u/Alamanjani • Sep 21 '16
None of the examples in the book with pyperclip works. I installed pyperclip with no problem (py3.5) and I can import it without the problem. But I get errors trying to use it:
> text = pyperclip.paste()
> pyperclip.copy()Error: text = pyperclip.paste() AttributeError: module 'pyperclip' has no attribute 'paste'
pyperclip version = 1.5.27-1
Since I'm running Linux, I did install xclip.
r/inventwithpython • u/xyz135711 • Dec 26 '17
Chapter 15 of "Automate the Boring Stuff with Python" discusses really cool stuff like multithreading, concurrency, and subprocesses. I really enjoyed studying it like I did the first fourteen chapters.
Yet, I believe other programs can be started on mac OS similar to how they can be in Windows contrary to what is stated under the “Launching Other Programs from Python" and “Opening Files with Default Applications” headings in this chapter.
You don't need to pass the ‘Open’ command and the application’s name to start an application in mac OS via Python. You just need to pass its executable file's absolute path to subprocess.Popen(), similar to how it would be done under Windows. Below is how the calculator application, for example, can be opened on mac OS from within Python.
import subprocess
calcProc = subprocess.Popen('/Applications/Calculator.app/Contents/MacOS/Calculator')
# Below expression should return “True” if calculator is launched and running
calcProc.poll() == NoneTrue # Correct value
The “default” application opening method recommended in the book (shown below) for mac OS has also the disadvantage of being non-trackable as far as I can see.
import subprocess
calcProc = subprocess.Popen(['open', ‘/Applications/Calculator.app/'])
# “False” value by expression below means calculator is not launched or is closed
calcProc.poll() == NoneFalse # Contrary to what this outcome implies the calculator is launched and not closed
To find the path to an executable app/program file in mac OS, CTRL-click the application and select Show Package Contents. Locate the “MacOS” subfolder through the opened Finder window. This subfolder should have the executable program file in it. CTRL-click the executable file and select Get Info. In the window that opens, you can get the path to the executable file from Where under General. Just copy and paste what is shown next to Where to your Python editor. Add a forward slash and the name of executable file as shown in the Finder window to it without any extensions.
The path may come out in a different (but the correct) format when pasted to your Python editor from how it might be shown in Finder's Get Info window. Also note that Python / mac OS is partly sensitive to the capitalization of the path. Therefore, do not change capitalization of any of the letters in the path after pasting it. If you make any capitalization changes, Python may not be able to locate the executable file.
This way of locating an executable for mac OS is partly mentioned under the “Launching Other Programs from Python" heading but for some reason the book, thereafter, recommends using and describes the “default” method.
Pls let me know if you have encountered otherwise when studying this chapter using mac OS or have any other suggestions. Thank you.
r/inventwithpython • u/gr4ycloud • Nov 16 '14
Hello everyone,
I've started working through the "Invent with Python" book, and must say it is quite pleasant. However, I have a question about the program presented in Chapter 4.
If the user types in anything that Python can not convert into an int on line 14, an expection is thrown on line 15 and the user is then dumped to the shell. I wanted to modify the program so that a friendly message is printed and the user has the opportunity to enter a valid integer again. From what I can tell, I have two options for dealing with this.
I use a "try-except" block and let Python handle the testing:
guess = input()
try:
guess = int(guess)
except ValueError:
print('Please enter a valid integer.')
continueOR
I use .isdigit() on the string returned from input() (understanding that this wouldn't accept negative numbers of course):
guess = input()
if not guess.isdigit():
print('Please enter a valid integer.')
continue
guess = int(guess)I'm very new to Python, though not quite new to programming, and was wondering what the author and other folks here thought would be proper in this situation.
Thanks for you time :).
r/inventwithpython • u/Zeldacode • Aug 09 '17
Help me please. I'm new to coding and have been at this for hours. Syntax error near the bottom at gameIsDone
r/inventwithpython • u/[deleted] • Mar 12 '17
I have the correct version and architecture of Pygame on my computer. My question is how do I install it in so that I can just use PIP Install?
r/inventwithpython • u/stussll • Jan 02 '18
What bugs did you identify and fix?
I'm wanting to double check my solution to the Ch. 10 Practice Project: Debugging Coin Toss
Here's what I came up with: https://pastebin.com/X5wvWGSL