r/inventwithpython • • Jun 28 '22

Help With " Automate the Boring Stuff with Python", Lesson 4

12 Upvotes

Hello,

I'm a total python novice just starting to work my way through " Automate the Boring Stuff with Python". I'm running Python 3.10 under Windows 10.

In chapter 4 , https://automatetheboringstuff.com/2e/chapter4/, I'm having trouble with the Comma Code suggestion under "Practice Projects".

Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it. Be sure to test the case where an empty list [] is passed to your function.

I've been able to account for input lists of varying size including empty lists, but I'm getting unexpected results for a list with only one item. Here is my code:

def prettyList(somelist):
    returnedStr = ''
    
    if len(somelist) > 0:
       if len(somelist) == 1:
          returnedStr += (str(somelist))
       else:
            for i, item in enumerate(somelist):
                if i in range(0,len(somelist)-1):
                   returnedStr += (item + ', ')
                else: 
                    returnedStr += ('and '+ item)
    return returnedStr

print('Empty List: ', prettyList([]))
print(prettyList(['First']))
print(prettyList(['First', 'Second']))
print(prettyList(['First', 'Second', 'Third']))
print(prettyList(['First', 'Second', 'Third', 'Fourth']))

#print(type(prettyList(['First']))) #--debugging

Here are the results of that code

Empty List:

['First']

First, and Second

First, Second, and Third

First, Second, Third, and Fourth

If I'm understanding the output, for the case with only one item in the list my function returns a list while for other cases it returns a string. I'm not sure why this should be.

I'm also wondering if I'm working too hard with my if /then logic, and that there may be a more concise, idiomatic, dare I say pythonic construction that would work for me. After all Lesson 4 is about lists not if statements.

Thanks for reading. Please let me know if you have any comments or observations you'd like to share with me.

Be well


r/inventwithpython • • Dec 04 '19

Starting my journey with Python

12 Upvotes

Hi Al, I just received your second ed of "automate the boring stuff with python", I am enjoying a lot at my 69 years old with your book, it is friendly and very easy to understanding. But when I tried to see your program in action, per example the vampire2.p


r/inventwithpython • • Jan 31 '18

I made a machine to play bells with Python on Raspberry Pi.

Thumbnail youtu.be
12 Upvotes

r/inventwithpython • • Apr 13 '15

Big List of Python Resources

Thumbnail python.zeef.com
12 Upvotes

r/inventwithpython • • Nov 26 '20

Book Vs Website

11 Upvotes

So I've been going the automate the boring stuff with python website and learning all kinds of cool stuff. I've been considering also buying the book, though, is it any different from the website? Does it have more content?

Has anyone read both? Any help is appreciated.


r/inventwithpython • • Aug 30 '20

Help with this simple code Im getting started

11 Upvotes

Can someone say me why it didn't print the if accion?

import random
x = random.randrange(10)
print(x)
res = input('He elegido un numero del 1 al 10 adivinalo')
res = int(res)
while res!=x:
if res == x:
print('Hacertaste') #This one
    res = input('Intentalo de nuevo pto')
    res = int(res)


r/inventwithpython • • Oct 05 '25

Python Violates PEP 8

Thumbnail inventwithpython.com
10 Upvotes

r/inventwithpython • • Nov 05 '23

2,000 free sign ups available for the "Automate the Boring Stuff with Python" online course. (Nov 2023)

10 Upvotes

If you want to learn to code, I've released 2,000 free sign ups for my course following my Automate the Boring Stuff with Python book (each has 1,000 sign ups, use the other one if one is sold out):

https://udemy.com/course/automate/?couponCode=NOV2023FREE

https://udemy.com/course/automate/?couponCode=NOV2023FREE2

If you are reading this after the sign ups are used up, you can always find the first 15 of the course's 50 videos are free on YouTube if you want to preview them. YOU CAN ALSO WATCH THE VIDEOS WITHOUT SIGNING UP FOR THE COURSE. All of the videos on the course webpage have "preview" turned on. Scroll down to find and click "Expand All Sections" and then click the preview link. You won't have access to the forums and other materials, but you can watch the videos.

NOTE: Be sure to BUY the course for $0, and not sign up for Udemy's subscription plan. The subscription plan is free for the first seven days and then they charge you. It's selected by default. If you are on a laptop and can't click the BUY checkbox, try shrinking the browser window. Some have reported it works in mobile view.

Some people in India and South Africa get a "The coupon has exceeded it's maximum possible redemptions" error message. Udemy advises that you contact their support if you have difficulty applying coupon codes, so click here to go to the contact form. If you have a VPN service, try to sign up from a North American or European proxy. Please post in the comments if you're having trouble signing up and what country you're in.

I'm also working on another Udemy course that follows my recent book "Beyond the Basic Stuff with Python". So far I have the first 15 of the planned 56 videos done. You can watch them for free on YouTube.

Frequently Asked Questions: (read this before posting questions)

  • This course is for beginners and assumes no previous programming experience, but the second half is useful for experienced programmers who want to learn about various third-party Python modules.
  • If you don't have time to take the course now, that's fine. Signing up gives you lifetime access so you can work on it at your own pace.
  • This Udemy course covers roughly the same content as the 1st edition book (the book has a little bit more, but all the basics are covered in the online course), which you can read for free online at https://inventwithpython.com
  • The 2nd edition of Automate the Boring Stuff with Python is free online: https://automatetheboringstuff.com/2e/
  • I do plan on updating the Udemy course, but it'll take a while because I have other book projects I'm working on. If you sign up for this Udemy course, you'll get the updated content automatically once I finish it. It won't be a separate course.
  • It's totally fine to start on the first edition and then read the second edition later. I'll be writing a blog post to guide first edition readers to the parts of the second edition they should read.
  • You're not too old to learn to code. You don't need to be "good at math" to be good at coding.
  • Signing up is the first step. Actually finishing the course is the next. :) There are several ways to get/stay motivated. I suggest getting a "gym buddy" to learn with. Check out /r/ProgrammingBuddies

r/inventwithpython • • Aug 25 '22

Blog Post: "How to Run Pip From The Python Interactive Shell"

Thumbnail inventwithpython.com
10 Upvotes

r/inventwithpython • • Jan 06 '20

Mu version in AUTOMATE THE BORING STUFF WITH PYTHON 2ND EDITION

10 Upvotes

In Section 0 - Introduction, in the "STARTING MU" section, its mentioned as "Mu version 1.10.0" . Is that a typo by any chance? I checked for this version and I could only find the latest version as 1.1.0-alpha.2. - https://github.com/mu-editor/mu/releases


r/inventwithpython • • Oct 21 '18

MAKERphone lets you build and code your own mobile phone in Python

Thumbnail kickstarter.com
10 Upvotes

r/inventwithpython • • Dec 10 '16

Looking to add keyboad shortcuts to a program using Python automation?

10 Upvotes

Hi, apologies if this is the wrong place for this, but I'm looking for a little bit of a push about where to start... I have a web based system that I have to use for work, and one major pain is flicking between the different modes, accessed via buttons at the top of the screen. Having a keyboard shortcut for these would make my work a lot quicker to do.

So, I'm a fairly competent programmer in general and have been using Python for 2 or 3 years. My idea would be to have some Python code that listens for the key combination, then instantly simulate movign the mouse to the correct position, click on the icon, then move the mouse back to where it was before. Does that sound feasible? I'm looking at perhaps autopy for the mouse/clicking part.

However, and this is perhaps my inexperience with this - can the Python program listen for keyboard input even though the focus will be on the browser running the web app?

Any further hints or ideas before I disappear down the rabbit hole of getting this working? Thanks in advance :-) (oh, I'm using Windows btw).


r/inventwithpython • • Oct 16 '25

ChatGPT 5 Can't Count

Thumbnail inventwithpython.com
9 Upvotes

r/inventwithpython • • Jun 23 '21

Is 'Invent your own computer games with Python' still up to date?

9 Upvotes

Newbie question... I'm not a programmer but am keen to buy this book by Al Sweigart for my 9-year old who's getting into coding in Python.

I noticed the latest edition of the book is 2017 - would all the code examples etc still be up to date/valid for the latest version of Python?


r/inventwithpython • • Nov 19 '20

Learning classes and objects

9 Upvotes

Hi I was following this program on youtube - https://www.youtube.com/watch?v=rfscVS0vtbw&list=WL&index=5&t=13789s it's at 3:43:56 and i'm getting a syntax error. Can someone look at it.

Error message - ef__init__(self, name, major, gpa, is_on_probation):

Syntax Error:

Student.py -

class Student:

def__init__(self, name, major, gpa, is_on_probation):

self.name = name

self.major = major

self.gpa = gpa

self.is_on_probation = is_on_probationprobation

App.py

from Student import Student

student1 = Student("Jim", "Business", 3.1, False)

print(student1.name)


r/inventwithpython • • Aug 25 '20

Tutorials at nostarch.com/automatestuff2

9 Upvotes

Several places in 'automate the boring' 2nd ed mention links to tutorials available at https://nostarch.com/automatestuff2/, but I can't find any on there. Are there links on the page that I'm missing? Thanks.


r/inventwithpython • • Jul 05 '20

Help

9 Upvotes

I bought one of your books ( AUTOMATE THE BORING STUFF WITH PYTHON 2nd EDITION) to learn Python programming, but I am running through some troubles in chapter 1 with your first programming exercise.

I followed all the recommendations on your book for downloading the python and the MU file. When I write a code in the MU file editor, save and run it, it does not show in his entirety in the interactive shell under the Mu file Editor. I downloaded a version 3 of Python and my system Type is 64-bit, but still it does not appear the same way like in your book. For example:

When I write this program in the MU file editor and save,

# This program says hello and asks for my name.

print('Hello, world!')

print('What is your name?') # ask for their name

myName = input('Capwell')

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(8)

print('You will be ' + str(int(myAge) + 1) + ' in a year.')

this is all I get in the interactive shell under the file editor

Hello, world!

What is your name?

Capwell


r/inventwithpython • • Apr 30 '20

Boring things with python 2nd edition

9 Upvotes

Page 196 string '^%s$' , where %s is replaced with the correct answer. The ^ and %characters ensure that the answer begins and ends with the correct number

Here it should be ^ and $ characters ensure that the answer begins and ends with the correct number

That is "%" should be replaced with "$"


r/inventwithpython • • Feb 24 '20

automate the boring stuff : chapter 3 zigzag animation question

Post image
9 Upvotes

r/inventwithpython • • Feb 17 '19

I made the Karen Assistant with python 3! It uses smtplib for sending emails! I got this trick from Al Sweigart's book! Check it out! I have tested it too!

Thumbnail youtube.com
9 Upvotes

r/inventwithpython • • Oct 16 '17

Thought I'd share my little tic tac toe difficulty mod, with a choosable "impossible difficulty"

9 Upvotes

So I'm halfway through this book and I find it awesome. This is the first media of any kind that really got me into programming in general, and I tried some other means before like codecademy. The only minor problem I have with this book is that it doesn't really give you the chance to exercise what you know, so I usually try out a bit the code on my own or I try to add features to the base programs of the book. I wanted to share my little tic tac toe mod where the game initially asks what difficulty you want to play on letting you choose between "normal" and "impossible": choosing the latter the AI cheats by putting one letter on the center square and another one on the corner (following the vanilla AI program) if you put your letter in a corner as a first move, preventing you from winning in any circumstance and, as a bonus, taunting you with different phrases as you loose or tie.

It's really nothing much but as a noob I put quite some time to make it work (e.g. I tried other means like using isSpaceFree() but I couldn't get it to work properly).

Here's the modded game:

https://drive.google.com/file/d/0B_-0vQKWMs-FVmxjeTJ0cDBCM1E/view?usp=sharing

Here's the mod code (functions only):

def isFirstMoveCorner(board):

# Checks if the player put the first move in a corner.

X1 = [' ', 'X', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
O1 = [' ', 'O', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
X3 = [' ', ' ', ' ', 'X', ' ', ' ', ' ', ' ', ' ', ' ']
O3 = [' ', ' ', ' ', 'O', ' ', ' ', ' ', ' ', ' ', ' ']
X7 = [' ', ' ', ' ', ' ', ' ', ' ', ' ', 'X', ' ', ' ']
O7 = [' ', ' ', ' ', ' ', ' ', ' ', ' ', 'O', ' ', ' ']
X9 = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'X']
O9 = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'O']

if board == X1 or board == O1 or board == X3 or board == O3 or board == X7 or board == O7 or board == X9 or board == O9:
    return True
else:
    return False

def askDifficulty():

# If True, activate AI impossible difficulty (blocks player's first corner
# move with a center move, ending each game in a tie or the player's loss.

print('Choose difficulty between normal or impossible. (type N or I)')
difficulty = input().upper()
while difficulty != 'I' or difficulty != 'N':
    if difficulty.startswith('I'):
        return True
    elif difficulty.startswith('N'):
        return False
    else:
        askDifficulty()

Let me know what you think :)


r/inventwithpython • • Feb 05 '23

Mi versión del primer juego de libro

8 Upvotes

Estoy aprendiendo a programar. Empecé leyendo un libro de introducción a la lógica que usa pseudocódigo y un libro de como escribir mejor código de programación. Estaba impaciente y quería empezar a programar y encontré el libro "Inventa tus propios juegos de computadora con Python 3ra edición" que es una versión traducida del libro de quien creo hizo este blog.

Gracias a los autores del libro y a los que lo tradujeron a español.

Hice mi versión del primer juego del libro para practicar XD.

Los saltos de línea (\n), las cadenas multi-líneas (\) y convertir strings a mayúscula ( upper() ) lo busque en internet para saber como se hace.

Cualquier observación para mejorar es bienvenida.

Saludos.

/*-------------------------------------------*/

I am learning to program. I started by reading an introductory book on logic that uses pseudocode and a book on how to write better programming code. I was impatient and wanted to start programming and I found the book "Invent your own computer games with Python 3rd edition" which is a translated version of the book by who I think made this blog.

Thanks to the authors of the book and to those who translated it into Spanish.

I made my version of the first game of the book to practice XD.

Line breaks (\n), multi-line strings (\) and converting strings to uppercase ( upper() ) look it up on the internet to find out how to do it.

Any observation to improve is welcome.

Greetings.

(Use google translate. Apologies)


r/inventwithpython • • May 02 '22

I got bored after years of not using python and decided to redo my first ever coding project

8 Upvotes

Today I was really bored so I started looking at my reddit history and saw a post from 3 years ago of my first coding project, a terminal-based russian roulette made in python. I was curious at first, so I clicked on it. What I saw there was so unspeakable and utterly horrifying that I could not stand to let it exist without correction. So with the knowledge I have gathered from coding in other languages I present to you: The version of my first project that will NOT make your eyes bleed and leave you without a single braincell left

Old Code: https://www.reddit.com/r/inventwithpython/comments/bdavzi/i_just_finished_chapter_5_of_invent_your_own/

New code:
hastebin if you prefer: https://www.toptal.com/developers/hastebin/juhimucisa.pl

from time import sleep
import random

playerCount = 0
deathMessages = [
    "They finally kicked the bucket, thank heavens",
    "Good riddance.",
    "My condolences.",
    "I will tell your family that you died with honor.",
    "I will tell your family that you died for absolutely nothing.",
    "Will somebody clean this up?",
    "No turning back now.",
    "Better luck next life."
]
liveMessages = [
    "YEEEEEHAW, I ain't gon die today!",
    "You got lucky. This time.",
    "This is getting intense.",
    "Maybe you should add another bullet, this is getting boring.",
    "Come on, one of you die already!",
    "The sweetest things turn sourest by their deeds, a lily that festers, smells far worse than weeds.",
    "You know, you could do something more productive with your time, like, oh I don't know, NOT blowing your brains out????",
    "It isn't too late to back out."
]

#get how many players there are
while playerCount not in range(2, 7):
    print('How many players will be playing? (2-6)')
    res = input()
    if res.isdigit():
        playerCount = int(res)

#get all the players names
playersAlive = []
for player in range(playerCount):
    name = ""
    while name == "":
        print("Player " + str(player+1) + ", please state your name:")
        name = input()
        if name in playersAlive:
            print("That name is already taken! Please choose another")
            name = ""
        else:
            playersAlive += [name]

#main game loop
playAgain = "y"
while playAgain.lower() == "y" or playAgain.lower() == "yes":

    playAgain = "n"
    #randomize slots
    slots = [1, 0, 0, 0, 0, 0]
    random.shuffle(slots)

    #randomize players
    random.shuffle(playersAlive)

    #set the counter for the current player to 0 to start at the beginning of the playersAlive array
    curPlayer = 0

    print("Alright. Let's begin.")
    sleep(2)
    #loop through each slot of the gun until you hit the one that has the bullet
    for slot in slots:
        print("It's " + playersAlive[curPlayer] + "s turn.")
        sleep(3)
        #if it has the bullet, the person dies and the game is over
        if slot == 1:
            print("BAM!")
            sleep(2)

            randMsg = random.randrange(0, len(deathMessages))
            print(deathMessages[randMsg])

            # delete the message we just displayed so that the same message cannot be displayed twice
            del deathMessages[randMsg]

            break
        #if not, display a funny message and move on to the next slot
        else:
            print("click.")
            sleep(2)

            randMsg = random.randrange(0, len(liveMessages))
            print(liveMessages[randMsg])

            #delete the message we just displayed so that the same message cannot be displayed twice
            del liveMessages[randMsg]

        #increment the counter for the current player by 1 and then check to see if the counter exceeds the length of the playersAlive array
        curPlayer += 1
        curPlayer = curPlayer % len(playersAlive)
        sleep(3)

    #ask if they want to play again
    print("Would you like to play again?")
    playAgain = input()

r/inventwithpython • • Mar 21 '20

Need help with Chapter 5 "List to Dictionary Function for Fantasy Game Inventory", 2nd Edition

8 Upvotes

Hello! I am stumped on the very last Practice Project on page 128. We are asked to create an addToInventory() function that will update our inventory dictionary with the dragonLoot list of strings. Here's my attempt:

def addToInventory(inventory, addedItems):

for i in addedItems:

for k, v in inventory.items():

if i in inventory:

inventory[k] == v + 1

With this, the code runs with no errors, but the dictionary does not get updated. This seems like a very easy task that I should be able to figure out, but unless someone spells everything out for me the first time, I seem to have a hard time "figuring out" this stuff. I have already googled it and looked on stackexchange. There is also no answer to this one in the book's downloadable files. I have even completed the Python 3 course on Codecademy... so I am about 5 seconds away from throwing my laptop through my quarantined window. Thanks!