r/inventwithpython • • Apr 12 '22

Eagl and Tails (task experiments in monet, page in book 161, name book Automating routine tasks with Python: A practical guide for beginners)

2 Upvotes

Здравствуйте, у меня есть вопрос, конкретно в этом: правильно я понял задачу и выполнил её?
I have a question about the task (task name in the table of contents of the post), specifically in this one: did I understand and complete it correctly?

import random, numpy, re
chetone = 0
chetzero = 0
numberOfStreaks = 0
for experimentNumber in range(10000):
    # create lists range of 100 values 0 and 1
    spisok = numpy.random.randint(0, 2, 100)    
    # Code verify availability 6 series Eagle and Tails
    sc = " ".join(map(str, spisok))
    regexone = re.search("1 1 1 1 1 1", sc)
    regexzero = re.search("0 0 0 0 0 0", sc)
    if regexone:
        chetone = chetone + 1
    elif regexzero:
        chetzero = chetzero + 1
    else:
        numberOfStreaks = numberOfStreaks + 1
print('Procent serries: %s%%' % (100 - (numberOfStreaks // 100)))
print(chetone, '\n' + str(chetzero))

r/inventwithpython • • Apr 16 '22

Probability of sailors found alive (Bayes project in Real-World Python)

4 Upvotes

I'm not certain whether this is the place to discuss or ask about Real-World Python. It is an InventWithPython book but isn't by Al Sweigart. I am asking here anyway, and hope to be (politely) directed elsewhere if this isn't the right place.

My question is an advanced statistical modeling question that goes beyond the project as specified. But this is the first time I've done a Monte Carlo simulation, and I've sort of become obsessed with fine tuning the project.

When doing the Monte Carlo simulation, it was fine to get a histogram of number of days it took to find the the sailor, but I wanted to also calculate the likelihood that the sailor is found alive. In my first version, I just used found alive if found in 3 days, dead otherwise. But I don't feel that that captured the urgency of trying to find them sooner and that three days is kind of iffy.

My intuition is that probability of dying on any given day should follow a Gamma distribution, but I have nothing to back up that intuition. And it certainly doesn't give me the parameters for the Gamma distribution. So I just played around by drawing curves of the cumulative distribution function and settled on a = 6, and scale = 1/2.

import scipy.stats as stats
def prob_alive_on_day(day):
    alpha = 6
    beta = 2
    p_dead = stats.gamma.cdf(day, a=alpha, scale = 1/beta)
    return 1 - p_dead

(I should also say that this is rather grim compared to the alive if found within three days. Even with using a strategy based on the Probability of Discovery extra, the sailor is only found alive about 75% of the time.)

Anyway, as morbid as this whole thing is, I am wondering if there is data or theory to help model this right.


r/inventwithpython • • Apr 24 '22

Window placement in Chapter 2 project of Real World Python

3 Upvotes

There are lots of really great things to say about the project in Chapter 2 of Real-World Python (Attributing authorship with stylometry), and will get to those in other posts. But as I just spent a bunch of time dealing with an annoying problem (not the author's fault), I thought that I would describe a bit of what I learned.

First, I am using macOS, where everything is supposed to "just work." Hold that thought.

In the core part of the project, we produce three figures using matplotlib.pyplot. I was finding myself a bit annoyed that each of the figures being created came up in the exact same spot on my machine. For a while, I thought I was only getting one of the figures, as the other two were being hidden directly underneath the one that I could see.

It shouldn't be hard to change the positions of the plots, right? I mean that seems like a fairly basic thing one would want to do. We did that in Chapter 1, but there we were using CV instead of pyplot. I was initially a bit annoyed that we weren't given some guidance on how to do this in the book. Naturally, I thought that a quick amount of DuckDuckGoing and looking at Matplotlib documentation should tell me how to do this.

Searching always brought be to this Stack Overflow answer. I didn't really believe that that was the right way to go, as it seemed weirdly complicated for something that should be simple. Searching the Matplotlib docs was even worse. I couldn't even find documentation for what was listed in the Stack Overflow answer.

Eventually, I realized that the Stack Overflow answer really was right. Positioning the window was done differently for each backend, and there was no general, uniform way of doing this. So I eventually went with that answer. I then discovered that the answer didn't work for macOS, or at least it didn't work for my setup. The "MacOSX" backend doesn't seem to provide the APIs to get this working. But hunting elsewhere, I found that at least some Mac users were able to tell their systems to use the "TkAgg" backend. (Indeed, I know that I am using TclTk as the back of the backend anyway due to other problems I've had; but that is a different story.)

So, it turns out that I can set the Matplotlib backend to "TkAgg", but this has to be done at the module level instead of something I could just do in main(). So my imports include

import matplotlib
if matplotlib.get_backend() == "MacOSX":
    matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

I also modified the StackOverflow answer to at least raise an error if you are using the macOS backend.

# https://stackoverflow.com/a/37999370/1304076
def move_figure(f, x, y):
    """Move figure's upper left corner to pixel (x, y)"""

    backend = matplotlib.get_backend()
    if backend == "MacOSX":
        raise Exception("This doesn't work for MacOSX backend. Try TkAgg.")
    
    if backend == 'TkAgg':
        f.canvas.manager.window.wm_geometry("+%d+%d" % (x, y))
    elif backend == 'WXAgg':
        f.canvas.manager.window.SetPosition((x, y))
    else:
        # This works for QT and GTK
        # You can also use window.setGeometry
        f.canvas.manager.window.move(x, y)

And I moved my plt.show() to the main() function and moved the figures around a bit with

    # on macos, this needs setting matplotlib.use('TkAgg') in module
    fig_offset = [100, 200]
    for fignum in plt.get_fignums():
        move_figure(plt.figure(fignum), fig_offset[0], fig_offset[1])
        fig_offset[0] += 160
        fig_offset[1] += 80
        
    plt.show(block=True)

I have no idea if what I did would work or be necessary for other Mac users. It is what worked for me.

I now completely understand why the book did not attempt to offer help with this. It is the kind of thing that is a lot to do to fix and will work (or not) differently in different setups. There isn't really an easy solution that will work for most people.

Again, there are lots of really great things in that project, but this is what has drawn my attention for a bit, so it is what I am talking about now.


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 • • 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 • • Apr 16 '22

Pyzmail

2 Upvotes

Hi all,

It seems Pyzmail won't install beyond python 3.6? Any suggestions around this. It would be nice to be able to do the book on the latest version of python


r/inventwithpython • • Apr 12 '22

Image shows on Part 1 (Pg. 4) is different from what I'm seeing

1 Upvotes

On page 4 of the book, the first image says
>>> 2 + 2
4
>>>

However, what I see is:
Jupyter QtConsole 4.7.7

Python 3.8.11 (default, Jul 24 2021, 23:33:17) [MSC v.1929 64 bit (AMD64)]

Type 'copyright', 'credits' or 'license' for more information

IPython 8.0.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]:

The In [1] is there instead of the '>>>'. I can still do the calculation of 2 + 2 without the '>>>'.
Does this change the outcome of any code/any section in the book? Or am I good to go?


r/inventwithpython • • May 06 '22

Non-OOP Tic-Tac-Toe in "Beyond the basic stuff"

5 Upvotes

Hey guys ! Currently working my way through "Beyond the basic stuff" and ran into this for this non oop tic tac toe game. The online version and paperback code match .. but the diff tool seems to have it written differently.. anyways here's what I found:



def isValidSpace(board, space):     
    """Returns True if the space on the board is a valid space number     
    and the space is blank."""     
    return space in ALL_SPACES or board[space] == BLANK

Original function kept giving a key error. I think it's because None will never be in the list and its betting on an or condition. I changed it to an and condition and it ran fine:


def isValidSpace(board, space):     
    """Returns True if the space on the board is a valid space number     
    and the space is blank."""     
    return space in ALL_SPACES and board[space] == BLANK

r/inventwithpython • • Aug 08 '21

Need help with loop

2 Upvotes

r/inventwithpython • • Jul 01 '21

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

51 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: JUL2021FREE

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

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

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

New Book by Al Sweigart: The Big Book of Small Python Projects

Thumbnail
inventwithpython.com
75 Upvotes

r/inventwithpython • • Jul 08 '21

Total Frustration CH3 ZigZag

3 Upvotes

The ch3 zigzag program seems to be a big leap from the previous examples in the chapter and includes things that haven't been covered. I am completely lost and frustrated.

Is there a way to view the execution of this program like the earlier examples?


r/inventwithpython • • May 13 '18

Cracking Codes With Python Corrections

4 Upvotes

u/AlSweigart , I felt bad spamming your e-mail, so I'll just post all corrections here and add if I find more.

Note: My PDF copy was created 12/1/2017 7:03:06PM and was last modified 12/4/2017 5:30:14PM

  • Chapter 1 Practice Questions:

The answer for Practice Question 1, part b: Encrypt “GUILLOTINE: A machine which makes a Frenchman shrug his shoulders with good reason.” with a key of 17 should be “XlZccfkZeV:NRN4rtyz5vN.yztyN4r2v0NrNW9v5ty4r5N0y9!xNyz0N0y6!3uv90N.z yNx66uN9vr065Q”, not “bpdggjodiZ:RVR8vx349zRD34x3R8v6z.RvRa?z9x38v9R.3?B2R34.R.30B7yz?.RD4A3R200yR?zv.09U” (that’s key of 21)

Scratch that, with SYMBOLS = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”, even the messages should be in all caps with totally different outputs, like the decryption in question 2.

Question 1 answers should be:

a. EQFMHIBXVSYW: EFPI XS TMGO AMXL IUYEP WOMPP E VMKLX-LERH TSGOIX SV E PIJX.

b. XLZCCFKZEV: R DRTYZEV NYZTY DRBVJ R WIVETYDRE JYILX YZJ JYFLCUVIJ NZKY XFFU IVRJFE.

c. DHKDZOT: TJPM DMMZQZMZIXZ OJRVMY HT YZDOT.

and Question 3 should be using all caps as well.

  • On page 57, the final paragraph reads:

“Just as in the reverse cipher in Chapter 5, …”

However, the reverse cipher was in chapter 4 because chapter 5 is the Caesar cipher!

  • On page 84, end of the third-to-last paragraph:

“(All the variables in the reverse cipher and Caesar cipher programs in Chapters 5 and 6, respectively, were global.)”

Chapter 6 was the Caesar cipher hacker program!

  • On page 166, the fourth paragraph:

Line 30 uses string interpolation to print the key currently being tested using string interpolation to provide feedback to the user.

  • On page 236, the code block​

>>> letterMapping1 = simpleSubHacker.addLettersToMapping(letterMapping1,
'OLQIHXIRCKGNZ', candidates[0])
>>> letterMapping1

Should be

>>> simpleSubHacker.addLettersToMapping(letterMapping1, 'OLQIHXIRCKGNZ', candidates[0])
>>> letterMapping1
  • On page 237, the code blocks:

>>> letterMapping1 = simpleSubHacker.addLettersToMapping(letterMapping1,
'OLQIHXIRCKGNZ', candidates[1])
>>> letterMapping1

and

>>> letterMapping2 = simpleSubHacker.getBlankCipherletterMapping()
>>> wordPat = makeWordPatterns.getWordPattern('PLQRZKBZB')
>>> candidates = wordPatterns.allPatterns[wordPat]
>>> candidates
['CONVERSES', 'INCREASES', 'PORTENDED', 'UNIVERSES']
>>> for candidate in candidates:
...     letterMapping2 = simpleSubHacker.addLettersToMapping(letterMapping2, 'PLQRZKBZB', candidate)
...
>>> letterMapping2

should be

>>> simpleSubHacker.addLettersToMapping(letterMapping1, 'OLQIHXIRCKGNZ', candidates[1])
>>> letterMapping1

and

>>> letterMapping2 = simpleSubHacker.getBlankCipherletterMapping()
>>> wordPat = makeWordPatterns.getWordPattern('PLQRZKBZB')
>>> candidates = wordPatterns.allPatterns[wordPat]
>>> candidates
['CONVERSES', 'INCREASES', 'PORTENDED', 'UNIVERSES']
>>> for candidate in candidates:
...     simpleSubHacker.addLettersToMapping(letterMapping2, 'PLQRZKBZB', candidate)
...
>>> letterMapping2
  • On page 238, the code block:​

>>> letterMapping3 = simpleSubHacker.getBlankCipherletterMapping()
>>> wordPat = makeWordPatterns.getWordPattern('MPBKSSIPLC')
>>> candidates = wordPatterns.allPatterns[wordPat]
>>> for i in range(len(candidates)):
...     letterMapping3 = simpleSubHacker.addLettersToMapping(letterMapping3, 'MPBKSSIPLC', candidates[i])
...
>>> letterMapping3

should be

>>> letterMapping3 = simpleSubHacker.getBlankCipherletterMapping()
>>> wordPat = makeWordPatterns.getWordPattern('MPBKSSIPLC')
>>> candidates = wordPatterns.allPatterns[wordPat]
>>> for i in range(len(candidates)):
...     simpleSubHacker.addLettersToMapping(letterMapping3, 'MPBKSSIPLC', candidates[i])
...
>>> letterMapping3

May 14, 2018 Update:

  • On page 253, the code block:​

>>> building = ''
>>> for c in 'Hello world!':
>>>     building += c
>>> print(building)

should be

>>> building = ''
>>> for c in 'Hello world!':
...    building += c
...
>>> print(building)
  • On page 254, the code block:​

>>> building = []
>>> for c in 'Hello world!':
>>>     building.append(c)
>>> building = ''.join(building)
>>> print(building)

should be

>>> building = []
>>> for c in 'Hello world!':
...    building.append(c)
...
>>> building = ''.join(building)
>>> print(building)

May 15, 2018 Update

  • On page 260, the last line:

Similarly, the letters that appear least often in the ciphertext are more likely to have been encrypted from to X, Q, and Z in plaintext.

May 18, 2018 Update

  • On page 298, the code:​

>>> set([1, 2, 3, 3, 4])
set([1, 2, 3, 4])

outputs

>>> set([1, 2, 3, 3, 4])
{1, 2, 3, 4}

for me, but that may be the interactive shell or OS I'm using (Ubuntu 16.04 with Python 3.5.2). TODO: Can anyone else confirm?

  • On page 306, the code:

>>> def printStuff():
        print('Hello', end='\n')
        print('Howdy', end='')
        print('Greetings', end='XYZ')
        print('Goodbye')
>>> printStuff()

should be

>>> def printStuff():
...     print('Hello', end='\n')
...     print('Howdy', end='')
...     print('Greetings', end='XYZ')
...     print('Goodbye')
...     
>>> printStuff()

May 19, 2018 Update

  • On page 318, the code block:

>>> import secrets
>>> otp = ''
>>> for i in range(55):
        otp += secrets.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
>>> otp

should be

>>> import secrets
>>> otp = ''
>>> for i in range(55):
...     otp += secrets.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
>>> otp

I think. Ubuntu 16.04 LTS doesn't have Python 3.6 or above. TODO: Can someone confirm?

  • On page 326, the code block:

>>> primeNum.isPrime(13)
True

should be

>>> primeNum.isPrime(13)
False

Here's the thing: isPrime() checks a number for divisibility by low prime numbers (which would make it not prime). Therefore, 13 is divisible by the low prime number 13 and is not prime by that definition.

You'd have to add something like:

if num in LOW_PRIMES:
    return True  # Low prime numbers are still prime numbers

to isPrime() to keep it from doing that.

May 20, 2018 Update:

  • On page 341 and 347, the code:

64. print('The private key is a %s and a %s digit number.' %
(len(str(publicKey[0])), len(str(publicKey[1]))))

should be

64. print('The private key is a %s and a %s digit number.' %
(len(str(privateKey[0])), len(str(privateKey[1]))))

r/inventwithpython • • Dec 15 '19

python

1 Upvotes

i am trying to train data using Word2Vec Skip-Gram and i am getting an error which is below.

"UserWarning: C extension not loaded, training will be slow. Install a C compiler and reinstall gensim for fast training."

These are the tools i am using with Visual Studio Code

Genism 3.8.1

Python 3.8.0

conda 4.7.12

scipy 0.18.1

numpy 1.11.3


r/inventwithpython • • Oct 11 '19

Having an issue with ATBS chpt 13

3 Upvotes

So I'm starting chapter 13. I downloaded the online materials zip. I installed the PyPDF2 module. When I start the lesson I can't even open the "meetingminutes.pdf". I always this message.

FileNotFoundError: [Errno 2] No such file or directory: 'meetingminutes.pdf'

I have tried moving the pdf, and the whole folder into the current working directory but that doesn't work either. Any idea what is happening here?


r/inventwithpython • • May 11 '18

Ch 12 Working with openpyxl pg 270 correction? openpyxl.cell should be openpyxl.utils

4 Upvotes

In order to use "get_column_letter" and "column_index_from_string" to work I used .utils instead of .cell:

from openpyxl.utils import get_column_letter, column_index_from_string


r/inventwithpython • • Dec 08 '18

Chapter 5 fantasy game inventory errors

1 Upvotes

For some reason i'm getting nonetype errors ( File "inventory.py", line 6, in displayInventory for k, v in inventory.items(): AttributeError: 'NoneType' object has no attribute 'items') when running my code for this excercise. It's strange because I have it working but specifically can't use this

inventory.items():

I have to use

myItems.items():

which means that my code isn't reusable and blocks me from finishing the second half of the excercise (which I have 90% working) full code:

myItems = {'rope':1,'sword':1,'shield':0,'potion':3,'mushroom':2,'chain':1,'egg':12}
def displayInventory(inventory):
    print('Inventory:')
    item_total = 0
    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        item_total = item_total + v
    print('Total number of items: ' + str(item_total))


displayInventory(myItems)

r/inventwithpython • • May 27 '19

"Automate the Boring Stuff" author is live streaming Python programming on Monday evening 5/27, 6pm Pacific

27 Upvotes

Hi Reddit! I'll be live streaming myself working on a few different text-based games in Python on Monday, 5/27 at 6pm Pacific:

https://www.twitch.tv/alsweigart/

I'm creating a collection of short, complete, text-based Python games. The idea is to create several examples for beginner/intermediate programmers to look at to see how programming concepts come together into a complete program (while still being small enough to understand). The current collection is on GitHub at: https://github.com/asweigart/PythonStdioGames/tree/master/src/


r/inventwithpython • • Dec 07 '18

Python. Why error? Help me please.

2 Upvotes
  1. import re

  2. phoneRegex = re.compile(r"""

  3. \+\d{1,2}(\s\-)?

  4. \(\d{3}\)(\-)?

  5. \d{3}(\-)?

  6. \d{2}(\-)?

  7. \d{2}

  8. """, re.VERBOSE)

  9. mo = phoneRegex.findall('My number is: +38(050)-453-25-12 +7(495) 162-24-30.')

  10. print('Found number is: ' + mo)

File "C:/Users//untitled1/Test.py", line 11, in <module>

print('Found number is: ' + mo)

TypeError: must be str, not list


r/inventwithpython • • Dec 14 '18

AtBS: Google Sheets

2 Upvotes

Hey /u/AlSweigart

Any chance of some additional content (addendum, blog post, something) related to using Python with Google Sheets, much like the chapter on Excel?

I know there are various other articles or tutorials already, but none with quite your focused problem solving approach!

Thanks!


r/inventwithpython • • Dec 15 '19

Python

3 Upvotes

i am trying to train data using Word2Vec Skip-Gram and i am getting an error which is below.

"UserWarning: C extension not loaded, training will be slow. Install a C compiler and reinstall gensim for fast training."

These are the tools i am using with Visual Studio Code

Genism 3.8.1

Python 3.8.0

conda 4.7.12

scipy 0.18.1

numpy 1.11.3


r/inventwithpython • • Dec 14 '19

Automate the Boring Stuff

3 Upvotes

I have the first edition of Automate the Boring Stuff and I see there is a second one out. Will I be able to use the new MU Editor when following along with the book or is that mostly with the new content for the second book? Also, will the second edition be online at some point? Thanks all.


r/inventwithpython • • Oct 05 '21

The Recursive Book of Recursion: Ace the Coding Interview with Python and Javascript

4 Upvotes

Will there be a way to purchase through inventwithpython.com instead of https://www.amazon.ca/gp/product/B09BKL34VL/ref=dbs_a_def_rwt_bibl_vppi_i6 ?

I love the "bonuses" that come with preordering from inventwithpython.com

TIA.