r/inventwithpython • • Oct 13 '15

Beautiful Soup in Automate the Boring Stuff (Ch. 11) only works 50% of the time. Anyone else having this problem?

2 Upvotes

When I run the program exactly as offered, I succesfully get the price information only about half the time. The other half, I get a "503 Server Error: Service Unavailable".

This happens when run on the Amazon.com website, and I am completely unable to get accounting information from finance.yahoo.com website (example: downloading revenues from http://finance.yahoo.com/q/is?s=PG+Income+Statement&annual)

Any advice about where I am going wrong and/or how to remedy this situation would be greatly appreciated. Thanks!


r/inventwithpython • • Sep 22 '15

Chapter 17 Animation not Working

2 Upvotes

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 • • Jun 25 '15

Thunderbird is a pain of a email client:Automate boring stuff

2 Upvotes

I am working on an automated emailer based on the one in Automate the boring stuff. It works well except when I try to read it using Thunderbird. (Seriously I have read the exact same email through Gmail's website and Thunderbird and they are different)

With the line smtpObj.sendmail('[email protected]',To,'Subject: test \n' + '\nDear '+name+'\nCan I order the following from you?\n \n'+body+

                 '\nChris \nKPFA Radio')

It would look correct in Gmail and Hotmail, but until I put the extra /n before "Dear", It would put Subject: Test Dear Chris as the subject
and simply '\nChris \nKPFA Radio' as the main part of the email. None of the actual details of what I want to order from people.

I have coded around it by just trying various things until it worked, but I don't know why. Is Thunderbird just written to interpret the message differently ? Is it not following standards or are standards just loose.

Since I want to use this mailer at work, sending out real work related emails to outside people, how can I be sure that there aren't other 'gotchas' out there . I don't know what email client they will be using and I can't ask them if they got my previous email without it looking odd. (These are established vendors, so it's not spam, it's just that asking if they got the last email may not look professional to them).


r/inventwithpython • • Jun 02 '15

Global And Local scope are confusing me ! -chapter 6 invent with python

2 Upvotes

i was confused at chapter 6 page 55 about the local and global scope, and about the example of changing a global variable inside a function , actually before the example the book says that " but attempting to change a global variable from the local scope won’t work. What Python actually does in that case is create a local variable with the same name as the global variable " , i dont get it when python will make 2 different variables while in the example the function bacon has spam variable and outside it there is spam , at first i thought the result of the example would be ( 99 , 42 , 99) not ( 42, 99, 42 ) if python creates another variable with the same name, then why did he change the value of local spam ? and why the value of the global spam changed from 42 to 99 ? thanks and i hope you got what i'm trying to say . again: the example is at page 55 in book ( invent with python )


r/inventwithpython • • May 31 '15

Understanding Len function in Chapter 9 (Hangman)

2 Upvotes

So I actually bought the book "Invent your own computer games with Python", third ed.

I'm new to programming though i've tested it before in school, back then I had a hard time to keeping up and understanding everything. I don't know if that has anything to do with my not so high math skills, but anyway.

I'm reading chapter 9 at the moment and I'm kinda stuck in the follwing section:

61. def getRandomWord(wordList): 62. # This function returns a random string from the passed list of strings. 63. wordIndex = random.randint(0, len(wordList) - 1) 64. return wordList[wordIndex]

I think the author has forgotten to explain the len-function in the book. I googled it of course, and I know that len "counts" how many letters a word exists of for example. But if anyone could explain the line 3 (btw, its actually 63 if you read the book, but the post keep typin 1,2,3,4) to me, I would be grateful.

Link: https://inventwithpython.com/chapter9.html

I know that the function returns a single secret word from the wordLIst, but I dont know how. Why is there a len-function, why do we want to count how many letters there is in the word we want to randomly select?

As you can guess, I need a kick in the right direction. Please explain to me as if I'm 5 years old :).

Ms


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 • • 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 • • Jan 29 '15

problem about pyperclip.py in caesarCipher.py, Chapter 6

2 Upvotes

when I run caesarCipher.py, it shows this:

".../pyperclip.py", line 150, in <module> import gtk ImportError: No module named 'gtk'

and ".../pyperclip.py", line 155, in <module> import PyQt4.QtCore ImportError: No module named 'PyQt4'

and also: ".../pyperclip.py", line 162, in <module> raise Exception('Pyperclip requires the gtk or PyQt4 module installed, or the xclip command.') Exception: Pyperclip requires the gtk or PyQt4 module installed, or the xclip command.

Can you help me to explain why I meet this problem?My system is Ubuntu 14.04


r/inventwithpython • • Jan 20 '15

Problems in Chapter 7 - The Debugger.

2 Upvotes

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...


r/inventwithpython • • Jan 07 '15

Has anyone figured out how to display .png images?

2 Upvotes

I have a top and bottom png image. The top image is mostly transparent (alpha) so I should be able to see most of the bottom image, yet I see black in those areas instead (as if the top image image transparency isn't working).

Any pointers how to go about this?


r/inventwithpython • • Dec 11 '14

A question about the book

2 Upvotes

So, I just wanted to ask, what important python topics weren't covered in the "Invent your own computer games with python" book and where should I learn them?


r/inventwithpython • • Nov 16 '14

Taking exception to guess.py

2 Upvotes

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.')
    continue

OR

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 • • Nov 13 '14

Ch. 13 - getRandomChests function question

2 Upvotes

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 • • 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 • • Nov 06 '14

How do I import pyperclip using Ubuntu 14 LTS?

2 Upvotes

Hi there. I'm quite new to using Ubuntu and am having issues with pyperclip.py not working.

Can someone clarify how exactly I get it to work, as it quotes issues with gtk/PyQt dependencies.

Either:

  • using pyCharm (how do I import pyperclip)?

  • using Ubuntu, with cmd python3 ~/pyperclip.py


r/inventwithpython • • Oct 06 '14

Chapter 4. Line 143 - Strange code?

2 Upvotes

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 - 1

Which to me looks confusing, couldn't you just use:

counter = x + 2

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

chapter 10 tic-tac-toe not working

2 Upvotes

i made a small change on line 26, replacing the print and then letter = input() statement with a letter = raw_input(print 'do you want to be 'o' or 'x'')

that ran fine, but when the program advances my move never registers or appends to the board. i copied this from the source script. has anyone else has issues/insights?


r/inventwithpython • • Aug 31 '14

Making Games with python, Squirrel example, questions.

2 Upvotes

Hey everyone, I'm new to python and pygame generally. I have been trying to study the several examples of the book and have learnt quite a lot already in short time. I have several questions though regarding some of the code:

  1. Line 108. # camerax and cameray are where the middle of the camera view is. The way it works in the code below however it seems that camerax, cameray are the top left coordinates of the view and not the middle.

  2. Line 172. if (camerax + HALF_WINWIDTH) - playerCenterx > CAMERASLACK:

The way I understand the code by typing/running is that this condition seems to check whether the player is more pixels to the left of the center while the line 174 checks whether it is to the right. However in the text the opposite is stated. Which one is the correct interpretation?

3. Line 275. if 'rect' in sqObj and playerObj['rect'].colliderect(sqObj['rect']):

why is 'rect' in sqObj required in the if statement? Isn't it enough to call if playerObj['rect'].colliderect(sqObj['rect'])? Can't we just omit the 'rect' in sqObj? I am running it without it and it seems to work fine I just don't understand whether by omitting it there is a subtle loss.

Thank you in advance for your help.


r/inventwithpython • • Apr 07 '14

hackingtraces??

2 Upvotes

I can't seem to find http://invpy.com/hackingtraces

anyone any help?


r/inventwithpython • • Apr 04 '14

Having problems with the sort method

Thumbnail
gist.github.com
2 Upvotes

r/inventwithpython • • Apr 02 '14

pygame not working

2 Upvotes

I've installed python, but when I put "import pygame" into the IDLE, it gives me an error. Please help.


r/inventwithpython • • Mar 15 '14

Can I translate the book?

2 Upvotes

I want to translate the "Invent Your Own Computer Games With Python" book to Turkish. Can I do it? I mean, is the book copyrighted?


r/inventwithpython • • Feb 21 '14

I know Python 2.X.X programs can be turned into .exe files that other people can play, but can you also do that with Python 3.X.X?

2 Upvotes

I looked it up and it seemed like you couldn't, but it was slightly old information so I wanted to double check. I am currently learning from the book, but typing everything in Python 2.7.6 by changing a couple things around, but is that necessary? I want to be able to write programs good enough to be Greenlighted on Steam someday, and to do that I'll need to write in code that can be executed by any normal computer (i.e. without downloading python and pygame).


r/inventwithpython • • Aug 28 '13

Help: Install pygame on Mac 10.8.4?

2 Upvotes

I don't want to give up on the process... but after a few days of trying to get this to work I may need to find a mac with 10.6.xx... I really want to use pygame. Please can anyone help?


r/inventwithpython • • Jul 27 '13

Where can I download Pygame for Python 3.3? (Link to download page.)

Thumbnail bitbucket.org
2 Upvotes