r/inventwithpython • • Jun 13 '15

image window disappears

3 Upvotes

The following code creates a window on my screen, which disappears after about 1 second:

---code--

import pygame, sys

from pygame.locals import *

'''set up pygame'''

pygame.init()

'''set up the window'''

windowSurface = pygame.display.set_mode((500, 400), 0, 32)

pygame.display.set_caption('Hello world!')

--end code--

I've tried it with two setups with the same result: python2.7 and python3.4.

Before I put 3.4 on my system, python2.7, it ran with what I expect is the correct behavior, i.e., the image persisted until I killed python. After installing 3.4 and pygame for 3.4, the current problem emerged.

My OS is Debian Wheezy.

ALSO, is it possible to post to this forum using email?

FINALLY, i looked at the formatting help page and i can't find a way to set code blocks in the messages.

thanks in advance ;o)


r/inventwithpython • • Jun 08 '15

Application specific passwords with Gmail?

3 Upvotes

I am using Automate the Boring Stuff with Python. I am working on sending email from Chapter 16. It's asking for an application specific password when I try to login. The book says to check the resources at nostarch.com/automatestuff but I can't find any references that refer to that . How do I set up an application-specific passwords for my script so I can use gmail as my outgoing mail server.

Thanks for any help


r/inventwithpython • • May 21 '15

Question about variables "bo" and "le" in Tic-Tac-Toe (Invent Computer Games)

3 Upvotes

Hi. I love the book. I am finding it incredibly useful. I have a hard time knowing exactly when to call myself "Done" with a chapter, but I just try to study it and absorb the knowledge as best I can. Then I get frustrated. Then I leave for a few days and come back and tackle it with a clearer head.

I'm getting to the point where the code for Tic-Tac-Toe is starting to make sense to me, but there's one bit that really goes over my head and I think it might be crucial to my overall understanding of programming concepts.

Starting at line 53 in the book's source code, it has a block that looks like this:

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 

and so on, to check if the player has won.

The book says that we use "bo" and "le" as shorthand for the variables, so that we don't have to do as much typing. Because (bo, le) is in the parameters of the function, I believe the function will return the value of that big honking code block to the parameters bo and le. PLEASE jump in and correct me if I'm misunderstanding the way parameters work, or clarify further if that is correct, because I feel like functions and parameters are still going a little bit over my head and it's keeping me from comfortably going any further.

The question, in short, is once that value goes into the (bo, le) variables, how does that...affect the rest of the board? Or how is it affected by the rest of the board? I feel like every other function that changes the board or affects the flow of the game at all uses the variable "board." It's just this one function that uses "bo." So how does this function know whether the board is filled in, and how does the rest of the program know when this function returns true, if they're using different variable names?

Sorry if that got a little muddled. I'm relatively new and these concepts are still pretty slippery for me, so my post reflects my current sort of frazzled stream of consciousness.

Thanks in advance.


r/inventwithpython • • Mar 12 '15

Link in 3rd edition does not work.

3 Upvotes

r/inventwithpython • • Dec 20 '14

Just finished chapter 3. Made a few changes with what I learned. Is there a better way to do this?

3 Upvotes

So once I finished up chapter 3 I wanted to experiment a little to see how well I understood the material. I added an option for the user to say how many guesses they wanted and a count down of those guesses.

#guess numbers
import random

guessesTaken = 0

print ('Hey what is your name?')
myName = input()

number = random.randint(1, 200)
print ('Well, ' + myName + ', I am thinking of a number between 1 and 200. How many guesses do you need?')
guessesWantedInt = int(input())
while guessesTaken < guessesWantedInt:
    guessesWanted = guessesWantedInt - guessesTaken
    guessesLeft = str(guessesWanted)
    if guessesWanted > 1:
        print ('Take a guess. You have ' + guessesLeft + ' guesses left.' )
    else:
        print ('Take a guess. You have ' + guessesLeft + ' guess left.' )
        
    
    guess = input()
    guess = int(guess)

    guessesTaken = guessesTaken + 1

    if guess < number:
        print ('Your guess is too low.')
    if guess > number:
        print ('Your guess is too high.')
    if guess == number:
        break

if guess == number:
    guessesTaken = str(guessesTaken)
    print ('Good job ' + myName + '! You did guessed it in only '+ guessesTaken + ' guesses!')

if guess != number:
    number = str(number)
    print ('You are out of guesses. The number I was thinking of was ' + number)

I would really like pointers on how to make this cleaner if possible. I guess I will learn more as i go through the book too. Just thought I'd share a little bit as I go along.


r/inventwithpython • • Aug 16 '14

A code-cracking game I hacked together yesterday with ncurses.

3 Upvotes

https://www.github.com/cris1133/codeBreaker

(Designed for a 80x24 terminal, sorry, I really meant "hacked" together)

The basic idea of the game is hacking a 4 digit code.

You have a few tools to assist you in this, namely your bruteforcer and test window.

At the bottom-left window, you can set the ranges of your bruteforcer.

At the bottom-right window, you can enter numbers to test them out and scroll through your logs.

Green numbers have 4 bits in common with the code, red numbers do not.

Red numbers picked up by the Bruteforcer are auto-logged.

You will need a programmer's calculator to play this, one can be found on your computer's calculator by switching it to Programmer mode. Paper is also highly suggested!*


r/inventwithpython • • Mar 02 '14

Chapter 9 - Hangman

3 Upvotes

I'm going through and adding comments to the code so that I can make sure I understand every part of it before I move on.

this is the function that I'm having problems with specifically the for loop that replaces blanks with correctly guessed letters.

what does the i stand for in the line "for i in range(len(secretWord)):

I looked at the chapter multiple times and it eludes me.

Any help would be appreciated.

def displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord): #this function displays the game board to the player. len(missedLetters) will look at the length of the #missedLetters variable and add it as an element so the interpreter knows which picture to display to the player #from HANGMANPICS. HANGMANPICS is all caps because it is a constant variable, which does not change. #the for loop prints a _ for every letter in the secret word chosen in the function getRandomWord (line 66) with a #space between them. #the blanks variable makes _ the length of the word chosen for the variable secretWord #the next for loop will go through each letter in secretWord and replace the _ with the actual guessed letter. print (HANGMANPICS[len(missedLetters)]) print ()

print('Missed letters:', end=' ')
for letter in missedLetters:
    print(letter, end=' ')
print ()

blanks = '_' * len(secretWord)

for i in range(len(secretWord)):  #replaces blanks with correctly guessed letters

    if secretWord[i] in correctLetters:
        blanks = blanks[:i] + secretWord[i] + blanks[i+1:]

for letter in blanks: #show the secret word with spaces in between each letter.
    print(letter, end=' ')
print()

r/inventwithpython • • Aug 24 '13

Is there a way to get pygame to work with python 3 on a Mac?

3 Upvotes

I've been doing just fine using python 2.7 but I'm curious if there's a way to use python 3. All solutions seem to be Windows only, from what I can find.


r/inventwithpython • • May 10 '13

RSA help

3 Upvotes

Can anyone give me some guidance as to how to leverage the code in the RSA program to decode the message given below? The problem is from the picoCTF competition that finished earlier this week.

Thanks in advance!

p = 9648423029010515676590551740010426534945737639235739800643989352039852507298491399561035009163427050370107570733633350911691280297777160200625281665378483

q = 11874843837980297032092405848653656852760910154543380907650040190704283358909208578251063047732443992230647903887510065547947313543299303261986053486569407

e = 65537

c = 83208298995174604174773590298203639360540024871256126892889661345742403314929861939100492666605647316646576486526217457006376842280869728581726746401583705899941768214138742259689334840735633553053887641847651173776251820293087212885670180367406807406765923638973161375817392737747832762751690104423869019034

Use RSA to find the secret message


r/inventwithpython • • May 09 '13

When importing Pygame, I get "ImportError: DLL load failed: The specified module could not be found."

3 Upvotes

This is caused by using Pygame with a 64-bit version of Python. Currently Pygame only works on 32-bit versions of Python.


r/inventwithpython • • Apr 29 '25

Program Robots in Minecraft links dead

2 Upvotes

On this page: https://inventwithpython.com/#minecraft The links to the book are dead: https://turtleappstore.com/book/

Bummer, I was going to send information about it to some kids


r/inventwithpython • • Jun 10 '24

How is everyone? I just started reading Invent Your Own Computer Games with Python, 4th Edition.

2 Upvotes

(This photo is not me irl btw, found it when i googled "waving picture")
Anyways, just me saying hello to the community, i doubt anyone is gonna care anyways. :D


r/inventwithpython • • Feb 03 '23

Having Issues with selenium

Post image
2 Upvotes

r/inventwithpython • • Oct 29 '22

problem with indentation, python 3

Thumbnail self.learnpython
2 Upvotes

r/inventwithpython • • Oct 07 '22

Invent with python book hw, unexpected character error

Thumbnail self.learnprogramming
2 Upvotes

r/inventwithpython • • Jun 04 '22

How do I install the Debugger on Python 3.10.4?

2 Upvotes

I'm on Chapter 7 of Using the Debugger on Invent with Python but I don't have the debug option on my Idle Shell 3.10.4. How do I fix this? Newbie here.


r/inventwithpython • • Apr 16 '22

Pyzmail

2 Upvotes

Hi all,

It seems Pyzmail won't install beyond python 3.6? Any suggestions around this. It would be nice to be able to do the book on the latest version of python


r/inventwithpython • • Apr 12 '22

Eagl and Tails (task experiments in monet, page in book 161, name book Automating routine tasks with Python: A practical guide for beginners)

2 Upvotes

Здравствуйте, у меня есть вопрос, конкретно в этом: правильно я понял задачу и выполнил её?
I have a question about the task (task name in the table of contents of the post), specifically in this one: did I understand and complete it correctly?

import random, numpy, re
chetone = 0
chetzero = 0
numberOfStreaks = 0
for experimentNumber in range(10000):
    # create lists range of 100 values 0 and 1
    spisok = numpy.random.randint(0, 2, 100)    
    # Code verify availability 6 series Eagle and Tails
    sc = " ".join(map(str, spisok))
    regexone = re.search("1 1 1 1 1 1", sc)
    regexzero = re.search("0 0 0 0 0 0", sc)
    if regexone:
        chetone = chetone + 1
    elif regexzero:
        chetzero = chetzero + 1
    else:
        numberOfStreaks = numberOfStreaks + 1
print('Procent serries: %s%%' % (100 - (numberOfStreaks // 100)))
print(chetone, '\n' + str(chetzero))

r/inventwithpython • • Aug 08 '21

Need help with loop

2 Upvotes

r/inventwithpython • • Sep 15 '20

HELP The noob is here AGAIN

2 Upvotes

Hi people today I'm trying to do a program where you can add names to a list or something like this, so I'm starting and I have a problem with the if idk why so if someone can explain me and help I would be happy.

Yes I'm trying to do a calendar

Agenda = ['Juan', 'Alvaro', 'Lucia']
elem = Agenda
print ('Los contactos actuales que hay son: ')
for elem in Agenda:
print ('- ' + elem)
res = input('¿Deseas añadir algun contacto a la lista?')
if res == ('si') or ('Si'):
print('¿Que contacto desea añadir?')
else:

print('¿Esta seguro de que no quiere añadir ningun contacto?')

The problem is the if idk why else is not doing anything and always if is printed I mean if I write asdas in the input of the 9th line then the if of the 11th line is executed as well and the else doesn't do anything.

See you thanks ma boooys.


r/inventwithpython • • Aug 08 '20

Feedback please -- auto-generate new python file, new batch file, and open in editor, ready to go...

Thumbnail self.learnprogramming
2 Upvotes

r/inventwithpython • • Jul 15 '20

Need Help with Selenium and Stale Elements - No Longer Attached to DOM

2 Upvotes

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 refreshed

Why 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 element

From 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 • • Jul 01 '20

Multiclipboard project from Automate is not working

2 Upvotes
#! 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 • • Jun 12 '20

Importing openpyxl

2 Upvotes

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!