r/inventwithpython • • Dec 08 '18

Chapter 5 fantasy game inventory errors

1 Upvotes

For some reason i'm getting nonetype errors ( File "inventory.py", line 6, in displayInventory for k, v in inventory.items(): AttributeError: 'NoneType' object has no attribute 'items') when running my code for this excercise. It's strange because I have it working but specifically can't use this

inventory.items():

I have to use

myItems.items():

which means that my code isn't reusable and blocks me from finishing the second half of the excercise (which I have 90% working) full code:

myItems = {'rope':1,'sword':1,'shield':0,'potion':3,'mushroom':2,'chain':1,'egg':12}
def displayInventory(inventory):
    print('Inventory:')
    item_total = 0
    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        item_total = item_total + v
    print('Total number of items: ' + str(item_total))


displayInventory(myItems)

r/inventwithpython • • Jun 29 '18

Nostarch book cover becoming unglued

1 Upvotes

Hi:

I enjoy your publications and intend to buy more.

Just wanted to alert you to a problem I'm having with "How to automate the boring stuff ..."

Not sure what your affiliation with nostarch is ..

Bought on amazon  (great book) but the glue is becoming soft and not holding the cover on.

(office temperature is around 70-85 F)

I have reattached it and I'm going t try and use superglue.

I tried to visit nostarch website to let them know but they are trying to install some rogue chrome extension, so no F&*%$# way :)

Just wanted to let you know

Best


r/inventwithpython • • Apr 22 '18

Python help, got a test tomorrow. (Pretty basic)

1 Upvotes

Guys ive been trying to mount the code on a class but it keeps triggering erros, Im not sure where to use the: "self." in variables! Could someone help ? here is the code: def dimensiones(): mat=[] f = int(input("Ingrese el tamaño de las filas: ")) c = int(input("Ingrese el tamaño de las columnas: ")) tipo=int(input("Desea ingresar 2=letras/1=numeros")) if tipo == 1: ifnums(f,c,tipo) else: ifletras(f,c,tipo)

def ifnums(f,c,t): nums=[] for x in range(f): nums.append([ ]) for y in range(c): conte=int(input("Ingrese numeros: ")) nums[x].append(conte) printo(nums) solicito(nums,t)

def ifletras(f,c,t): lets=[] for x in range(f): lets.append([]) for y in range(c): conte=input("Ingrese letras: ") lets[x].append(conte) printo(lets) solicito(lets,t)

def solicito(m,t): banner=0 if t==1: busco=int(input("Ingrese el numero a buscar: ")) else: busco =input("Ingrese el letra a buscar: ")

for x in range(len(m)):
    for y in range(len(m[x])):
        if(busco==m[x][y]):
            print("Se encuentra el numero: ",busco,"en la fila: ",(x+1),",Y columna:",(y+1))
            banner=1
if banner==0:
    print("No se encontro")

def printo(mat): print("-----------------") print("Matriz completa: ") for x in range(len(mat)): print(mat[x])

dimensiones()


r/inventwithpython • • Jan 29 '18

caesar_cipher2.py doesn't work.

1 Upvotes

LETTERS = ' !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\] _`abcdefghijklmnopqrstuvwxyz{|}~'

It falls apart here. I don't see how it's possible to include all possible symbols here, especially the single and double quotes here. It confuses the vm, and won't decipher correctly.

Tips or solutions?


r/inventwithpython • • Jan 09 '18

addressing list element error

1 Upvotes

There is a strange error when I try to change an element in a simple empty list Board1 size 3x3 (all the elements are ' '). For example Board1[0][1]='12' changes 3 elements in the Board1 instead of only one, if the list is generated through a for loop, otherwise it is ok. I would appreciate if someone explains what is the problem here? Please see the code and the difference..

line=[' ']*3

Board1=[]

for y in range(3):

 Board1.append(line)

print('Board1=%s' %(Board1))

Board2=[[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']] print('Board2=%s' %(Board2))

Board1[0][1]='12'
print('new Board1=%s' %(Board1))

Board2[0][1]='12'
print('new Board2=%s' %(Board2))


r/inventwithpython • • Dec 08 '17

Problem decrypting messages

1 Upvotes

Hello, I keep getting the error int too large to convert to c long whenever I run the decryption function. I checked my code with what was provided and it was the same. Kindly assist


r/inventwithpython • • Dec 06 '17

Small typo in Automate Boring Stuff Ch. 9

Thumbnail
self.learnpython
1 Upvotes

r/inventwithpython • • Sep 21 '17

Problem with Tic Tac Toe game.

1 Upvotes

I'm getting a invalid syntax error in the Tic Tac Toe game. Line 50. I've typed it exactly like the book and it's the same in the dif tool. I'm using the 3rd edition web download book.

def isWinner(bo, le):

Too bad when you get an error, it didn't tell you how to fix it.


r/inventwithpython • • Aug 11 '17

Tic Tac Toe (Invent your Own Games Ch. 10) Error

1 Upvotes

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 NoneType

When 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 • • Jul 11 '17

Shelve error in chapter 8

1 Upvotes

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 • • Jul 05 '17

[Automate] Automate the Boring Stuff - Chapter 7 - Regex Version of Strip() Question

1 Upvotes

Hi guys, quick question here:

Chapter 7's last practice problem says the following:

Write a function that takes a string and does the same thing as the strip() string method. If no other arguments are passed other than the string to strip, then whitespace characters will be removed from the beginning and end of the string. Otherwise, the characters specified in the second argument to the function will be removed from the string.

My question is: *Do I have to use args or some new thing not covered by this book yet, or is there a way to have a function that does something with no argument and then does something if you add an argument as well?


r/inventwithpython • • May 09 '17

[Automate] Having trouble with printing formatted table

1 Upvotes

I'm working on the project for chapter 6 of the "Automate the Boring Stuff" (table printer) and I'm having a hard time figuring out how to properly setup my loops to go through the ljust, rjust, and center formatting. I already have code that prints the table in a 'grid" found here but I feel like it's kind of bulky code for what it does.

Can anyone help point me in the right direction to print this properly and maybe clean up my code?


r/inventwithpython • • Apr 02 '17

How to install PYPERCLIP? [hacking]

1 Upvotes

Hey there.

I've been have trouble finding out how to install the pyperclip module on windows. Any help would be much appreciated.

I am using the Python 3.6.1


r/inventwithpython • • Mar 27 '17

[invent] Chapter 3, need help with the "Guess The Number" game.

1 Upvotes

Windows 7 64 bit with Python 3.5.2, need help. https://pastebin.com/DkCpFZzN Code is right there. I'm trying to get the "random" function working but after line 5 where I enter my name, the error says "line 8, in <module> number = random.randit(1, 20) AttributeError: module 'random' has no attribute 'randit'"


r/inventwithpython • • Mar 18 '17

[automate]Chapter 3 Practice Project Collatz

1 Upvotes

I can't figure out why the output is just one loop. http://pastebin.com/LZyNiDeq


r/inventwithpython • • Mar 18 '17

[invent] I am trying to make a game merging the animation with the collier game? I can't seem to get the enemy object to move.

1 Upvotes

I can't seem to get the trump rectangle to move. I think it is because the object on screen is both a image and a rect. not just a rect. Look under Trump AI section http://pastebin.com/gwUjTF9H


r/inventwithpython • • Dec 16 '16

[Automate] Difficulty running Selenium due to Marionette in Chapter 11 exercises

1 Upvotes

Hi - I'm running into a problem that's a little beyond my expertise. I've been trying to get into the Selenium section in Chapter 11, but I had a lot of problems that weren't covered in the book -- first I had to download the Gecko driver. I followed all the directions, and I can

browser = webdriver.Firefox()

which opens a browser window and also spits back this error:

selenium.common.exceptions.WebDriverException: Message: Unsupported Marionette protocol version 2, required 3

Attempting even the first command:

browser.get('http://inventwithpython.com')

results in a name error:

NameError: name 'browser' is not defined

Marionette: A lot of searching yielded the following:

pip install marionette_driver

but attempting to install it gives me the error message:

Command "python setup.py egg_info" failed with error code 1 in C:\Users\Jacob\AppData\Local\Temp\pip-build-i1y17220\mozrunner\

When I dive any deeper into the documentation, I hit a severe knowledge gap. FAQs start directing me toward virtualenv and command line stuff, which is a complete black box to me at this point. Also, everything is presented in UNIX command line formats, which is doubly difficult! If anyone has any insights or a moment to walk through this with me, I would really appreciate it.


r/inventwithpython • • Oct 27 '16

Affine Cipher Hacker (ch. 16)

1 Upvotes

One of my students is participating in the national cipher challenge (UK) and has been working through the Hacking book at the same time. He knows that challenge 2B is an Affine Cipher and wanted to use his program to find the solution. The Affine sample ciphertext can be hacked by the program (alan turing quote), but it fails when trying challenge 2B https://www.cipherchallenge.org/challenges/challenge-2/

Two other online tools were able to hack it (a= 5, b = 11): http://rumkin.com/tools/cipher/affine.php http://www.dcode.fr/affine-cipher

We've tried many variations to no avail.

What are we missing? Any advice?


r/inventwithpython • • Oct 25 '16

[Pygame] Debugging Pygame Help?

1 Upvotes

Hi guys, I just learned about virtual environments. To avoid running into problems further down the road, I scrapped my modules before they got out of hand and am now working with virtual environments, a 'pygame' env for everything pygame, with Pygame re-installed, naturally. But now it's acting up.

Take as an example the memorypuzzle.py from http://inventwithpython.com/pygame/downloads/ Most of it works, but it doesn't reveal the second square when you click it. I already checked the 'firstSelection' part, that works. The square also does get set to 'True' in the 'revealedBoxes' List. And it does show (and keeps showing) both squares once you've found a matching pair.

tl;dr -- I don't get any error messages and the game code as such seems to be correct (it's the sample code, and it worked fine before), so I have no idea where to even start debugging? Help?

Many thanks in advance!

UPDATE: so now it doesn't reveal any squares anymore.

I suspected sth must be wrong with event handling, so I added the following lines to the code:

myevents = pygame.event.get()

      if len(myevents) != 0:

          print(myevents)

(I put it into the main Game Loop, inside the "while True", just before "for event in pygame.event.get()"...)

The output that generates is this. Note that I clicked on a different square each time, so I don't know why the position doesn't keep changing:

[[<Event(4-MouseMotion {'buttons': (0, 0, 0), 'rel': (229, 375), 'pos': (229, 375)})>, <Event(5-MouseButtonDown {'pos': (229, 375), 'button': 1})>, <Event(6-MouseButtonUp {'pos': (229, 375), 'button': 1})>, <Event(4-MouseMotion {'buttons': (0, 0, 0), 'rel': (-139, -326), 'pos': (90, 49)})>, <Event(5-MouseButtonDown {'pos': (90, 49), 'button': 1})>, <Event(6-MouseButtonUp {'pos': (90, 49), 'button': 1})>]
[<Event(5-MouseButtonDown {'pos': (90, 49), 'button': 1})>]
[<Event(6-MouseButtonUp {'pos': (90, 49), 'button': 1})>]
[<Event(5-MouseButtonDown {'pos': (90, 49), 'button': 1})>]
[<Event(6-MouseButtonUp {'pos': (90, 49), 'button': 1})>]
[<Event(5-MouseButtonDown {'pos': (90, 49), 'button': 1})>]

(last line gets repeates as often as I keep clicking)

Any help would be very much appreciated. Thanks!


r/inventwithpython • • Sep 06 '16

[ERROR] IDLE can't import Tkinter.

1 Upvotes

So i've just got the book and i was so excited to start coding, installed python and when i tried to run it, i got "Idle can't import Tkinter, Your Python may not be configured for Tk" I tried google but no use. I am using 64bit of Ubuntu 16. Could anyone help me out please?


r/inventwithpython • • Aug 18 '16

"Automate the Boring Stuff" site down?

1 Upvotes

I'm loving the course, but I've tried to continue today and the website appears to be down. Can anyone confirm?


r/inventwithpython • • Aug 08 '16

random 'Extending Hangman' question

1 Upvotes

I'd like to start by saying I'm enjoying the book a lot.

Well, I'm modifying the original Hangman game from chapter 9. It involves randomly picking an item from a list to be the secret word.

In chapter 9.5, the Hangman game is now using a dictionary. It first picks up a key from the dictionary. Each key is holding a list of strings, and one word is chosen from this list.

So the process islike this:

  1. pick a key that holds a list;

  2. pick a word from list;

The first step uses the random.choice() method. The second one uses random.randint() method.

The function code:

def getRandomWord(wordDict): # This function returns a random string from the passed dictionary of lists of strings, and the key also. # First, randomly select a key from the dictionary: wordKey = random.choice(list(wordDict.keys()))

# Second, randomly select a word from the key's list in the dictionary:
wordIndex = random.randint(0, len(wordDitc[wordKey])- 1)

Why is it? Why not use randint() or choice() on the two of them? I'm going to test them this way later, but I might not understand why it works/doesn't work.


r/inventwithpython • • Jul 30 '16

Question??? Invent with Python, Hangman Game

1 Upvotes

In the hangman game I do not exactly know what the **end = ' ' ** does. I really don't understand why it's in the print function either.


r/inventwithpython • • Jul 29 '16

Chapter 13: What do we need this line?

1 Upvotes

if moveResult == False: (Lines 193, 194) continue

Why do we need it when we already have these lines in def enterPlayerMove() ?

move = move.split()

     if len(move) == 2 and move[0].isdigit() and move[1].isdigit() and isValidMove(int(move[0]), int(move[1])):

         return [int(move[0]), int(move[1])]

r/inventwithpython • • Jul 28 '16

Chapter 6 Project: Password Locker

1 Upvotes

I'm working through Automate the Boring Stuff, and it's been going pretty well until Ch. 6. No matter what I do I can't seem to get this script to run.

When I try to run it in IDLE I receive the following error message:

Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> email NameError: name 'email' is not defined

And, when I try to run it from the command line it correctly prints the line: "Usage: python pw.py [account] - copy account password" but then gives me "Press any key to continue..."

I'm certain I have the code typed out correctly (but I've pasted it below), and I'm using Windows 10 and Python 3.5.2. Any ideas? Thank you

! python3

pw.py - An insecure password locker program

PASSWORDS = {'email': 'easyPW', 'blog': 'hardPW', 'luggage': '12345'}

import sys, pyperclip if len(sys.argv) < 2: print('Usage: python pw.py [account] - copy account password') sys.exit()

account = sys.argv[1] # first command line arg is the account name

if account in PASSWORDS: pyperclip.copy(PASSWORDS[account]) print('Password for ' + account + ' copied to clipboard.') else: print('There is no account named ' + account)