r/inventwithpython • • Jul 23 '16

My debugger, won't run so I can't find whats wrong. [Pygame]

Post image
1 Upvotes

r/inventwithpython • • Jul 21 '16

[Automate] Why does this work? Nested Loop for Table Printer

1 Upvotes

Hi all, complete beginner here, I'm doing the Practice Project for the String Manipulation chapter, where I am supposed to print out a table-ish view from a nested list of items. So, I managed to perform the printout as required using the code below, but I have a question.

In the second part of my printTable function, the 'for j in range(len(info[i])' comes before the 'for i in range' yet the code can be executed? Is it because the i has been iterated in the first part of the function? Or is Python able to understand the purpose of the i even though it comes later?

P/S: Sorry if this sounds confusing, I'm not very articulate with words.


tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'elephant']]

def printTable(info):
	colWidths = [0] * len(info)
	for i in range(len(info)):                  # Calculate max length per category
		for j in range(len(info[i])):
			if len(info[i][j]) > colWidths[i]:
				colWidths[i] = len(info[i][j])
	for j in range(len(info[i])):
		for i in range(len(info)):
			print(info[i][j].rjust(colWidths[i] + 2, ' '), end='')
		print('')
			
printTable(tableData)

r/inventwithpython • • Jul 19 '16

Chapter 9.5 - a mistake? (Accessing items from dictionaries)

1 Upvotes

spam = {'hello':'Hello there, how are you?', 4:'bacon', 'eggs':9999} spam[eggs] 9999

This is what the original source code says, but in the Idle I get an error: Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> spam[eggs] NameError: name 'eggs' is not defined

=========================================== To solve this problem I wrote spam['eggs'] in shell with single quotes and get the right output.

Am I missing something?


r/inventwithpython • • Jul 19 '16

Chapter 9 HANGMAN - displaying the correct answer in blanks

1 Upvotes

I have copied the original source code, but when I enter a last letter and get the message that I have won, the blank that should have been replaced with the last correct letter remains unchanged.

To solve this I decided to write a line : print(HANGMANPICS, missedLetters, correctLetters, secretWord) after line 127. Now, when I enter the last correct letter all blanks will be replaced with the correct word.

Did I make a mistake copying an orginal code or it has been done on purpose?


r/inventwithpython • • Jul 18 '16

This is driving me crazy (collatz sequence)

1 Upvotes

I'm going through automate the boring stuff learning Python and I'm having a lot of fun.

I'm an overthinker and I'm taking my time to understand all of the elements before I move forward. I just did the collatz sequence. After looking at the answer, cross referencing going back and forth a few times I got it working.

But, this is bothering me. Here is the stack overflow answer. http://m.imgur.com/kW4jP1V

It is correct and works for me.

But what is going on here.

n = input("Give me a number: ") while n != 1: n = collatz(int(n))

How is n = collatz(int(n)) valid?

n is a variable but then it calls a function and passes the argument of n, this is referencing itself right?

Does this mean that n exists in multiple places and that it is handled by Python and we never see it?

I assume that n1 = (collatz(n2)) where n2 is passed to the function and passed back to n1 when the function is complete.


r/inventwithpython • • Jul 16 '16

[Pygame] Unable to open .ogg files?

1 Upvotes

When running simulate.py, I get an error saying that pygame was unable to open "beep1.ogg". I am on OSX El Capitan, which seems to have a lot of issues with pygame. I have heard people say that it is because the file is too large. In that case, can someone teach me how to shorten the sound file? After listening to it, it seems that the beep is quite short, and is followed by over a second of nothing.

Thanks!


r/inventwithpython • • Jun 13 '16

[Chapter 2]Cant find file

1 Upvotes

On invent your own computer game with Python page 15 it says "IDLE has another part called file editor. lick on the file menu at the top of the interactive shell window." I cannot find file on the top of the window all it says when you open it up is "Python 3.5.1.... on win32"


r/inventwithpython • • May 30 '16

Can someone walk me through this problem on chapter 4, I'm stuck.

1 Upvotes

I have spent 2 days on this one problem, and it's driving me insane!

Character Picture Grid Say you have a list of lists where each value in the inner lists is a one-character string, like this:

grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] You can think of grid[x][y] as being the character at the x- and y-coordinates of a “picture” drawn with text characters. The (0, 0) origin will be in the upper-left corner, the x-coordinates increase going right, and the y-coordinates increase going down. Copy the previous grid value, and write code that uses it to print the image.

..OO.OO.. .OOOOOOO. .OOOOOOO. ..OOOOO.. ...OOO... ....O.... Hint: You will need to use a loop in a loop in order to print grid[0][0], then grid[1][0], then grid[2][0], and so on, up to grid[8][0]. This will finish the first row, so then print a newline. Then your program should print grid[0][1], then grid[1][1], then grid[2][1], and so on. The last thing your program will print is grid[8][5]. Also, remember to pass the end keyword argument to print() if you don’t want a newline printed automatically after each print() call.

How exactly can you have a loop, in a loop?


r/inventwithpython • • May 08 '16

Think I am going crazy - where can I download python (Chapter 1)

1 Upvotes

It references a 'website':

On Mac OS X, download the .dmg file that’s right for your version of OS X from the website and double-click it. Follow the instructions the installer displays on the screen to install Python, as listed here:

I cannot find a link to this website at all :( Am I going crazy, missing some inside joke or what? I have komodo IDE installed atm- is that any good?


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 ~


r/inventwithpython • • Apr 30 '16

Chapter 16 sending email. How do you locate the SMTP server domain name for hostgator webmail?

1 Upvotes

I'm at Chapter 16 and I'm trying to send emails through python. I tried it with my gmail account and it works. However, I wish to send emails from my webmail that has my domain name in it.

My web host is hostgator.

I tried to set smtpObj as such (i've replaced my domain name as 'mydomainname' for privacy issue):

smtpObj = smtplib.SMTP('smtp.mydomainname.com', 587)

but it gave me an error:

Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> smtpObj = smtplib.SMTP('smtp.mydomainname.com', 587) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 251, in init (code, msg) = self.connect(host, port) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 335, in connect self.sock = self._get_socket(host, port, self.timeout) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/smtplib.py", line 306, in _get_socket self.source_address) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/socket.py", line 693, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/socket.py", line 732, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 8] nodename nor servname provided, or not known

I tried going on hostgator to find out but to no avail :(


r/inventwithpython • • Apr 05 '16

Ch.3 Collatz Function

1 Upvotes

I am having a little trouble with global variables. What I am trying to do is let the user know the number of operations performed before the number 1 was achieved. Is it possible to pull out a local variable of n to the global space, and if so how?

print("This is console module")
def collatz(number):
    global n
    while number != 1:
        if number%2 == 0:
            number = number//2
            n = n+1
        else: 
            number = 3*number+1
            n = n+1
print('Input a number')
number = int(input())
print('It took ' + str(n) + ' operations to achieve your number = 1')

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 • • 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 • • Jan 27 '16

Trouble installing Pyautogui

1 Upvotes

Hey everyone,

I've been struggling to install pyautogui for quite some time. My environment is OSX 10.9.5 and my pip3 version is 7.1.2. Using python 3.5

Anyways I've tried

sudo pip3 install pyautogui, 
sudo pip3 install --upgrade pypautogui

It seems like I am missing Quartz, though when I try to install it i get: Could not find a version that satisfies the requirement Quartz (from versions: ) No matching distribution found for Quartz

When I try to installl pyautogui I get:

Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-build-0skmo2kq/pyautogui

Any help is greatly appreciated!


r/inventwithpython • • Jan 22 '16

Automate the Boring Stuff with Python - Chapter 10 - Logging won't print

1 Upvotes

I'm currently teaching myself Python in my spare time using Automate the Boring Stuff with Python. I've been working through chapter 10 which deals with debugging and I am having trouble with one of the examples. I'm unable to get Python to print the strings found in logging.debug(), so all I'm outputting is the final result which is 0 in this case. The code that I have been trying to replicate is:

import logging

logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
logging.debug('Start of program')

def factorial(n):
    logging.debug('Start of factorial(%s%%)' %(n))
    total = 1

    for i in range(n + 1):
        total *= i
        logging.debug('i is ' + str(i) + ', total is ' + str(total))

    logging.debug('End of factorial(%s%%)' % (n))

    return total

print(factorial(5))
logging.debug('End of Program')  

r/inventwithpython • • Jan 19 '16

Nested For Loop Confusion

1 Upvotes

For some reason, I can't figure out what's actually going on inside a nested for loop. For example, the practice question in Chapter 4 (also referenced here).

grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']]

for j in range(len(grid[0])):
    for i in range(0, len(grid)):
        print(grid[i][j], end='')
    print()

If there's anything out there that can explain what is kind of going on in this code, it would be super helpful.


r/inventwithpython • • Jan 08 '16

I cant find the link on the website to download python

1 Upvotes

r/inventwithpython • • Dec 21 '15

Ch3: Memory Game - How do I use my own images?

1 Upvotes

I am new to python and coding in general... so I'm havinga bit of trouble.

I understand the code in this chapter but I want to change it to incorporate my own .pngs rather than simple shapes. This seems to not like interacting with colours...

Effectively I want the colours to not just be rgb values but code that alters the pngs to be a different hue? How would I go about doing this? is it possible?

Sorry for rambling, hope this makes even a bit of sense... Any help is much appreciated.


r/inventwithpython • • Dec 03 '15

Quick question about strip method from chapter 6 of Automate the Boring Stuff

1 Upvotes

If you are stripping any occurence of a,m,p, and S from the end of strings stored in the spam variable (which is 'SpamSpamBaconSpamEggsSpamSpam'), how is there still one Spam left in the output of that method/function?


r/inventwithpython • • Dec 01 '15

Regex project in 'Automate the Boring Stuff'

1 Upvotes

On page 189 of 'Automate the Boring Stuff', there's a list of 'Ideas for Similar Programs'.

I've completed them all except this one:

Find common typos such as multiple spaces between words, accidentally accidentally repeated words, or multiple exclamation marks at the end of sentences. Those are annoying!!

I've worked out how to detect multiple spaces and exclamation marks, but I'm struggling with repeated words.

When I did a google search, I found this within the Python 3.5 documentation:

The regular expression for finding doubled words, (\b\w+)\s+\1 can also be written as (?P<word>\b\w+)\s+(?P=word)

Are these the only ways to find duplicate words?

The reason I ask is that \b isn't mentioned in the chapter, and I assumed that the task could be completed solely using the symbols covered in the preceding pages.


r/inventwithpython • • Nov 26 '15

Can you make Tic Tac Toe 2 players?

1 Upvotes

Can somebody help me! I need help with this as it is a class challenge! Can somebody please paste the code as an answer. I will be grateful! Can you also please explain the code to help me out (you don't need to do this but it will be helpful). I've been trying for three hours.


r/inventwithpython • • Nov 20 '15

How do you use pip to import modules? I'm totally confused.

1 Upvotes

I've read appendix A, I'm not sure how to use the windows command prompt (cmd?) to use pip. Could someone give me an idiot-friendly guide to installing modules


r/inventwithpython • • Oct 24 '15

Automate The Boring Stuff, Chapter 12: get_active_sheet does not work.

1 Upvotes

In Chapter 12 from Automate the Boring Stuff, in excersise 'Getting sheets from the workbook', when I call wb.get_active_sheet() I get the following error:

/usr/lib/python3.5/site-packages/openpyxl/workbook/workbook.py:102: UserWarning: Call to deprecated function or class get_active_sheet (Use the .active property). def get_active_sheet(self):

I understand that I have to write a function calling the .active property. But I don't know how to do that. I tried looking in the openpyxl documentation, but there is no information on the new method. Can anyone tell me how to get the active sheet in an Excel file? Thank you in advance.


r/inventwithpython • • Oct 11 '15

Interesting outcome of str(number) in random number generation game

1 Upvotes

Hi! I just started to make my way through the Invent with Python book and I came across something interesting. I decided I wanted to just add a little extra line to Chapter 4's game in the win/lose condition flow control statements. So, if you win it says "Well done! I was thinking of number [x]! You got it in just [y] guesses!" and if you lose it says "Aww, too bad! The number I was thinking of was [y]"

if guess == number:
    guessesTaken = str(guessesTaken)
    print('Well done! I was thinking of the number ' + str(number) + '! You got it in just ' + guessesTaken + ' guesses!')

if guess != number:
    number = str(number)
    print('Aww, too bad! The number I was thinking of was ' + number)

The code above works. However, when I first tried this I entered:

if guess == number:
    guessesTaken = str(guessesTaken)
    number = str(number)
    print('Well done! I was thinking of the number ' + number + '! You got it in just ' + guessesTaken + ' guesses!')

if guess != number:
    number = str(number)
    print('Aww, too bad! The number I was thinking of was ' + number)

This, resulted in it playing both outputs (win and lose) when you won.

I was wondering if someone could explain to me why this would be the case? Is the doubling up of number = str(number) just confusing Python interpreter? Or, is there a programming reason why it's not skipping the second block?

Sorry for the long first post and thank you :)

edited to apply proper formatting for code