r/inventwithpython • • May 19 '14

A successful port of a text mode game (using curses) in a graphic mode version using pygcurse

5 Upvotes

Last week, I was wondering how to convert a text-mode version of my game "squadron4" in graphics mode -- see http://redd.it/25pzrb and was informed about "pygcurse", made the transition this week-end and it worked - see the result at https://code.google.com/p/squadron4g/


r/inventwithpython • • Aug 31 '22

Question - on pg 60 of "Automate the boring stuff with Python"

5 Upvotes

Hello!

How do you add an input from the user after importing random? It doesn't seem to work. I want to add it before the code starts:

import random

right here <-------------------------- Where I want to add the str(input()) statement.

def getAnswer(answerNumber):

if answerNumber == 1:

return 'It is certain'

elif answerNumber == 2:

return 'It is decidedly so'

elif answerNumber == 3:

return 'Yes'

elif answerNumber == 4:

return 'Reply hazy try again'

elif answerNumber == 5:

return 'Ask again later'

elif answerNumber == 6:

return 'Concentrate and ask again'

elif answerNumber == 7:

return 'My reply is no'

elif answerNumber == 8:

return 'Outlook not so good'

elif answerNumber == 9:

return 'Very Doubtful'

r = random.randint(1, 9)

fortune = getAnswer(r)

print (fortune)

How do I add the input statement without getting the error:

SyntaxError: invalid syntax ?


r/inventwithpython • • Aug 22 '22

Which Al Sweigart Python Books Should I Start Reading?

Thumbnail
inventwithpython.com
16 Upvotes

r/inventwithpython • • Aug 09 '22

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

35 Upvotes

NOTE: The codes are all used up. But you can watch the first 15 of the 50 videos for free on YouTube. If you want to buy the rest of the course, the https://inventwithpython.com/automateudemy link redirects to a discount code that lowers the price to $13. The course follows the info in the book, which is for free in full at https://automatetheboringstuff.com/

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):

Udemy has changed their promo code and severely limited the number of sign ups I can provide each month, so only sign up if you are reasonably certain you can eventually finish the course. The first 15 of the course's 50 videos are free on YouTube if you want to preview them.

Instead of having unlimited free sign ups for 6 days per month, Udemy only lets me make 2,000 free sign ups per month. >:(

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.

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.

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.

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.

Side note: My latest book, The Big Book of Small Python Projects, is out. It's a collection of short but complete games, animations, simulations, and other programming projects. They're more than code snippets, but also simple enough for beginners/intermediates to read the source code of to figure out how they work. The book is released under a Creative Commons license, so it's free to read online. (I'll be uploading it this week when I get the time.) The projects come from this git repo.

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. 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 • • 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 • • Aug 25 '22

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

Thumbnail
inventwithpython.com
10 Upvotes

r/inventwithpython • • May 05 '23

Coin Flip Streak project in Automate the boring stuff - Is my solution logically correct?

4 Upvotes

I'm doing projects in Automate the boring stuff. This particular project asks me to Write a program to find out how often a streak of six heads or a streak of six tails comes up in a randomly generated list of heads and tails.

The #comments are hint by the author. This program I created ran just fine but the chance of streak is surprisingly high to me: ~152% - 153%. So I'm wondering if I got the logic right? Any help will be greatly appreciated. Thank you

import random

def flip():
    random_num = random.randint(0, 1)
    if random_num == 1:
        return "H"
    else:
        return 'T'
            
numberOfStreaks = 0 #author wrote this line
for experimentNumber in range(10000): #author wrote this line
# Code that creates a list of 100 'heads' or 'tails' values.

    head_tail_str = ""
    side = flip() 
    head_tail_str += side
    for _ in range(99):
        prev_side = side
        side = flip()
        if side != prev_side:
            head_tail_str += f",{side}"
        else:
            head_tail_str += side

# Code that checks if there is a streak of 6 heads or tails in a row.

    head_tail_lst = head_tail_str.split(',')
    for item in head_tail_lst:
        if len(item) >= 6:
            numberOfStreaks += (int(len(item)) // 6)

print('Chance of streak: %s%%' % (numberOfStreaks / 100)) #author wrote this line

p/s: I've been learning Python for 1 month


r/inventwithpython • • Apr 05 '23

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

27 Upvotes

EDIT: The sign ups are all used up. Remember that the Free Preview is enabled for all videos, so you can still watch them all on the course home page. And the first 15 videos are also on YouTube.

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=APR2023FREE

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

Udemy has changed their promo code and severely limited the number of sign ups I can provide each month, so only sign up if you are reasonably certain you can eventually finish the course. 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.

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.

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.

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.

Side note: My latest book, Python Programming Exercises Gently Explained is a set of 42 programming exercises for beginners for free or as a 99 cent ebook.

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. 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 • • May 09 '23

[Possible errata] Recursive Book of Recursion, p. 24

3 Upvotes

In the middle of the page it's written:

The first half is factorial(number - 1). This involves calculating number - 1
and making a recursive function, causing a new frame object to be pushed
to the call stack. This happens before the recursive call is made.

I think this should be something like this:

The first half is factorial(number - 1). This involves calculating number - 1

and making a recursive call to this function, causing a new frame object to be pushed

to the call stack.

Am I misunderstanding it?


r/inventwithpython • • Oct 02 '22

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

33 Upvotes

UPDATE: The sign ups have run out. You can still find the first 15 videos of the 50 video course on YouTube for free. Also, check out my new book with programming exercises for beginners for free or as a 99 cent ebook.

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=OCT2022FREE

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

Udemy has changed their promo code and severely limited the number of sign ups I can provide each month, so only sign up if you are reasonably certain you can eventually finish the course. The first 15 of the course's 50 videos are free on YouTube if you want to preview them.

Instead of having unlimited free sign ups for 6 days per month, Udemy only lets me make 2,000 free sign ups per month. >:(

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.

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.

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.

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.

Side note: My latest book, The Big Book of Small Python Projects, is out. It's a collection of short but complete games, animations, simulations, and other programming projects. They're more than code snippets, but also simple enough for beginners/intermediates to read the source code of to figure out how they work. The book is released under a Creative Commons license, so it's free to read online. (I'll be uploading it this week when I get the time.) The projects come from this git repo.

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. 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 • • Sep 05 '22

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

40 Upvotes

NOTE: The codes are all used up. But you can watch the first 15 of the 50 videos for free on YouTube. If you want to buy the rest of the course, the https://inventwithpython.com/automateudemy link redirects to a discount code that lowers the price to $13. The course follows the info in the book, which is for free in full at https://automatetheboringstuff.com/

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=SEP2022FREE

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

Udemy has changed their promo code and severely limited the number of sign ups I can provide each month, so only sign up if you are reasonably certain you can eventually finish the course. The first 15 of the course's 50 videos are free on YouTube if you want to preview them.

Instead of having unlimited free sign ups for 6 days per month, Udemy only lets me make 2,000 free sign ups per month. >:(

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.

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.

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.

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.

Side note: My latest book, The Big Book of Small Python Projects, is out. It's a collection of short but complete games, animations, simulations, and other programming projects. They're more than code snippets, but also simple enough for beginners/intermediates to read the source code of to figure out how they work. The book is released under a Creative Commons license, so it's free to read online. (I'll be uploading it this week when I get the time.) The projects come from this git repo.

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. 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 • • Oct 05 '23

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

24 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=OCT2023FREE

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

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 • • Sep 07 '23

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

18 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=SEP2023FREE

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

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 • • Sep 24 '23

[HELP] HTTP2 protocol ERROR keeps happening inconsistently when scraping website with Selenium python

1 Upvotes

I'm going through Automate the boring stuff book and instead of downloading the comic images for the exercise project, I decided to try scraping Sotheby auction site. I've written a script that goes through all the pages on https://sealed.sothebys.com (that have listings of auctioned items), collecting all the items' url, then open each url and download the 1st image of each item.

There are 2 specific points in the execution where the HTTP2 protocol ERROR (this site is unsecure) bug could happen:

  1. When clicking the next button to go to the next page

  2. When opening each auction item's url in a loop

I've isolated just the code for those 2 parts for debugging

I. Clicking the Next Button:

from selenium import webdriver
import time

browser = webdriver.Chrome()
browser.get('https://sealed.sothebys.com')
time.sleep(5)
# click on Next button
n = 0
while True:
    next_button = browser.find_element('css selector', 'button.sc-dd495492-1:nth-child(5)')
    if not next_button.is_enabled():
        print('End of current item on auction catalogue.')
        break
    browser.execute_script("arguments[0].click()", next_button)
    n += 1
    print(n)
    time.sleep(2) 

When this works, it outputs in order: 1 2 'End of current item on auction catalogue.'

(there are only 3 listings pages at this moment)

When it doesn't work, it outputs: 1 <Error message

II. Opening auction items' urls:

I have to remove the https:// part and replace '.' in the url with '_' to avoid issues with posting

from selenium import webdriver
import time

new_items = ['sealed_sothebys_com/YF23/auction', 
         'google_com',
         'sealed_sothebys_com/BC23/auction', 
         'sealed_sothebys_com/michael-jordan/auction', 
         'google_com', 
         'sealed_sothebys_com/the-black-rose/auction', 
         ]

for url in new_items:
browser.get(url)
time.sleep(2)
try:
    item_name_ele = browser.find_element('tag name', 'h3')
except:
        print('Error')

60-70% of the time, the error starts happening with the 2nd url and every url afterwards, 30-39% of the time, the first few urls will have no problems (the number of the working urls varies, could be 3 ,5, 10, more than 10 ..) and only 1% of the time or less that 100% of the urls work. Once the error happens with 1 url, all the urls after it will have the error as well. I've inserted 2 google links in the list to test, and they still work fine even if the error happens with the sothebys url right before them.

WHAT I'VE TRIED

  1. I run the code with Firefox driver in the beginning. When the error happened, I thought to try the Chrome driver. It worked with 100% the urls the 1st time I run it with Chromedriver. But from the 2nd time onwards, the error starts showing up with no difference to using Firefox driver.

  2. I tried turning off my antivirus software. Didn't work.

  3. I tried browser.delete_all_cookies() then browser.refresh() when the code encounters error finding element on page. Didn't work. (I did this because if I manually do this on the page opened with selenium: delete cookies and refresh -> the error will disappear, but it will appear again when I click on any link on that page)

  4. I tried adding arguments for Chrome options

from selenium.webdriver.chrome.options import Options as ChromeOptions

options = ChromeOptions()
# cloud_options = {}

options.accept_insecure_certs = True
options.add_argument('--ignore-ssl-errors=yes')
options.add_argument('--ignore-certificate-errors')
options.add_argument('--allow-insecure-localhost')
options.add_argument('--allow-running-insecure-content')

# options.set_capability('cloud:options', cloud_options)
browser = webdriver.Chrome(options=options)

The above block of code added before browser.get('https://sealed.sothebys.com') does absolutely nothing. How do I make my code work? I really really appreaciate any help and insights


r/inventwithpython • • Sep 06 '23

Learning to Program In An Age of ChatGPT with Al Sweigart

Thumbnail
youtube.com
13 Upvotes

r/inventwithpython • • Jun 11 '24

my "dragon realm" is not working

4 Upvotes

hello everyone, i have a problem with my code. In chapter 5, its explained how to do a game called dragon realm. I wrote the code and when i tried to run it, but no text showed up. I tried copypasting the code and running it but it didnt work either. I dont know if im supposed to do something and i need help. i'm using python 3.12.4.

please help me, ive did all the other games introduced before this one and something like this never happened.


r/inventwithpython • • Jan 17 '19

Strange problem with Hangman project

1 Upvotes

Hiyo,

I've got a some what interesting problem with the extended hangman game project.

It runs fine, but if the player guesses the first letter of the secret word, the game ends, thinking the player has won.

For example if the word is "Purple" and the player guesses P, the game ends, even if they haven't guessed the other letters. I'm still very new to programming so I don't really know what would be causing this issue.

Any help would be greatly appreciated.

https://pastebin.com/hPBTbqB6


r/inventwithpython • • Oct 06 '18

Error in wikipedia subcategory crawling using python3

2 Upvotes

Hello Community Members,

I am getting the error `FileNotFoundError: [Errno 2] No such file or directory: 'categories/Category/Cricket.html' `. The code is as follows. Please help. Any sort of help is appreciated. I have been strucked onto this since last 3 days. The code is all about to extract all the subcategories name of wikipedia category in Python 3.

I have tried both the relative and absolute paths.

The code is as follows:

import httplib2 
from bs4 import BeautifulSoup 
import subprocess 
import time, wget 
import os, os.path  
#declarations 
catRoot = "http://en.wikipedia.org/wiki/Category:" 
MAX_DEPTH = 100 
done = [] 
ignore = [] 
path = 'trivial' 
#Removes all newline characters and replaces with spaces 
def removeNewLines(in_text): 
    return in_text.replace('\n', ' ') 
# Downloads a link into the destination 
def download(link, dest): 
# print link 
    if not os.path.exists(dest) or os.path.getsize(dest) == 0:     
        subprocess.getoutput('wget "' + link + '" -O "' + dest+ '"') 
        print ("Downloading") 

def ensureDir(f): 
    if not os.path.exists(f):         
        os.mkdir(f) 
# Cleans a text by removing tags 
def clean(in_text):  
    s_list = list(in_text)
        i,j = 0,0
        while i < len(s_list):
    #iterate until a left-angle bracket is found
            if s_list[i] == '<':
                if s_list[i+1] == 'b' and s_list[i+2] == 'r' and s_list[i+3] == '>':
                    i=i+1
                    print ("hello")
                    continue               
                while s_list[i] != '>':
    #pop everything from the the left-angle bracket until the right-angle bracket
                    s_list.pop(i)
    #pops the right-angle bracket, too
                s_list.pop(i)

            elif s_list[i] == '\n':
                s_list.pop(i)
            else:
                i=i+1        
    #convert the list back into text
    join_char=''
    return (join_char.join(s_list))#.replace("<br>","\n")

    def getBullets(content):
        mainSoup = BeautifulSoup(contents, "html.parser")
    
    # Gets empty bullets
    def getAllBullets(content):
        mainSoup = BeautifulSoup(str(content), "html.parser")
        subcategories = mainSoup.findAll('div',attrs={"class" : "CategoryTreeItem"})
        empty = []
        full = []
        for x in subcategories:
            subSoup = BeautifulSoup(str(x))
            link = str(subSoup.findAll('a')[0])
            if (str(x)).count("CategoryTreeEmptyBullet") > 0:
                empty.append(clean(link).replace(" ","_"))
            elif (str(x)).count("CategoryTreeBullet") > 0:
                full.append(clean(link).replace(" ","_"))

        return((empty,full))

    def printTree(catName, count):
        catName = catName.replace("\\'","'")
        if count == MAX_DEPTH : return
        download(catRoot+catName, path)
        filepath = "categories/Category:"+catName+".html" 

        print(filepath) 
        content = open('filepath', 'w+')

        content.readlines()
        (emptyBullets,fullBullets) = getAllBullets(content)
        f.close()
        for x in emptyBullets:
            for i in range(count): 
              print ("  "),
        download(catRoot+x, "categories/Category:"+x+".html")
        print (x)
        for x in fullBullets:
          for i in range(count): 
              print ("  "),
          print (x)
       	  if x in done:
       		 print ("Done... "+x)
       		 continue
          done.append(x)
          try: printTree(x, count + 1)        
          except: 
              print ("ERROR: " + x)
    name = "Cricket"
    printTree(name, 0)   

r/inventwithpython • • Nov 04 '19

"Automate the Boring Stuff with Python" Udemy course is free to sign up for with code NOV2019FREE

57 Upvotes

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

Udemy has changed their coupon policies, and I'm now only allowed to make 3 coupon codes each month with several restrictions. I'll no longer be able to make free coupon codes with arbitrary restrictions. Instead I can:

  • Make free codes that are only good for 3 days for an unlimited number of people (NOV2019FREE lasts until November 7, 2019 11:05 AM PST)

  • Make codes that make the course cheap (but not cheaper than what Udemy offers, allowing them to undercut me) for unlimited people that lasts for 30 days. (I've made a code NOV2019 for this.)

There's two other options, but they're less than ideal: free but only 10 people can use it, or lowest price but it's only good for a few days instead of a month. I can only make 3 codes a month, so I can't just generate new codes every few days.

If you're reading this post after the NOV2019FREE code, you can use the NOV2019 code to get the course for about $14. I plan on making new free codes for the first three days of each month. You can probably guess what next month's free code will be.

To head off any questions:

  • 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 the same content as the book, which you can read for free online at https://inventwithpython.com

  • The 2nd edition of Automate the Boring Stuff with Python will be posted on the website in mid-November. It gets released on the 12th, and I'll need a couple days to format it to HTML and make it look nice.

  • 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- or late-2020. 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

  • I used to do free codes once or twice a year. The last time I did, I had an amazing 80,000 people sign up (so a dozen of them might have actually finished the course, if people are as good as I am about finishing the online courses I sign up for). Udemy's new policies mean I can't do this anymore. I find this to be a less than ideal situation. So I'm rolling out new codes each month. NOV2019FREE is the free code, and NOV2019 is the cheap code. I'll come out with new ones at the start of each month. (And yes, I'll probably write a script to automate this.)


r/inventwithpython • • Oct 30 '19

EU preorder of the second edition available?

5 Upvotes

Does anyone know of a european resaler for the upcoming second edition?

I had a look at nostarch but the shipping is more than the book and this is without the expected import taxes.


r/inventwithpython • • Jan 15 '19

Problem in the last line of Python code

4 Upvotes

from random import randint,seed

equal_distances=0

for n in range(5000):

seed(n)

res_sum=0

distr_num=[]

t=0

for i in range(10):

g=randint(0,1000)

res_sum+=g

distr_num.append(g)

t+=1

mean=res_sum/t

higher_sum=0

lower_sum=0

for item in distr_num:

if item<mean:

s_lower=mean-item

lower_sum+=round(s_lower,1)

else:

s_higher=item-mean

higher_sum+=round(s_higher,1)

if lower_sum==higher_sum:

equal_distances+=1

In the last line of the above code the variable equal_distances counts how many times variable lower_sum is equal to higher_sum. Because of the method used in the code the result is suppose to be 5000. Unfortunately the result is 3957. In spite the fact that the both variable respectively are always the same increment in the last line has been skipped many times. If you try to print the value of equal_distances in every step it is looks like this 1-2-3-3-3-4-5-6-6-7-8-9-10 and so on. At the end of the day I have 5000 attempts of addition but because of skipping only 3957 increments. What is the problem in the above code?


r/inventwithpython • • Jan 18 '19

Encrypt email message and forward

1 Upvotes

Hi there,

I am new to this forum. Hope, i get guidance/advise from any one of you on my requirement. My req. is, I need to develop a python script which will read the emails received on the email server encrypt them and forward to destination email server/address. The email server which i want to read from is kind of mediator between two or many other email servers. Can someone guide me as to how to approach this read, encrypt and forward part in python.

Thanks in advance.


r/inventwithpython • • Nov 15 '18

pylint errors that make no sense?

2 Upvotes

I'm new to Python and every time I try running Pygame i get these errors:

Module 'pygame' has no 'quit' member

Module 'pygame' has no 'QUIT' member

Module 'pygame' has no 'KEYDOWN' member

Module 'pygame' has no 'K_RIGHT' member

Module 'pygame' has no 'K_UP' member

Module 'pygame' has no 'K_DOWN' member

Module 'pygame' has no 'K_LEFT' member

How can I fix this??????


r/inventwithpython • • Sep 27 '19

MANY LINKS PROBLEM

1 Upvotes

There are so many links to download files from https://www.python.org/downloads/release/python-344/. Which I should choose??


r/inventwithpython • • Jun 25 '15

Thunderbird is a pain of a email client:Automate boring stuff

2 Upvotes

I am working on an automated emailer based on the one in Automate the boring stuff. It works well except when I try to read it using Thunderbird. (Seriously I have read the exact same email through Gmail's website and Thunderbird and they are different)

With the line smtpObj.sendmail('[email protected]',To,'Subject: test \n' + '\nDear '+name+'\nCan I order the following from you?\n \n'+body+

                 '\nChris \nKPFA Radio')

It would look correct in Gmail and Hotmail, but until I put the extra /n before "Dear", It would put Subject: Test Dear Chris as the subject
and simply '\nChris \nKPFA Radio' as the main part of the email. None of the actual details of what I want to order from people.

I have coded around it by just trying various things until it worked, but I don't know why. Is Thunderbird just written to interpret the message differently ? Is it not following standards or are standards just loose.

Since I want to use this mailer at work, sending out real work related emails to outside people, how can I be sure that there aren't other 'gotchas' out there . I don't know what email client they will be using and I can't ask them if they got my previous email without it looking odd. (These are established vendors, so it's not spam, it's just that asking if they got the last email may not look professional to them).