r/inventwithpython • • Dec 02 '19

"Automate the Boring Stuff" Udemy course is free to sign up for the next 72 hours: DEC2019FREE

55 Upvotes

You can use this code to sign up for the Udemy "Automate the Boring Stuff with Python" course for free:

https://www.udemy.com/course/automate/?couponCode=DEC2019FREE

(If DEC2019FREE doesn't work, try it again in a few minutes.)

During the month of December, you can also use DEC2019 to sign up for $14 instead of the usual $50: https://www.udemy.com/course/automate/?couponCode=DEC2019

(Due to the way Udemy now does promotions, I'm limited in how many discount codes I can make each month, so there's no way for me to make more after the 72 hour period, which ends roughly Wednesday night 7pm Pacific time.)


r/inventwithpython • • Feb 03 '20

Chapter 8 error module 're' has no attribute 'Pattern'

3 Upvotes

Hi,
I'm working my way through Automate the boring stuff and when trying the allowRegexes and blockRegexes parameters in the input validation sections I get the following error;

Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license()" for more information.
>>> import pyinputplus as pyip
>>> import re
>>> response = pyip.inputNum(allowRegexes=[r'(I|V|X|L|C|D|M)+',r'zero'])
X
module 're' has no attribute 'Pattern'

Is this an issue with the version of python?
Thanks in advance!


r/inventwithpython • • Feb 02 '20

[automate]Chapter 8, revised, make your own multiplication Quiz, can't do timeout

4 Upvotes

Trying to take on the challenge of doing a multiplication quiz without using PyInputPlus.

Have done everything except the 8 second timeout. I've looked all over the Interwebz for a way to do it, but just can't wrap my brain around it. I managed to do the 1 second pause with the correct answer.

Any hints? Here's my code so far:

#mymultiplicationquiz
#tries to recreate a multiplication quiz WITHOUT PyInputPlus

import random, time

number_Questions = 10
answer = 0
i = 0

for questionNumber in range(1, (number_Questions + 1)):
    num1 = random.randint(0,9)
    num2 = random.randint(0,9)
    prompt = '#%s: %s x %s = ' %(questionNumber, num1, num2)
    print(prompt)
    for i in range(1,4):
        answer=input()
        if answer==str((num1*num2)):
            print('good')
            time.sleep(1)
            break
        print('incorrect')

r/inventwithpython • • Aug 19 '16

[Automate] TypeError: must be str, not list for birthdays example

2 Upvotes

I'm trying to execute an example from the ATBS book and it's not working in Python 3.6. I've tried Googling but haven't got far at all.

I would type in "Alice" the key in the dictionary and I would get an error, see below for code + error.

Code:

birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}

print(birthdays)

while True:

print('Enter a name: (blank to quit)')

name = input()

if name == '':

    break


if name in birthdays:

     print(birthdays[name] + ' is the birthday of ' + [name])

else:

    print('I do not have that in our records')

    print('What is their birthday?')

    bday = input()

    birthdays[name] = bday

    print('Birthday database updated.')

Error:

Traceback (most recent call last): File "C:/Users/seyi/AppData/Local/Programs/Python/Python36/Scripts/Ch5 dictionaries.py", line 10, in <module> print(birthdays[name] + ' is the birthday of ' + [name]) TypeError: must be str, not list

Any assistance would be helpful


r/inventwithpython • • Dec 02 '19

Beginners double installing pip3 requirements.txt and single modules for Mu Editor

1 Upvotes

Hey there,

Just starting the 2nd Edition and right after starting the 1st Edition so switching from IDLE to Mu Editor. I attempted installing the 'automate-mac-requirements.txt' to the Mu Editior via the command line but it keeps failing.

The command I am using is: pip3 install --user –r automate-mac-requirements.txt --user - just as mentioned in the ebook but I am receiving the error: ERROR: Invalid requirement: '–r'

Alternatively, I tried installing just one module to the Mu Editor instead using this code: pip3 install --user -U send2trash==1.5.0 --target /Applications/mu-editor.app/Contents/Resources/app_packages .... but instead get this long error below:

Using cached https://files.pythonhosted.org/packages/49/46/c3dc27481d1cc57b9385aff41c474ceb7714f7935b1247194adae45db714/Send2Trash-1.5.0-py3-none-any.whl

Installing collected packages: send2trash

ERROR: Exception:

Traceback (most recent call last):

File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/cli/base_command.py", line 153, in _main

status = self.run(options, args)

File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/commands/install.py", line 446, in run

installed = install_given_reqs(

File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/req/__init__.py", line 58, in install_given_reqs

requirement.install(

File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/req/req_install.py", line 858, in install

self.move_wheel_files(

File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/req/req_install.py", line 487, in move_wheel_files

wheel.move_wheel_files(

File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/wheel.py", line 353, in move_wheel_files

scheme = distutils_scheme(

File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/locations.py", line 125, in distutils_scheme

i.finalize_options()

File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/distutils/command/install.py", line 252, in finalize_options

raise DistutilsOptionError("can't combine user with prefix, "

distutils.errors.DistutilsOptionError: can't combine user with prefix, exec_prefix/home, or install_(plat)base

Can anyone provide me an explanation as to what I am doing incorrectly? Much appreciated.


r/inventwithpython • • Aug 17 '16

my solution to Ch 4 practice comma code

2 Upvotes

Sharing this as I googled/reddited other answers with for loops built into them and couldn't wrap my head around that approach, and found an alternative way. I probably used too many variables but it was just easier to break it down that way for me.

import copy

spam = ['buttmonkeys','dsfdsfs','dsfsfsdfsfdfdsf','gggggg','dddddd','fff','ttt','123','789']

def thefunction(anylist):
	length=len(anylist)
	anylist.insert(length-1, 'and ') 
	lastitem= copy.copy(anylist[-1]) 
	stringedlist= ', '.join(anylist[:-1]) 
	lastlist= str(stringedlist)+str(lastitem)
	print(lastlist)
	
thefunction(spam)

Any helpful feedback is welcome.


r/inventwithpython • • Feb 22 '19

No Starch Press giveaway! Comment on the /r/nostarchpress post to get a chance to win your favorite NSP title.

Thumbnail
reddit.com
7 Upvotes

r/inventwithpython • • May 08 '19

Cracking Codes with Python

3 Upvotes

When i Answered Chapter one Practice questions , i found that my answer different from the answers on https://nostarch.com/crackingcodesanswers, i am sure that i answered them right, could anyone has read the book find the same ?


r/inventwithpython • • Aug 18 '16

CH 3 The Collatz Sequence

2 Upvotes

Here is what I came up with, It's the first "program" I've written from scratch. The exception handling doesn't work. I'm thinking it needs to be moved but not sure where to. Let me know what you guys think and what i can do to improve.

The Collatz Sequence

def collatz(number): if number % 2 == 0: #even number return number // 2

elif number % 2 == 1:    #odd number
    return 3 * number + 1

try: number = input("Please input an integer.") while number !=1: number = collatz(int(number))
print(number)
except ValueError: print("This program accepts integers only! Plese input an integer")


r/inventwithpython • • Aug 27 '13

How to ensure errors are removed as script doesn't work.

1 Upvotes

I was doing Dragon realm and typed it into idle. I ran it and it didn't work, no errors it just produce no output and went back to prompt. I saved the file as another name.

So I used the diff tool. And edited the original file to be the same and it worked. Mind you it only had an extra space in 2 lines.

So I took the original file and ran it through a pep8 checker and fixed the errors until it passed pep8. I ran the file it failed as it originally did.

My concern is if I didn't have the authors script and I was running my own script with this error how would I ever figure out the error. If pep8 passed then I would probably think I had a code error.

Is there a way to ensure a file is 100% ok?


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 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 • • 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 • • May 26 '15

(ATBSWP Ch. 6) I completed the Practice Project, but I have a question about a for loop I made.

4 Upvotes

I finished Chapter 6's Practice Project, which asks you to 'Write a function named printTable() that takes a list of lists of strings and displays it in a well-organized table with each column right-justified.'. Here is how I made it. The function takes the tableData list of lists and prints an ordered version of the items and, just for testing reasons, the colWidths list, and it looks like this:

    apples Alice  dogs
  oranges   Bob  cats
 cherries Carol moose
   banana David goose
[9, 6, 6]

While the code works, the version I had made before it didn't work correctly. It was the same, except in the if colWidths[a] <= len(table[a][b]): I had written if colWidths[a] < len(table[a][b]):, and it printed this:

   apples Alice dogs
  oranges   Bob cats
 cherries Carolmoose
   banana Davidgoose
[9, 6, 5]

My question is: Why is the outcome different? Why does the colWidths[a] = len(table[a][b]) + 1 only adds one if the if statement is has the <= comparison operator and not with <?

I am sorry if my question wasn't clear enough, it's my first one. Thanks in advance.


r/inventwithpython • • May 25 '15

Confused on “TRUTHY” AND “FALSEY” Values, Chap 2

3 Upvotes

Tried Googling this, nothing comes up. The part I don't get is "while not name", specifically why the 'not' boolean operator is there and what it's telling the computer to do?

name = ''
while not name:
	print('Enter your name:')
	name = input()
print('How many guests will you have?')
numOfGuests = int(input())
if numOfGuests != 0:
	print('Be sure to have enough room for all your guests')
print('Done')	

r/inventwithpython • • May 20 '15

Automate the Boring Stuff Chapter 4 Practice Project - What is the most efficient way to code it?

7 Upvotes

So far, I managed to complete all practice projects in Automate The Boring Stuff. But in chapter 4, I think my solution is not very "elegant", as it envolves deleting the list items (even though I could simply deep copy it). It is also the only solution I've found until now.

Could anyone provide some feedback on the code or the most efficient solution to this problem? Thanks!

My Solution

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][0], end='')
		del grid[i][0]
	print()

For Reference, here's what's asked in the Practice Project:

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


r/inventwithpython • • Jan 08 '17

Python newb question.

4 Upvotes

Alright so I decided to try python as the first language to learn. I'm very excited as I've tried to learn c++ and lost motivation really quickly. I'm hoping python will help me get the bigger picture without worrying about syntax issues. Anyway so I'm running an old 2011 MacBook Pro (unfortunately) and have Windows 10 partioned 50/50. I've tried to start using python in both operating systems but can't seem to get either to work. In Windows I can't get past the path variable error (already did path;python3.6 location) and in mac using 2.7 and I can't get scripts I write to run in terminal (keeps popping up syntax errors). I'm using bracket by adobe as a substitute for notepad++. Preferably I'd like to run it on windows however getting it running on either operating system would be awesome at this point.


r/inventwithpython • • Jul 21 '16

Chapter 10 - Found a way to get rid of 4 lines in getComputerMove(board, computerLetter) - what do you think?

2 Upvotes

Creating the Computer’s Artificial Intelligence

96. def getComputerMove(board, computerLetter): (LINE 96) 97. # Given a board and the computer's letter, determine where to move and return that move.(LINE 97) 98. if computerLetter == 'X': (LINE 98) 99. playerLetter = 'O' (LINE 99) 100. else: (LINE 100) 101. playerLetter = 'X' (LINE 101)

I deleted these lines and instead of it added to a line 96 def getComputerMove(board, computerLetter): an argument "playerLetter" and to a line 171 move = getComputerMove(theBoard, computerLetter)
an argument "playerLetter".

It seems to work pretty well, what are your thoughts?


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

I cant find the link on the website to download python

1 Upvotes

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 • • 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 • • Jan 17 '17

newb pygame makers question

2 Upvotes

i'm trying to make movement in pygame. I want my charcter to move the whole time ,but i'm not sure how to do it. My friends said to keep loop the different sprites, but i'm not sure how to do it.


r/inventwithpython • • Jul 23 '16

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

Post image
1 Upvotes

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?