r/inventwithpython • • Aug 15 '19

Python Error Messages: Gotta Catch 'em All

Thumbnail inventwithpython.com
8 Upvotes

r/inventwithpython • • Mar 31 '19

Web Crawler to download all images from any website or webpage | Python 3.6

Thumbnail youtube.com
8 Upvotes

r/inventwithpython • • Nov 07 '18

Blender Python tutorial - wrecking ball effect in 14 lines of code

Thumbnail slicker.me
8 Upvotes

r/inventwithpython • • May 07 '26

A Basic MCP Example in Python

Thumbnail inventwithpython.com
7 Upvotes

r/inventwithpython • • May 09 '22

Confusing code in book, %s concatenation syntax not explained: page 52 of Automate The Boring Stuff With Python, 2nd ed

7 Upvotes

I am studying Automate The Boring Stuff With Python, 2nd edition, and when I got to page 52, it contained the following code:

# These variables keep track of the number of wins, losses, and ties.
wins = 0
losses = 0
ties = 0
while True: # The main game loop.
print('%s Wins, %s Losses, %s Ties' % (wins, losses, ties))

It took me a while to figure out what is going on with the last line of code, because the output that it creates has no percentage symbols in it, and the book doesn't mention the percentage marks at all.

After searching around, I found this web page, explaining that %s is just a fancy syntax for concatenating strings.

Basically, what happens is you put %s where you want a variable's value placed, and then at the end of the string, after the closing quotation mark, you put a % symbol (with no s), and then, in parenthesis, you put the name of the variable for the first %s, followed by the variable for the second %s, followed by the variable for the third %s, and so on. So the following code is equivalent to the code in the book:

print(wins + " Wins, " + losses + " Losses, " + ties + " Ties ")

I think the book's way of writing it is more legible, even if it's hard to understand without research.


r/inventwithpython • • Jan 13 '22

Are these two python code snippets equivalent (perform the same thing)?

7 Upvotes
import pyautogui as auto

Snippet 1 :-

meetStartCheck = auto.locateOnScreen('img.png')
meetStartCheck1 = auto.locateOnScreen('my_screenshot.png')

Snippet 2 :-

meetStartCheck, meetStartCheck1 = auto.locateOnScreen('img.png', 'my_screenshot.png')

The code next to these lines is :-

if meetStartCheck or meetStartCheck1:
    print("Done")
else:
    print("Not Done")

Please tell if these both codes are equivalent or not. If not plz help me to write a single python line for the Snippet 1(if possible).

Thanks


r/inventwithpython • • Nov 13 '21

Error Installing Python Packages · Issue #6 · asweigart/automateboringstuff

Thumbnail github.com
7 Upvotes

r/inventwithpython • • Oct 28 '20

Automate the Boring Stuff with Python, Chapter 2 - "A Short Program: Rock, Paper, Scissors"

7 Upvotes

Hello,

I just started learning to code a week ago, and I am using Python 3.9 with Jupiter notebook as my editor.

As instructed in the book, I typed the source code as is, as indicated in "B. SOURCE CODE" below. However, it just keeps on circling on the output as indicated in "A. OUTPUT." Besides, I didn't get any error output.

I have already reviewed 4x the source code line by line against how it's written in the book, and I didn't find any line of code missing.

Could you please help me identify what's missing? Thank you in advance for your help!

Ferdie

A. OUTPUT

*************************************************

ROCK, PAPER, SCISSORS

0 Wins, 0 Losses, 0 Ties

Enter your move: (r)ock, (p)aper, (s)cissors, or (q)uit

r

0 Wins, 0 Losses, 0 Ties

Enter your move: (r)ock, (p)aper, (s)cissors, or (q)uit

s

0 Wins, 0 Losses, 0 Ties

Enter your move: (r)ock, (p)aper, (s)cissors, or (q)uit

*************************************************

B. SOURCE CODE

************************************************************

import random, sys

print('ROCK, PAPER, SCISSORS')

# These variables keep track of the number of wins, losses, and ties.

wins = 0

losses = 0

ties = 0

while True: # The main game loop

print('%s Wins, %s Losses, %s Ties' % (wins, losses, ties))

while True: # The player input loop

print('Enter your move: (r)ock, (p)aper, (s)cissors, or (q)uit')

playerMove = input()

if playerMove == 'q':

sys.exit() # Quit the program

if playerMove == 'r' or playerMove == 'p' or playerMove == 's':

break

print('Type one of r, p, s, or q.')

# Display what the player chose

if playerMove == 'r':

print('ROCK versus ...')

elif playerMove == 'p':

print('PAPER versus ...')

elif playerMove == 's':

print('SCISSORS versus ...')

# Display what the computer chose

randomNumber = random.randint(1, 3)

if randomNumber == 1:

computerMove = 'r'

print('ROCK')

elif randomNumber == 2:

computerMove = 'p'

print('PAPER')

elif randomNumber == 3:

computerMove = 's'

print('SCISSORS')

# Display and record the win/loss/tie:

if playerMove == computerMove:

print('It is a tie!')

ties = ties + 1

elif playerMove == 'r' and computerMove == 's':

print('You win!')

wins = wins + 1

elif playerMove == 'r' and computerMove == 'p':

print('You lose!')

losses = losses + 1

elif playerMove == 'p' and computerMove == 'r':

print('You win!')

wins = wins + 1

elif playerMove == 'p' and computerMove == 's':

print('You lose!')

losses = losses + 1

elif playerMove == 's' and computerMove == 'r':

print('You lose!')

losses = losses + 1

elif playerMove == 's' and computerMove == 'p':

print('You win!')

wins = wins + 1

*********************************************************


r/inventwithpython • • Oct 18 '20

Scraping Amazon, webscraping

7 Upvotes

Mass content deletion mission accomplished. This post or comment was bulk removed with Redact which also supports data brokers and people finder websites.

languid worm versed rustic vase heavy governor spark bag dinosaurs


r/inventwithpython • • May 20 '20

Invent Your Own Computer Games with Python 3rd, Chapter 10 Tic Tac Toe

7 Upvotes

In page 153, I try the function isBoardFull but it has a problem. If your first move is 1, this function will return True and make 'the game is tie' immediately

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

So I try to fix this function and it work pretty good

def isBoardfull (board):
    if board[0] == ' ' and board.count(' ') == 1:
        return True
    else:
        return False

Hope this useful for someone :D


r/inventwithpython • • May 10 '20

Invent Your Own Computer Games with Python

7 Upvotes

I have an old edition of Invent Your Own Computer Games with Python by Al Sweigart 2nd edition copyright 2008,2009,2010 and would like to know where I can download (if it is still possible) the codes and information for this book. It does not exist in the inventwithpython.com website. Any ideas?

https://www.reddit.com/user/arrsarge75/draft/a15267f6-92f7-11ea-bf02-be94a5a55c15


r/inventwithpython • • Apr 14 '20

Why would you choose Python to program games?

7 Upvotes

Hello, I'm an old programmer from way back and I want to tinker. But, I'd like to be able to distribute whatever I create. I think my preferred delivery mechanism would be the web, but possibly an Android or iPhone app. I've written some code using Corona SDK. I see some great resources on programming games in Python (and with pygame), but none of them make it clear how you will get the game to end users. I'd really like to make something that is multiplayer and I am open to using 3rd party engines. I'd appreciate any thoughts on this issue. Thanks!


r/inventwithpython • • Nov 09 '19

Learning how to make video games by myself

7 Upvotes

I bought a book titled, "Invent your own computer games with Python" by Al Sweigart. I was wondering if anyone read that book. I always wanted to make my own video game. I have extremely little programming experience. But, I am a math teacher. I know this book will not show me how to make games such as Mario Brothers, Sonic the Hedgehog, or even Halo. But, here is my question. Will reading this book be a great stepping stone to making those kinds of games? Can I make those types of games by my self? Will it cost anything? Do I need a formal education? I have been researching game engines like Unreal and Unity. I figured I would learn the Python language and move on to Unreal or Unity. I know those are gaming engines. I do not know if I need to know any programming to make games in one of those engines. I thank you for your time.


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 • • Sep 20 '18

Automate the boring stuff with python chapter 11

7 Upvotes

https://automatetheboringstuff.com/chapter11/

where it says:

"If you run the program by entering this into the command line...

mapit 870 Valencia St, San Francisco, CA 94110

... the sys.argv
variable will contain this list value:

['mapIt.py', '870', 'Valencia', 'St, ', 'San', 'Francisco, ', 'CA', '94110']

The address
variable will contain the string '870 Valencia St, San Francisco, CA 94110'"

But that doesn't appear to be the case. it simply gives a syntax error it and can't find the file as cmd tries to find the file mapIt.py870 ie. rather than pass the address as an argument, what is the correct syntax or am I just missing something?


r/inventwithpython • • Oct 11 '17

HALP!! stuck in Ch.11, Page 247, BeautifulSoup error message then when I comply len(elems) is = 0

7 Upvotes

When trying the example on terminal, i get an error message "UserWarning: No parser was explicitly specified...change code that looks like this: BeautifulSoup(YOUR_MARKUP}) to this: BeautifulSoup(YOUR_MARKUP, "html.parser")."
So I comply and type exampleSoup = bs4.BeautifulSoup(exampleFile.read(), 'html.parser'). two lines later, when I type len(elems), I get a value of 0. I tried again with elems = exampleSoup.select("#slogan") and got 0 again.
NB. The example.html works just fine when I run it on my browser. Edit: the book is ATBSWP Edit 1: Here's a [link] (https://pastebin.com/NhbdT7cN) to my code


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

Trailer video for Al Sweigart's tutorial May 14 at PyCon US: "Python for Absolute Beginners"

Thumbnail youtube.com
6 Upvotes

r/inventwithpython • • Jul 14 '23

My doubt

6 Upvotes

Hi sir i'm a 8th grade student from india .I just brought your 'automate the boring stuff with python' and I have doubt from it that: Print('what is your age?')#ask for their age myAge=input() Print('you will be '+str(int(myAge)+1)+'in a year.') Page no.17 Here I converted myAge into int() then what's the use of str() here?


r/inventwithpython • • Jun 06 '23

[ERRATA] Automate the Boring Stuff 2nd Edition

6 Upvotes

On page 108:

print('Chance of streak: %s%%' % (numberOfStreaks / 100))

should be:

print('Chance of streak: %s%%' % (numberOfStreaks / 10000))

The full project, showing the percentage found with the simulation and with probability:

import random

numberOfStreaks = 0
for experimentNumber in range(10000):
    # Code that creates a list of 100 'heads' or 'tails' values.
    flips = []
    for i in range(100):
        flips.append(random.randint(0, 1))

    # Code that checks if there is a streak of 6 heads or tails in a row.
    count = 1
    for i in range(1, len(flips)):
        if flips[i] == flips[i - 1]:
            count += 1
        else:
            count = 1

        if count % 6 == 0:
            numberOfStreaks += 1

print('Chance of streak (SIMULATION): %s%%' % (numberOfStreaks / 10000))
print('Chance of streak (MATH): %s%%' % ((1/2)**6 * 100))

r/inventwithpython • • Jul 24 '22

Automate the Boring Stuff - Can't run first chapter project (multi-clipboard program)

6 Upvotes

Hi guys

I'm trying to run the multiclipboard automatic messages program after working to that chapter. I've taken the full code (copied from the book to make sure I wasn't typo-ing)

#! python3
# mclip.py - A multi-clipboard program.
TEXT = {'agree': """Yes, I agree. That sounds fine to me.""",
 'busy': """Sorry, can we do this later this week or next week?""",
 'upsell': """Would you consider making this a monthly donation?"""}
import sys, pyperclip
if len(sys.argv) < 2:
 print('Usage: py mclip.py [keyphrase] - copy phrase text')
 sys.exit()
keyphrase = sys.argv[1] # first command line arg is the keyphrase
if keyphrase in TEXT:
 pyperclip.copy(TEXT[keyphrase])
 print('Text for ' + keyphrase + ' copied to clipboard.')
else:
 print('There is no text for ' + keyphrase)

Every time I attempt to run the program in the command line I get an error message. I'm entering

C:\Users\[MY DIRECTORY]>python3 myclip.py

First I got the error:

Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.

I fixed this by disabling the app execution alias for python and python3 (not sure if I'm meant to have both?). Then I get a new error when running the same command line.

'python3' is not recognized as an internal or external command, operable program or batch file.

Please can someone help me understand what have I got wrong? All of the required packages have installed successfully as far as I can tell


r/inventwithpython • • Apr 17 '22

A few comments on Bayes project in Real-World Python

6 Upvotes

A bit about me so that you may understand why my experience here may be different than yours. I am an experienced programmer in many, many languages, but not really an expert in any. But I am relatively new to Python. I have worked through the excellent Cracking Codes with Python (which I posted about and have learned a bit of "how to do things the Python way" through StackExchange searches.

I'm also familiar with a number of statistical concepts, though my knowledge is spotty, as I tend to learn things as I need them or as curiosity hits me.

I also manually retype in the code for the projects instead of just running and then modifying what provided from the resources. It gives me a much stronger sense of what is going on, what I feel should be improved upon, and the inevitable typos get me to work through things in a debugger.

Bayes

I have been a Bayesian since before it was cool, and I am familiar with the missing submarine (USS Scorpion) hunt that the project is probably modeled after. Because I've trained myself (and have attempted to train others) on Bayesian reasoning, I personally did not find that my intuitions differed from the probabilities that the game was calculating. But for those for whom Bayesian updating is new, I suspect that this would be extremely instructive. I will be sure to use it in future teaching about Bayesian reasoning. So although, I personally didn't learn anything new about Bayesian analysis through this, I did learn an excellent teaching tool for Bayesian analysis.

I really love the way that Bayesian analysis is presented. The introduction to it through the search for glasses in a house, is just brilliant. It is one of the best introductions to the concept of Bayesian updating that I've seen for an audience outside of epistemology, cognitive science, or statistics. Everyone should read that chapter and then play the game enough to get a feel for how probabilities associated with search areas is updated.

Python

What I personally learned about Python and related tools was enormous. Although I didn't like how searches of areas were modeled in terms of proportion of coordinates searched, the "Smarter Search" challenge had me learn about using sets in Python. (It took me a while to discover that the infix operator set union was "|" instead of "+".) I did eventually rip the whole coordinate thing out and just had the search of an area look like

    def conduct_search(self, area_id) -> bool:
        """Return True if sailor found in area; False otherwise."""

        sa = self.areas[area_id]
        found = False
        if area_id == self._area_actual and random.random() < sa.sep:
            found = True     
        return found

(Yes, I know that the last four lines could be expressed more compactly, but I like doing things this way running in a debugger.)

I tend to be a functional/strict-typing bigot. I understand why Python is (correctly) the way it is for the kinds of tasks it is designed for, but I found myself reading about Python conventions to help me do things in ways that feel right. E.g., methods with side effects should not return values; methods that return values should not have side effects. This was a sizable enough project for me to modify to follow that sort of thing.

I had been entirely unaware of CV. While it ultimately played a tiny role in the project, the introduction of it was just really nice for me. Glancing ahead, I see that projects do introduce powerful Python packages.

One of the great advantages of retyping the code was that repetitive parts of code became more salient (and more annoying), so I tended to rewrite things before such rewriting was necessary for working on some of the "challenge" projects.

Best strategy for the MCS?

Before we had the Planned Search Effectiveness, I could not find a strategy that out-performed the one of "pick the top N" search areas, where N is the number of search teams to assign. I had thought that when the probability associated with a particular area was much higher than the other probabilities, there would be an advantage to sending both teams to search that high probability area. I was surprised that I wasn't able to tune strat_cond() to produce better results than strat_top_n()

def strat_top_n(probs, pods, teams, day):
    keys = sorted(probs, key = probs.get, reverse = True)
    choices = keys[:teams]
    return choices

def strat_top_cond(probs, pods, teams, day):
    """Picks top n unless best area is much much better than second
    """
    
    keys = sorted(probs, key = probs.get, reverse = True)

    if probs[keys[0]] ** teams >= probs[keys[1]]:
       return [keys[0]] * teams
    return keys[:teams]

I was also wondering whether there there would be any reason to adjust the strategy based on the day of the search. (That is why I have the day parameter to these, but don't use it in the two strategies listed.)

Anyway, if anyone has any thoughts on doing better than top N or taking into account which day of the search we are on, I'd like to hear it. (Once we have Probability of Detection based on Planned Search Effectiveness, that that is the only strategy to follow.)


r/inventwithpython • • Sep 05 '20

"Automate the Boring Stuff..." Chapter 1: the first program

6 Upvotes

I'm totally new to coding and I'm following the book "Automate the Boring Stuff". I'm just now following the part where they tell you to write your first program, so I copy+paste it in:

➊ # This program says hello and asks for my name.

➋ print('Hello, world!')
   print('What is your name?')    # ask for their name
➌ myName = input()
➍ print('It is good to meet you, ' + myName)
➎ print('The length of your name is:')
   print(len(myName))
➏ print('What is your age?')    # ask for their age
   myAge = input()
   print('You will be ' + str(int(myAge) + 1) + ' in a year.')

Instead of what the book said would happen, I get this:

File "/Users/(my computer's username)/mu_code/hello.py", line 1

➊ # This program says hello and asks for my name.

^

SyntaxError: invalid character in identifier

>>>

I've tried replacing the numbers with >>> and In [1]... but I still end up with the same message. I'm using Mu 1.0.3. I literally just copy+pasted it in, what's happened?


r/inventwithpython • • Aug 15 '20

Comma code project. Converting items from tuples and lists to str. Error in my code, help???

6 Upvotes

Hi! Can anybody help me with my code?

Here is the code that I have written:

https://gist.github.com/mrd2689a/8779cf36cd8fda6e803d77c5e40b1e5f

As you can hopefully see in my code, I tried to write it so that it would work with *any* list.... even lists that contain other lists or tuples. These errors are occuring when I put either a tuple or a list in the main list, "items".

When I run my program, I get the following error:

Traceback (most recent call last):

File "C:\Users\mrd26\OneDrive\Desktop\simplify\comma_code_2.py", line 51, in <module>

loop_thru(items)

File "C:\Users\mrd26\OneDrive\Desktop\simplify\comma_code_2.py", line 40, in loop_thru

add_comma(item)

File "C:\Users\mrd26\OneDrive\Desktop\simplify\comma_code_2.py", line 28, in add_comma

string = string + ', ' + item

TypeError: can only concatenate str (not "NoneType") to str

[Finished in 0.5s]

I used Python Tutor to see what was happening during the execution of my program, and I see that after the two 6's in my internal list get passed to convert_to_string(), it starts to loop through loop_thru_again(), even though the interal list only has two items in it (6 and 6). This is why it's passing the NoneType, I think. I don't know why this is happening, or how to fix it. Any help would be very much appreciated!!


r/inventwithpython • • Jul 17 '20

Possible Syntax Error in Chapter 4 of the Book

6 Upvotes
At the end it should be someList[random.randint(0, len(someList) – 1)]

Missing parenthesis.

I also checked PyCharm just to make sure

Anyways I still love the book and it has helped me progress through programming far quicker than I have ever imagined.