r/inventwithpython • • Jul 24 '15

Chapter 7 debug doesn't work for me

1 Upvotes

The tutorial says that when you reach line 5 you should click step, and that "The debugger waits until the player enters a response into the program". For me, it opens up pyshell and when I go to the python 3.4.3 shell and type a number and press enter nothing happens. When I click "Out" to get out of pyshell, every button on the debug goes grey and I have to restart. If i try to click "over" the same thing happens. I've been trying to solve this for about 1/2 hour and it's really starting to drive me crazy. Please help.

Edit: Just to clarify, I have read the other issue someone else had with chapter 7 on this subreddit, but I did not understand the answer given


r/inventwithpython • • Jul 29 '15

line 47 pyperclip wrong type returned - caesar

1 Upvotes

running the ceaser cypher in the book I get the correct translated output but pyperclip errors that it has a <TYPEERROR>. this wouldn't be noticed from standard console but is reported in ipython

I am on windows 7 64bit with python 3.4.3 λ python --version Python 3.4.3 :: Anaconda 2.3.0 (64-bit) C:\Users\sayth\OneDrive\repos\cipher

This is the error

In [1]: pwd Out[1]: 'C:\Users\sayth\OneDrive\repos\cipher'

In [2]: %run cipher.py GUVF VF ZL FRPERG ZRFFNTR

ArgumentError Traceback (most recent call last) C:\Users\sayth\OneDrive\repos\cipher\cipher.py in <module>() 33 print(translated) 34 ---> 35 pyperclip.copy(translated)

C:\Users\sayth\OneDrive\repos\cipher\pyperclip.py in _copyWindows(text) 45 if not isinstance(text, str): 46 text = text.decode('mbcs') ---> 47 d.user32.OpenClipboard(None) 48 d.user32.EmptyClipboard() 49 hCd = d.kernel32.GlobalAlloc(GMEM_DDESHARE, len(text.encode('utf-16-le')) + 2)

ArgumentError: argument 1: <class 'TypeError'>: wrong type


r/inventwithpython • • Feb 24 '17

Chapter 9 Backup to Zip typos?

2 Upvotes

I'm going through Automate the Boring stuff and I'm following along with the Backup to Zip project. When I get to the third part about walking through the directory tree and adding the files and folders to the zip file I get this error:

NameError: name 'newBase' is not defined

for the for loop:

for filename in filenames:
    newBase / os.path.basename(folder) + '_'
    if filename.startswith(newBase) and filename.endswith('.zip')
        continue
    backupZip.write(os.path.join(foldername, filename))

At the end of the if statement I went ahead and added in a colon because it needs it, but I can't figure out how to get it to use newBase. I'm using Python 3 on Fedora 25.

Full code


r/inventwithpython • • Feb 18 '17

Problem with Invent your own computer game with python 3rd, chapter19

3 Upvotes

In file collisionDetection.py.
I can't understand the line 125:

mainClock.tick(40)

Does it means that the program pauses for 1/40s?
Any help will be appreciated very much. :)


r/inventwithpython • • Nov 11 '14

New to Reedit and learning from "Invent Your Own Computer Games with Python"

5 Upvotes

Just wanted to say that i´m working with the "Invent Your Own Computer Games with Python" book, and i´m learning a lot. My goal is to make my children to get interested in programming, and this book is just what i was looking for. Thanks a lot!!! By the way, i´m also new to Reddit, and feel so lucky about finding this learning community.


r/inventwithpython • • Nov 09 '14

A couple questions about the terms

2 Upvotes

I'm really enjoying working through the exercises. My 13 y old son has expressed interest in getting into game programming and I thought Python would be a good way to start.

I was thinking about working up something like assignment slides that would summarize each chapter and perhaps add a few interstitial exercises to supplement the code in the chapters. I'm thinking something I could customize to our situation. I don't think I'd publish them, but what are licensing terms? If I did that, I would be just pushing them online somehere for no charge.

BTW - the pythontutor.com link is a neat discovery which will help with pairing activities with my son. Thanks!


r/inventwithpython • • Mar 03 '16

Hangman error.

1 Upvotes

Soo, im very new all of thism and im getting this error.

Traceback (most recent call last): secretWord=getRandomWord(words) NameError: name 'words' is not defined

on this part of the code:

missedLetters = ''

correctLetters = ''

secretWord = getRandomWord(words)

gameIsDone = False


r/inventwithpython • • Sep 14 '16

Chapter 9 Project - Fill in the Gaps

3 Upvotes

I'm having some issues with this project. Basically, what I've done is create a regex to find a file like spam001.txt. Then I walk through the folder, picking up any hits with my regex. After that, I'm looping through that list of objects and trying to see if I can find the ones that have the '1' or '2'. It's not really working. I'm not sure where to go after the walk through the folder or how to find sequential numbering. Here's my code:

import os, re, pprint

regex = re.compile(r'\w*\d\d\d.txt')

for folderName, subfolders, filenames in os.walk('.'):

    print(filenames)
    mo = regex.findall(pprint.pformat(filenames))
    
    number = 1
    
    for i in mo:
            if str(number) in i:
                    print(number)
                    print(i)
            
            else:
                    
            number = number + 1
            print(number)

Any help or guidance is really appreciated because I am really stuck.


r/inventwithpython • • Jul 21 '15

Chapter 4 Issue

1 Upvotes

So, I'm trying to get through Chapter 4 and for some reason, on line 19 I get a TypeError: unorderable types: int() < str()

I don't understand what I'm doing wrong, I did a diff and it seems to be the same.

http://pastebin.com/9HH0wuP9


r/inventwithpython • • Jul 16 '15

Chapter 4 - difficult question with list length and for loops.

1 Upvotes

I'm trying to write a program, that asks the user for input. Whatever they put is stored into the list as a new item, and each item is then printed on its own line. It then asks you again to add another value. This goes on forever, adding more and more values, and having the entire list printed back to you each time.

The complicated part is that I want to limit how long the list can get. Once the list gets beyond a certain length, I want the first value to be deleted, and only the most recent few lines to be printed. the length of the list is specified at the start. So far this works.

the problem happens once the list reaches this limit. for some reason, it just stops printing the list back. I don't know what's going on.

Pastebin: http://pastebin.com/Q6bGJjG2

Thanks for any help!


r/inventwithpython • • Feb 28 '16

why can't modify or erase expression or text after pressing enter?

2 Upvotes

title self explanatory.


r/inventwithpython • • Nov 25 '13

What if I want to use 2.x instead?

1 Upvotes

Can I still follow this book and just make the small changes in order to learn 2.7 rather than 3? or would I run into more problems than I need?


r/inventwithpython • • Dec 20 '17

where to start?

6 Upvotes

I have a 13 year old who has been playing with Scratch for a bit and is wanting something a bit more substantial. I have been meaning to learn Python myself and thought Python/PyGame would be a good next step for him (and would give us something to explore together).

Question is what would be a good book to start off with?

Thanks in advance!


r/inventwithpython • • Jul 28 '15

I can't install pyperclip - get "no commands supplied error" (MAC)

1 Upvotes

I'm unable to install pyperclip.py... I've downloaded the folder and navigated to it in terminal. There I tried "python setup.py" and received the error message: "error: commands supplied".

I've researched it a bit and have heard things like my python "path", but I can't figure it out...

Please help!


r/inventwithpython • • Feb 20 '17

[AUTOMATE] Ch. 4 Lists - Comma Code Exercise

2 Upvotes

Hello World! first post ever to Reddit!

Just wanted to know how you guys found a solution to the Comma Code exercise in ch. 4 of automate the boring stuff.

I did a quick search for a solution but couldn't find one.

I know the exercise states to make a function but my solution was this...

name = input("Gimme a list value: ")

newName = name[0:-1] + " and " + name[-1]
print(newName)

Any (constructive) comments? I'll be mashing away trying to find a solution with a function in the mean time.


r/inventwithpython • • Feb 25 '16

Trouble with retrieving and deleting emails with imap - Chapter 16

1 Upvotes

I'm having trouble replicating the example from chapter 16. I get an error message when I attempt

message = pyzmail.PyzMessage.factory(rawMessages[40041]['BODY[]'])

my input is:

>>> import imapclient, pyzmail
>>> imap.Obj = imapclient.IMAPClient('imap.gmail.com', ssl=True)
>>> imapObj.login('[email protected]', 'PASSWORD')
b'[email protected] authenticated (Success)'
>>> imapObj.select_folder('INBOX', readonly = True)
{b'RECENT': 0, b'FLAGS': (b'\\Answered', b'\\Flagged', b'\\Draft', ..., b'$Phishing'), b'PERMANENFLATS': (), b'READ-ONLY: [b''], ... b'UIDNEXT':11480}
>>> UIDs =  imapObj.search(['SINCE 20-Feb-2016'])
>>> UIDs
[11443, 11450, 11452, ..., 11479]
>>> rawMessages = imapObj.fetch([11450], ['BODY[]', 'FLAGS'])
>>> message = pyzmail.PyzMessage.factory(rawMessages[11450]['BODY[]'])

Where I get the following message:

File "<stdin>", line 1 in <module>
  KeyError: 'BODY[]'

At this point, I'm not really sure how to proceed.


r/inventwithpython • • Jul 23 '15

chapter 5 dictionary method

1 Upvotes

what's different between get() and setdefault() ?


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 • • Sep 14 '17

I have a problem with the Hangman game. The code that I copied from the textbook does not match the code that I compared it with the Diff Tool. I'm not talking about typing errors. There are a lot of differences in lines, spacing, and characters.

5 Upvotes

I have a problem with the Hangman game. The code that I copied from the textbook does not match the code that I compared it with, from the Diff Tool. I'm not talking about typing errors. There are a lot of differences in lines, spacing, and characters.


r/inventwithpython • • May 04 '16

Checking availability of library book using beautifulsoup

2 Upvotes

I'm learning python. And I'm trying to use it to automate the process of checking a library book's availability.

I tried executing it with bs4, request, and partition.

This is the link that I am trying to parse from: [http://catalogue.nlb.gov.sg/cgi-bin/spydus.exe/FULL/EXPNOS/BIBENQ/1592917/156302298,2][1]

I view its source code, and here's a snippet of it:

<tr> <td valign="top"><a href="/cgi-bin/spydus.exe/ENQ/EXPNOS/GENENQ/1564461?LOCX=BIPL">**Bishan Public Library**</a> <br /> </td> <td valign="top"> <book-location data-title="The opposite of everyone" data-branch="BIPL" data-usagelevel="001" data-coursecode="" data-language="English" data-materialtype="BOOK" data-callnumber="JAC" data-itemcategory="" data-itemstatus="" data-lastreturndate="20160322" data-accession="B31189097E" data-defaultLoc="Adult Lending">Adult Lending</book-location> </td> <td valign="top"><a href="/cgi-bin/spydus.exe/ENQ/EXPNOS/BIBENQ/1564461?CGS=E*English">English</a> <br /><a href="/cgi-bin/spydus.exe/WBT/EXPNOS/BIBENQ/1564461?CNO=JAC&amp;CNO_TYPE=B">JAC</a> <br /> </td> <td valign="top">**Available** <br /> </td> </tr> <tr> <td valign="top"><a href="/cgi-bin/spydus.exe/ENQ/EXPNOS/GENENQ/1564461?LOCX=BMPL">**Bukit Merah Public Library**</a> <br /> </td> <td valign="top"> <book-location data-title="The opposite of everyone" data-branch="BMPL" data-usagelevel="001" data-coursecode="" data-language="English" data-materialtype="BOOK" data-callnumber="JAC" data-itemcategory="" data-itemstatus="" data-lastreturndate="20160405" data-accession="B31189102C" data-defaultLoc="Adult Lending">Adult Lending</book-location> </td> <td valign="top"><a href="/cgi-bin/spydus.exe/ENQ/EXPNOS/BIBENQ/1564461?CGS=E*English">English</a> <br /><a href="/cgi-bin/spydus.exe/WBT/EXPNOS/BIBENQ/1564461?CNO=JAC&amp;CNO_TYPE=B">JAC</a> <br /> </td> <td valign="top">**Available** <br /> </td> </tr> The information that i am trying to parse is which library the book is available at.

Here's what I did:

import requests, bs4

res = requests.get('http://catalogue.nlb.gov.sg/cgi-bin/spydus.exe/FULL/EXPNOS/BIBENQ/1592917/156302298,2') string = bs4.BeautifulSoup(res.text) Then I try to make string into a string:

str(string) And it printed the whole source code out and severely lagged my IDLE!

After it stopped lagging, I did this:

keyword = '<a href="/cgi-bin/spydus.exe/ENQ/EXPNOS/GENENQ/1564461?LOCX=' string.partition('keyword') Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> string.partition('keyword') TypeError: 'NoneType' object is not callable I don't know why it caused an error, I did make the string into a string, right?

Also, I used that keyword because it is right before the "library branch" and right after "availability". So i thought even if it churns out a lot of other redundant code, I'll be able to see in the first line which library branch the book is available at.

I am sure the way I did it is not the most efficient way, and if you could point me to the right way, or show it to me, i will be extremely grateful!

I'm sorry this is a very long post, but i'm trying to be as detailed about my situation as possible. Thank you for bearing with me.


r/inventwithpython • • Feb 05 '15

Where to save files

2 Upvotes

Hi As someone who is now starting to make larger programmes on their own, is there somewhere I ought to be saving my files? Perhaps in the pygame or python directory?

Perhaps this is not something that matters at this stage but I was just curious about where 'serious' programmers might store their files. For the sake of both organisation and making things easier for the computer itself.


r/inventwithpython • • Apr 16 '17

Query from Automate the boring stuff book

3 Upvotes

Hi - I'm just working through Al's book online (complete Python/programming novice!) and struggling to understand why the programme below works to be honest. Would anyone be able to explain line by line what is going on and why?

Huge thanks in advance! Sam

catNames = [] while True: print('Enter the name of cat ' + str(len(catNames) + 1) + ' (Or enter nothing to stop.):') name = raw_input() if name == '': break catNames = catNames + [name] # list concatenation print('The cat names are:') for name in catNames: print(' ' + name)


r/inventwithpython • • Feb 08 '18

chapter 1 wrong awswer.

3 Upvotes

in 4 exercise : 4. Here are some words and their encryptions. Which key was used for each word? a. ROSEBUD – LIMYVOX b. YAMAMOTO – PRDRDFKF c. ASTRONOMY – HZAYVUVTF

the key of c is 7 ,not 19.


r/inventwithpython • • Feb 05 '15

Having some trouble with Chapter 10 - Tic Tac Toe - Game tied after 1st move.

2 Upvotes

Hi guys,

I was hoping for a little help with this. I copied the code out and used the checker - apart from missing comments and using _ rather than capital letters to denote words in the function names, my code looks to be exactly the same.

However, the game keeps telling me that it is a tie, sometimes even after the first go. I've checked through all my functions and tested it multiple times. It seems to stick on 7 and 6 more often than others, but sometimes the computer will go first several times in a row and the game will be tied each time! It's driving me mad . . .

Here's my code, i thought the problem was in either: is_space_free or is_board_full

but after having checked them, I have no idea!

import random

def draw_board(board): print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | |') print('------------') print(' | |') print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) print(' | |') print('------------') print(' | |') print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3]) print(' | |')

def input_player_letter(): letter = '' while not (letter == 'X' or letter =='O'): print('Do you want to be X or O?') letter = input().upper()

if letter =='X':
    return ['X', 'O']
else:
    return ['O', 'X']

def who_goes_first(): if random.randint(0,1) == 0: return 'computer' else: return 'player'

def play_again(): print('Do you want to play again? (yes or no)') return input().lower().startswith('y')

def make_move(board, letter, move): board[move] = letter

def is_winner(bo, le): return((bo[7] == le and bo[8] == le and bo[9] == le) or (bo[4] == le and bo[5] == le and bo[6] == le) or (bo[1] == le and bo[2] == le and bo[3] == le) or (bo[7] == le and bo[4] == le and bo[1] == le) or (bo[8] ==le and bo[5]==le and bo[2]==le) or (bo[9]==le and bo[6]==le and bo[3]==le) or (bo[7]==le and bo[5]==le and bo[3]==le) or (bo[9]==le and bo[5]==le and bo[1]==le))

def get_board_copy(board): dupe_board = []

for i in board:
    dupe_board.append(i)

return dupe_board

def is_space_free(board, move): return board[move] == ' '

def get_player_move(board): move = ' ' while move not in '1 2 3 4 5 6 7 8 9'.split() or not is_space_free(board, int(move)): print('what is your next move? (1-9)') move = input() return int(move)

def choose_random_move_from_list(board, moves_list): possible_moves = [] for i in moves_list: if is_space_free(board, i): possible_moves.append(i)

if len(possible_moves) != 0:
    return random.choice(possible_moves)
else:
    return None

def get_computer_move(board, computer_letter): if computer_letter =='X': player_letter == 'O' else: player_letter == 'X'

for i in range(1, 10):
    copy = get_board_copy(board)
    if is_space_free(copy, i):
        make_move(copy, computer_letter, i)
        if is_winner(copy, computer_letter):
            return i

for i in range(1, 10):
    copy = get_board_copy(board)
    if is_space_free(copy, i):
        make_move(copy, player_letter, i)
        if is_winner(copy, player_letter):
            return i

move = choose_random_move_from_list(board, [1,3,7,9])
if move != None:
    return move

if is_space_free(board, 5):
    return 5

return choose_random_move_from_list(board, [2,4,6,8])

def is_board_full(board): for i in range(1, 10): if is_space_free(board, i): return False else: return True

print('Welcome to Tic Tac Toe!')

while True: the_board = [' '] * 10 player_letter, computer_letter = input_player_letter() turn = who_goes_first() print('The ' + turn + ' will go first.') game_is_playing = True

while game_is_playing:
    if turn == 'player':
        draw_board(the_board)
        move = get_player_move(the_board)
        make_move(the_board, player_letter, move)

        if is_winner(the_board, player_letter):
            draw_board(the_board)
            print('Hooray! You have won the game!')
            game_is_playing = False
        else:
            if is_board_full(the_board):
                print('The game is a tie!')
                break
            else:
                turn = 'computer'

    else:
        move = get_computer_move(the_board, computer_letter)
        make_move(the_board, computer_letter, move)

        if is_winner(the_board, computer_letter):
            draw_board(the_board)
            print('The computer has beaten you! You lose!')
            game_is_playing = False
        else:
            if is_board_full(the_board):
                print('The game is a tie!')
                break
            else:
                turn = 'player'

if not play_again():
    break

r/inventwithpython • • May 07 '16

Chpt 18: Error downloading pyobjc-framework-Quartz

1 Upvotes

for chpt 18, the pyautogui Module is needed. however as per instructions of the author, i should download pyobjc-framework-Quarts first.

I'm using OS X I entered this command into my terminal: pip3 install pyobjc-framework-Quarts

It started downloading the file.

Then it showed this:

xcode-select: note: no developer tools were found at '/Applications/Xcode.app', requesting install. Choose an option in the dialog to download the command line developer tools. Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/setuptools/sandbox.py", line 152, in save_modules yield saved

ending with:

Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/jt/ft6m6cp50v142y48jzn09gsr0000gn/T/pip-build-x0k5pxwa/pyobjc-framework-Quartz

I downloaded the xcode developer command line as it prompted and tried to download the module again, but to no avail :(

please advise ~