r/inventwithpython • • Jun 03 '15

Automate The Boring Stuff - Chapter 5 - Why do my dictionaries always print in a different order?

4 Upvotes

Doing the practice problems in Chapter 5, I've noticed that when I run the program multiple times the output is different. The values are all the same, but in a different order each time.

Here's an example: this program displays the original inventory, then calls the function that adds loot to it, then displays it again.

https://gist.github.com/anonymous/8a2abef5024999270d1a

Here's my code:

https://gist.github.com/anonymous/7001bde7c602016234cb


r/inventwithpython • • Jan 25 '16

[x-post from /r/computervision/] [Help] Bag of visual words - Python

Thumbnail
reddit.com
2 Upvotes

r/inventwithpython • • Jul 05 '17

[Automate] Automate the Boring Stuff - Chapter 7 - Regex Version of Strip() Question

1 Upvotes

Hi guys, quick question here:

Chapter 7's last practice problem says the following:

Write a function that takes a string and does the same thing as the strip() string method. If no other arguments are passed other than the string to strip, then whitespace characters will be removed from the beginning and end of the string. Otherwise, the characters specified in the second argument to the function will be removed from the string.

My question is: *Do I have to use args or some new thing not covered by this book yet, or is there a way to have a function that does something with no argument and then does something if you add an argument as well?


r/inventwithpython • • Jun 02 '15

Global And Local scope are confusing me ! -chapter 6 invent with python

2 Upvotes

i was confused at chapter 6 page 55 about the local and global scope, and about the example of changing a global variable inside a function , actually before the example the book says that " but attempting to change a global variable from the local scope won’t work. What Python actually does in that case is create a local variable with the same name as the global variable " , i dont get it when python will make 2 different variables while in the example the function bacon has spam variable and outside it there is spam , at first i thought the result of the example would be ( 99 , 42 , 99) not ( 42, 99, 42 ) if python creates another variable with the same name, then why did he change the value of local spam ? and why the value of the global spam changed from 42 to 99 ? thanks and i hope you got what i'm trying to say . again: the example is at page 55 in book ( invent with python )


r/inventwithpython • • Aug 08 '16

random 'Extending Hangman' question

1 Upvotes

I'd like to start by saying I'm enjoying the book a lot.

Well, I'm modifying the original Hangman game from chapter 9. It involves randomly picking an item from a list to be the secret word.

In chapter 9.5, the Hangman game is now using a dictionary. It first picks up a key from the dictionary. Each key is holding a list of strings, and one word is chosen from this list.

So the process islike this:

  1. pick a key that holds a list;

  2. pick a word from list;

The first step uses the random.choice() method. The second one uses random.randint() method.

The function code:

def getRandomWord(wordDict): # This function returns a random string from the passed dictionary of lists of strings, and the key also. # First, randomly select a key from the dictionary: wordKey = random.choice(list(wordDict.keys()))

# Second, randomly select a word from the key's list in the dictionary:
wordIndex = random.randint(0, len(wordDitc[wordKey])- 1)

Why is it? Why not use randint() or choice() on the two of them? I'm going to test them this way later, but I might not understand why it works/doesn't work.


r/inventwithpython • • Jul 29 '16

Chapter 13: What do we need this line?

1 Upvotes

if moveResult == False: (Lines 193, 194) continue

Why do we need it when we already have these lines in def enterPlayerMove() ?

move = move.split()

     if len(move) == 2 and move[0].isdigit() and move[1].isdigit() and isValidMove(int(move[0]), int(move[1])):

         return [int(move[0]), int(move[1])]

r/inventwithpython • • Jan 19 '16

Warning when I create a bs4 object, with Beautiful Soup, Ch.11

2 Upvotes

First I get this warning when I create a bs4 object, saying something is wrong with my parser?

Warning (from warnings module): File "C:\Users\Poison\AppData\Local\Programs\Python\Python35\lib\site-packages\bs4_init_.py", line 166 markup_type=markup_type)) UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

To get rid of this warning, change this:

BeautifulSoup([your markup])

to this:

BeautifulSoup([your markup], "html.parser")

Should I worry about this bad boy?


r/inventwithpython • • Dec 21 '23

Google authorization despair

3 Upvotes

Hi! I've been using EZsheets etc for automating a twice annual reporting process with Google sheets, mail, and drive... which collides into the 180 day expiration of Google authorization keys.

This go around, I've found my efforts to reauthorize -- including creating a new "app" -- foiled in the end by the unhelpful error message:

google.auth.exceptions.RefreshError: ('invalid_grant: Bad Request', {'error': 'invalid_grant', 'error_description': 'Bad Request'})

Any advice on what I can try to get this working? I promise to run the app monthly henceforth to keep my access current. Thanks!


r/inventwithpython • • Dec 24 '23

Invent Your Own Computer Games with Python or Making Games with Python & Pygame?

5 Upvotes

Hello!

I want to learn Python by using either the Invent Your Own Computer Games or the Making Games with Python and Pygame book.

It's not the first time I've learned Python, I learned the very basics in 2014 and 2021. But I've got more experience in Unity and C#. I finished a Unity 2D course in 2022 which covered C#, and so I'd say that I'm confident in the basics of that language (at least for Unity), and I've been practicing that fairly frequently.

Based on that, would I be better off going with the Invent Your Own Computer Games book or should I just jump straight to the Making Games with Python and Pygame book?


r/inventwithpython • • Dec 17 '23

Can't find author.com server

3 Upvotes

Hi, Al. Reading Automate the Boring Stuff. I've tried linking to https://author.com/vampire2, among others. My browser returns a message saying it's unable to find the server. Is there a problem with the site? Thanks.


r/inventwithpython • • May 12 '21

"Automate the Boring Stuff with Python" online course is free to sign up for the next few days with code MAY2021FREE

50 Upvotes

I'm a bit late with this month's free code, but it is now active.

https://inventwithpython.com/automateudemy (This link will automatically redirect you to the latest discount code.)

You can also click this link or manually enter the code: MAY2021FREE

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

This promo code works for three days (I can't extend it past that). Sometimes it takes an hour or so for the code to become active just after I create it, so if it doesn't work, go ahead and try again a while later. I'll change it to MAY2021FREE2 in three days.

Udemy has changed their coupon policies, and I'm now only allowed to make 3 coupon codes each month with several restrictions. Hence why each code only lasts 3 days. I won't be able to make codes after this period, but I will be making free codes next month. Meanwhile, the first 15 of the course's 50 videos are 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 for the second edition, but it'll take a while because I have other book projects I'm working on. Expect that update to happen in mid-2021. 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.

  • I wrote a blog post to cover what's new in the second edition

  • 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 • • Jun 03 '21

"Automate the Boring Stuff with Python" online course is free to sign up for the next few days with code JUN2021FREE

42 Upvotes

https://inventwithpython.com/automateudemy (This link will automatically redirect you to the latest discount code.)

You can also click this link or manually enter the code: JUN2021FREE

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

This promo code works until the 4th (I can't extend it past that). Sometimes it takes an hour or so for the code to become active just after I create it, so if it doesn't work, go ahead and try again a while later. I'll change it to JUN2021FREE2 in three days.

Udemy has changed their coupon policies, and I'm now only allowed to make 3 coupon codes each month with several restrictions. Hence why each code only lasts 3 days. I won't be able to make codes after this period, but I will be making free codes next month. Meanwhile, the first 15 of the course's 50 videos are 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 for the second edition, but it'll take a while because I have other book projects I'm working on. Expect that update to happen in mid-2021 or late-2021. 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.

  • I wrote a blog post to cover what's new in the second edition

  • 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 • • 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 • • 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 • • Feb 11 '19

ATBS Chapter 16 - reading emails.

2 Upvotes

https://automatetheboringstuff.com/chapter16/

In your example on how to read mails from a imap server you wrote following code:

 message = pyzmail.PyzMessage.factory(rawMessages[40041]['BODY[]']) 

But this gives a key error. I checked the content of rawMessages and to get the body of the mail you have to use [b'BODY[]']

 message = pyzmail.PyzMessage.factory(rawMessages[40041][b'BODY[]']) 

I guess if r'string' is a raw string the b'string' is a binary one? Can't remember that this stringmode was introduced in atbs.

Greetings


r/inventwithpython • • Apr 24 '19

Regex with 3 phone numbers in a row

1 Upvotes

Hello everyone! I am going crazy with a regex exercise. I am typing it exactly as I see it in the video, but when my string object is searched, the regex object is not recognized.

The exercise if from video 25:

This is what I type:

Please tell me what I am doing wrong, I am really confused (and I am one of those people who can't let go and just stop thinking about it before it's investigated thoroughly!!)


r/inventwithpython • • Feb 10 '19

ATBS Chapter 14 json-API

2 Upvotes

Hello.

First. Very nice Book. I love it and it's very well written to get into programming.

But please think about changing the example with openweathermap so that at least it is pointed out that a registration is necessary to use the api in the meantime.

Or even better: Rewrite the example to the freely accessible Wikipedia-api where no api-keys are needed (see code in comment). One reason for this is that the module requests was not explained well enough to handle ssl requests and I guess sending the api-key in plain text is rather suboptimal?

Greetings Apop

One more thing. In the questions for chapter 14 you ask:

Q:3. What modes do File objects for reader and Writer objects need to be opened in?

And you answer this with:

3. File objects need to be opened in read-binary ('rb') for Reader objects and write-binary ('wb') for Writer objects.

But... why? As you explained csv is pure text data and no binary so no need to read or write in binary and you also never used 'rb' or 'wb' in your examples in chapter 14


r/inventwithpython • • Apr 24 '19

Watching videos on youtube instead of udemy

5 Upvotes

Hello,

For lots of reasons I don't like Udemy (

  1. does not work on Mozilla and Opera, only in bloody safari

  2. the progression bar takes lots of time to disappear when pausing and reproducing code and does not disappear at all on chrome. Makes it quite impossible to type along.

  1. often going back to the start of the video if you pause, it drives you crazy to hear "Welcome to lesson..." dozens of times in a row or if you unfortunately have to pause or resize the window!!

  2. and my screen went all black once when I maximized the window!!! ).

If I send a proof of purchase of the course, is it possible to have a link to the private videos on youtube instead? Now I have to download all the videos which I find really annoying.


r/inventwithpython • • Apr 28 '19

How can filename.endswith('rxt') print texts ending with 'txt'?

3 Upvotes

Question from chapter 9, or video 33:

How does the line

if filename.endswith('rxt'):

print(filename)

detects filenames that end with 'txt'? Is endswith non greedy (if I use the right terminology?)


r/inventwithpython • • Jan 22 '20

Images with EZsheets

3 Upvotes

Al and everyone!

I am working my way through the new Automate the Boring Stuff and specifically concentrating on the chapter about Google Sheets because there are several projects at my work that I could automate with python.

I had two questions associated with EZsheets and since I know Al wrote the module I thought I would as them here.

  1. While I haven't tried it just yet I would assume that if you had a merged cell that you could get EZsheets to write to that cell because it still has a unique cell ID. I want to write a larger block of text to a merged cell. I will be trying this one soon.

  2. My bigger question is can I add an email to a cell. I know that in Google Sheets there is an "Insert Image In Cell" option. I was curious if this can be done through the module. I have not drill down in the Google API, so the answer my be in there, but I just throught I'd ask here to see if anyone else knew the answer while I researched!

Awesome Book Al, and thanks everyone for reading! Happy Programming!


r/inventwithpython • • Nov 07 '18

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

Thumbnail
slicker.me
8 Upvotes

r/inventwithpython • • Nov 22 '19

Cannont run the run the Multiclipboard program at the end of Chapter 8 in the Automate the Boring Stuff With Python book

2 Upvotes

Hello all,

I have some troubles to run the Multiclipboard at the end of Chapter 8 in the Automate the Boring Stuff With Python book.

I tried to run it like the Password Locker project in Chapter 6 with: pressing Win-R and typing mcb save <some keyword> and mcb <some keyword> to retrieve the value stored in the shelf file.

My mcb.bat file looks like this:

@pyw.exe C:\MyPythonScripts\mcb.pyw %*

@pause

And the mcb.pyw file is the one I downloaded from the additional content page on https://automatetheboringstuff.com/

Anyone could explain how to run this program?

Thank you all.


r/inventwithpython • • Jan 21 '20

Mu or Sublime Text

3 Upvotes

I just started Automate the Boring Stuff after finishing Python Crash Course.

In ATBS, it is having us use Mu. Does anyone know if it matters too much if I continue to use Sublime Text since I got used to it with PCC or should I start using Mu for this book.

Thank you for your input.


r/inventwithpython • • Nov 29 '21

Best practice code for autbor ch3 "Practice Projects"

4 Upvotes

I'm enjoying my first taste of python (and programming), using Automate the Boring Stuff. Ch3 has practice projects, relating to Collatz sequence. I'm not sure where to find or ask for help to compare my code with someone else's. My code appears to work, but it would be interesting to see different approaches. Anyone care to comment or point me in right direction, thanks.

For anyone interested, here's my code, firstly without the "try, except" and then with...

-------------------------------------------------------------------

# Ask for an integer

print('please enter an integer')
entry = int(input())

# Define collatz function

def collatz(number):
    
    if number % 2 == 0:
        print(number // 2)
        return number // 2
    
    elif number % 2 == 1:
        print(3*number + 1)
        return 3*number + 1

# Main code loop

while entry != 1:
    
    entry = collatz(entry)

print('Converged to 1')

---------------------------------------------------------------

# Define collatz function

def collatz(number):
    
    if number % 2 == 0:
        print(number // 2)
        return number // 2
    
    elif number % 2 == 1:
        print(3 * number + 1)
        return 3*number + 1

# Ask for an integer

print('please enter an integer')

# Main code loop

loop = True
while loop:
    try:
        entry = int(input())

    except ValueError:
        print('That is not an integer, please try again')
        continue

    while entry != 1:
    
        entry = collatz(entry)
        Loop = False

print('Converged to 1')

r/inventwithpython • • Dec 25 '21

Answers to end of chapter projects | AutBor

3 Upvotes

Dear Al/All

I am presently reading your book "Automate the boring stuff with Python".

I am getting errors as I try to solve the practice projects at the end of the chapters.

Where can I find the answers to these projects? 

Happy holidays,