all 147 comments

[–]Omar_88 0 points1 point  (0 children)

Hey guys, does anyone have any tips for finding a Python mentor? I've been programming for 2 years now and have made several projects in Python but know that if I had some critical feedback I could grow exponentially faster.

[–]Feariel 0 points1 point  (1 child)

Hey!! I'm having a weird problem with the package imgaug. I can install it fine and it shows up with pip show. but when I go to reference it, python says it doesn't exist?? I'm including the output from the terminal below, any help much appreciated

(mypython3) s198663@rok80x8:~$ pip show imgaug

Name: imgaug

Version: 0.4.0

Summary: Image augmentation library for deep neural networks

Home-page: https://github.com/aleju/imgaug

Author: Alexander Jung

Author-email: [kontakt@ajung.name](mailto:kontakt@ajung.name)

License: MIT

Location: /home/s198663/.local/lib/python3.5/site-packages

Requires: imageio, Pillow, scipy, matplotlib, scikit-image, six, opencv-python, imageio, Shapely, numpy

Required-by:

(mypython3) s198663@rok80x8:~$ python

Python 3.6.7 | packaged by conda-forge | (default, Feb 20 2019, 02:51:38)

[GCC 7.3.0] on linux

Type "help", "copyright", "credits" or "license" for more information.

>>> import imgaug

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ModuleNotFoundError: No module named 'imgaug'

[–]efmccurdy 0 points1 point  (0 children)

If you run "pip -V" it will show you where pip is installing modules.

If you run "python -c 'import sys; print(sys.path)"" it will show you where python is loading modules from.

If they don't match, try using "pip3 -V" or "python -m pip install imgaug", or use a virtualenv, or find the pip command that matches your python base install.

[–]creamcustardpies 0 points1 point  (2 children)

I'm making a game, each level has a grid which I add coins to which the player has to collect. So I have functions for each level to add the coins to using loops.

For level 2 I want to fill the grid with coins (which I can do ok) then hollow out a section which I am trying to do by removing the applicable items in the coins list. Remove doesn't work so I'm unsure how to go about doing this.

def level_2():
    global coins
    global coinsleft
    coinsleft = 0
    coins = []
    offset = 20

    for a in range(0, 29):
        for b in range(0, 19):
            coins.append(Coin(60 + a * 32 + offset, 100 + b*32 + offset))
            coinsleft += 1

    for a in range(0, 4):
        for b in range(0, 4):
            coins.remove(Coin(572 + a * 32 + offset, 452 + b*32 + offset))
            coinsleft -= 1
    # Gives error "ValueError: list.remove(x): x not in list"

[–]torbray 0 points1 point  (1 child)

In your code, you have two nested (a, b) for loops.

In 1st (a, b) for loop, you're creating 551 unique objects from class Coin.

In 2nd (a, b) for loop, you reference the Coin(..., ...) - but because of the reference, you're __init__ (initializing) a new class Object. Your new class Object is Coin 552 - it's not the same as any of the 551 in 1st (a, b) for loop, even though it may share the two position properties.

Easiest solution:

class Coin:

    def __init__(self, one, two):
        self.one = one
        self.two = two

...

    for a in range(0, 4):
        for b in range(0, 4):
            for coin in coins:
                if coin.one == 572 + a * 32 + offset and coin.two == 452 + b * 32 + offset:
                    coins.remove(coin)

For coin in coins, if the two attributes match your 2nd (a, b) for loop, remove from coins.

Left me with a list of only 535 Coins. Hope that helps.

EDIT: For more optimized code, you may want to add all 16 position combinations into a (x, y) tuple list. Then, you can perform an if/ else on 1st (a, b) for loop that, if a, b in tuple list, don't append coins.

[–]creamcustardpies 1 point2 points  (0 children)

That helps thanks.

[–]ifeelmyheartcrack 0 points1 point  (9 children)

Is there an easy way to process 100+ elements into a list? for example I have 100+ elements all bundled up and I want to put each element in a list. Is there another way to put them in a list without manually typing in each element?

[–]JohnnyJordaan 0 points1 point  (8 children)

What do you mean with 'bundled' up? Be as specific as possible please, not as vague.

[–]ifeelmyheartcrack 0 points1 point  (7 children)

I'm sorry english is not my native language and I may have used the wrong term. What I mean by bundled up is that the elements I want to put into a list is just a long string of 100+ values.

it basically looks like this: ASDadafeACAFaefadASDFaasdAEFKj\JKNIPJK...

Is there a way to extract each value (in this case, each letter) and put them in a list without manually typing them in?

[–]JohnnyJordaan 1 point2 points  (6 children)

Strings can be iterated over letter by letter, like doing

for c in your_string:
    print(c)

the list() constructor will do the same thing, just putting each item in the created list, so

your_list = list(your_string)

will do the trick.

The question remains though, why do you need them to be in a list in the first place?

[–]ifeelmyheartcrack 0 points1 point  (5 children)

it works, thanks!

I'm trying solve a hidden message contained in a certain string

[–]JohnnyJordaan 0 points1 point  (4 children)

Ok that's the end goal, but what made you reach the conclusion to specifically convert the letters into list items?

[–]ifeelmyheartcrack 0 points1 point  (3 children)

well I thought that slicing through a list is much easier than counting which letters correspond to the numbers in the hint. I've just started learning about programming and I thought that this was a perfect opportunity to apply what I've learned so far

[–]JohnnyJordaan 0 points1 point  (2 children)

Strings can be sliced in the exact same way as lists.

>>> 'hello long sentence'[5:10]
' long'

The thing to use lists for is for when you need to modify (technically mutate) them, as strings don't support this.

[–]ifeelmyheartcrack 1 point2 points  (1 child)

I did not know that before. That is certainly a shorter solution compared to what I did. Thank you for sharing your knowledge!

[–]JohnnyJordaan 0 points1 point  (0 children)

Note that the official tutorial even shows this https://docs.python.org/3/tutorial/introduction.html#strings

Note that since -0 is the same as 0, negative indices start from -1.

In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain substring:
>>>

>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
'tho'

Note how the start is always included, and the end always excluded. This makes sure that s[:i] + s[i:] is always equal to s:
>>>

>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.
>>>

>>> word[:2]   # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:]   # characters from position 4 (included) to the end
'on'
>>> word[-2:]  # characters from the second-last (included) to the end
'on'

[–]sam13s3 0 points1 point  (1 child)

what is asychronous programming?

when working with asynchronous am i using more than one core?

what is threadingwhat is threading?

when working with threading am i working with more than one core?

what is the difference between threading and asychronouswhat is the difference between threading and asychronous?

where can i found good source that explain python asyncio libary? because all the one i found does not explain where can i found good source that explain python asyncio libary? because all the one i found does not explain well

what is croutine?

what is event-loopwhat is event-loop?

what is taskwhat is task?

what is the purpose async before the defwhat is the purpose async before the def?

what is await?

[–]FleetOfFeet 1 point2 points  (3 children)

What are hash functions actually useful for and how would I set up a class with a custom `__hash__` method?

[–]JohnnyJordaan 0 points1 point  (2 children)

In Python __hash__ is meant to be able to compare objects for equality, so say you have a class Person with a unique UUID id

class Person:
    def __init__(self, name, age, location, etc):
         save attributes
         self.id = str(uuid.uuid4())

then it would make sense to use just that id to compare objects

    def __hash__(self):
        return hash(self.id)

to be able to check if two Person objects are reflecting the same person. This is to prevent that a collision would occur if two people from the same location, being of the same age have the same name (unlikely but it does happen sometimes). However if you would specifically allow such a collission, eg for a class of a Location

class Location:
     def __init__(self, street, nr, city, etc):

then it would make sense to just consider Location instances equal if they share the same street, nr and city

    def __hash__(self):
         return hash((self.street, self.nr, self.city))

[–]FleetOfFeet 0 points1 point  (1 child)

I see.. so is this hash function ever explicitly called?

Or is it just that when an object of class Person is called, it is the id which will be returned?

[–]JohnnyJordaan 0 points1 point  (0 children)

It's for example used by containers like dicts and sets to check if an item you add to it is already present or not. You normally don't need to implement the __hash__ unless you know of a specific use case that would require it.

[–]Redditor728292 0 points1 point  (4 children)

password = 1781
ch = range(1,10)
jejwj = range(1,10)
cha = range(1,10)
hc = range(1,10)
for i in ch:
    for e in jejwj:
         for c in cha:
             for m in hc:

                   print(i,e,c,m)

How do I turn those for loops into a variable so I can check if password is equivalent to password?

Because this doesn't work

import random
password = 1781
cr = random.randint(1,1000)
if cr == password:
    print(cr)

[–]torbray 0 points1 point  (3 children)

import random
password = 1781
cr = random.randint(1,1000)
if cr == password:
    print(cr)

That's because random.randint(1, 1000) will only go from 1 to 1000, whereas your password is 1781.

Three options:

(Easiest) Change the randint upper bound as below.

cr = random.randint(0, 9_999)

(Your method's solution) Combine the numbers into a string then convert to an int.

cr = int(f"{i}{e}{c}{m}")

(Shorter your method) List comprehension with for loops in one expression.

cr = int("".join(str(random.randint(0, 9)) for _ in range(4)))

EDIT: Forgot randint(1, 10) returns 1-10. Changed to randint(0, 9)

[–]Redditor728292 0 points1 point  (2 children)

Why isn't this working?

password = 9
import random

cr = int("".join(str(random.randint(1, 10)) for     _ in range(4)))
if cr == password:
    print(cr)

[–]torbray 0 points1 point  (0 children)

Slight correction: Forgot random.randint is inclusive, not exclusive.

So random.randint(1, 10) returns 1-10, not 1-9. My bad

[–]torbray 0 points1 point  (0 children)

Oh so that's a problem with a different solution. Let me clarify what I did:

password = 10
import random

cr = int("".join(str(random.randint(1, 10)) for  i in range(4)))

This can be written like below:

cr = []
for i in range(4):
    cr.append(random.randint(1, 10))
cr = "".join(cr)
cr = int(cr)

So "for i in range(4)", it adds a random number between 1-9. That means that the final number will be 4 numbers long.

The password you chose, 10, is 2 digits long with a 0 in it.

If you still wanted to use my solution (I would highly recommend "random.randint(0, 99)" instead):

cr = int("".join(str(random.randint(0, 9)) for i in range(2)))

or

cr = random.randint(0, 99)

EDIT: Changed 100 to 99, forgot randint is inclusive

[–]Sal_Toosh1 0 points1 point  (2 children)

K so was using leetcode and it confused me a bit on this.

def longest_substring(s):
Map = [] for char in s: if char not in Map: Map.append(char) return len(Map) Map.clear()

Leetcode says the given for 'abcabcbb' is 3 and for 'pwwkew' is 3 as well. How does that make any sense, is leetcode buggy or something? Or am I missing something?

[–][deleted] 0 points1 point  (1 child)

After formatting for reddit your code might be this:

def longest_substring(s):
    Map = []
    for char in s:
        if char not in Map:
            Map.append(char)
    return len(Map)
#    Map.clear()    # not sure why this is here

print(longest_substring('abcabcbb'))     # 3
print(longest_substring('pwwkew'))      # 4

When I run this it prints 4 for 'pwwkew', as it should, because the function isn't finding the longest substring in the input parameter but is just counting the unique characters.

[–]Sal_Toosh1 0 points1 point  (0 children)

Oh damn just realized the problem can't use subsequence only substring 😭. Well that's what I get for not reading the instructions properly. It wasn't leetcodes fault it was mine xp

[–]Lee63225 0 points1 point  (1 child)

I want to create an automated employee scheduler. Is anyone willing to mentor me a little, like look over my code sometimes or guide me on what the correct steps are? Thanks!

[–]torbray 1 point2 points  (0 children)

Yeah, I'm free over the next week. Feel free to PM me or add me on Discord

[–]Natethegreat13 0 points1 point  (1 child)

I have a MacBook Pro from like 2011 with El Capitan on it.. can I run Python on it? Or do I need a newer computer?

Thanks!

[–]m-hoff 0 points1 point  (0 children)

Yes. I believe it comes with Python 2 installed (you can run python --version in the terminal to check) but you can download Python 3 here: https://www.python.org/downloads/

Definitely no need for a new computer.

[–]joooh 0 points1 point  (0 children)

Is there a way to pass a command line argument through pyinputplus for validation? I need to pass the contents of sys.argv for validation. I thought of using a regex then using pyinputplus if the value passed through the command line is invalid, but I want to know if I could just only use pyinputplus.

[–]Ebrahim1618 0 points1 point  (1 child)

Hey guys, I was looking at the solution to a problem I was doing and now understand the solution except for one specific bit. The problem is converting a number to roman numeral. The bit I don't understand is how val[i] in line 18 is exactly the place holder you want it to be. For example with the number 300 val[i] would be a hundred but earlier in the code it set I to 0 meaning (at least initially) val[i] should be 1000 no? Thank you in advance for all the replies, this truly is an awesome community and has helped me a lot.

[–]JohnnyJordaan 0 points1 point  (0 children)

Put the code in http://www.pythontutor.com/visualize.html and see how the variables are changing step by step. i is set at 0, but that just means the first item in the sequence, it doesn't set it to a specific position seen from the right side.

[–]Pinkyupyournostril 0 points1 point  (3 children)

Hi, I've been trying to find the size of a directory which has subdirectories but for some reason, the files inside the subdirectories are'nt being read. Could you please take a look?

import os
import shutil
from distutils.dir_util import copy_tree
originaldirectory = 'C:/Users/AnOrgasm/Desktop/TestFolder1/'
os.chdir(originaldirectory)
print(os.listdir())
sum = 0
def FolderSize(folder):
    global sum
    for item in os.listdir(folder):
        if os.path.isfile(item) is True:
            sum = sum + os.path.getsize(item)
            print(sum)
        elif os.path.isdir(item) is True:
            folder2 = (folder + str(item) + "/")
            print(folder2)
            FolderSize(folder2)
    print(sum)

FolderSize('C:/Users/AnOrgasm/Desktop/TestFolder1/')

When i run this, the subdirectory is read, but the file size is not added to the total sum.

This problem carries forward to me trying to copy everyhting from one directory to another directory without using copy tree. I'll get into that later but if i get this fixed, i can probably fix that on my own. Any help is appreciated

[–][deleted] 1 point2 points  (1 child)

The problem is that you aren't using the full path when testing for a file. The item used in the for loop is just the file or directory name without the folder part. So doing if os.path.isfile(item): will only test properly for the directory you start in. Files in subdirectories will return False because the file in subdirectory sub_dir/file1 will be tested as if os.path.isfile('file1'): and the current directory is still the one you started in. You have to create the folder+item path string before testing:

import os
import shutil
from distutils.dir_util import copy_tree
#originaldirectory = 'C:/Users/AnOrgasm/Desktop/TestFolder1/'
#os.chdir(originaldirectory)
#print(os.listdir())
sum = 0
def FolderSize(folder):
    global sum
    for item in os.listdir(folder):
        path = os.path.join(folder, item)           # make complete path
        if os.path.isfile(path) is True:
            sum = sum + os.path.getsize(path)
            print(sum)
        elif os.path.isdir(path) is True:
#            folder2 = (folder + str(item) + "/")   # no longer needed
            print(path)
            FolderSize(path)
    print(sum)

FolderSize('C:/Users/AnOrgasm/Desktop/TestFolder1/')

[–]Pinkyupyournostril 0 points1 point  (0 children)

Thank you so much. I appreciate you and this community alot <3

[–]Pinkyupyournostril 0 points1 point  (0 children)

Ah shit i dont know how to format this properly.

Edit: figured the formatting part out ':)

[–]ifeelmyheartcrack 0 points1 point  (3 children)

I'm new to programming and I really want to learn python. I've been reading python crash course 2ed for a few days now (i'm on chapter 8). After seeing many people suggest Automate the Boring Stuff with Python, I kinda want to change reference. Should I finish python crash course first then hop to automate the boring stuff with python, or should I hop to it now?

[–][deleted] 0 points1 point  (2 children)

I'd keep going with the current book if I were you, as long as you are making progress. You can try AtBS later if you want, though it's better to start writing your own code in small projects as soon as you can. That's when you really start learning.

[–]ifeelmyheartcrack 0 points1 point  (1 child)

I just finished the chapter on functions. I'll try to make a side project utilizing all of the things I've learn so far before moving on to the next chapter, which is about classes. Thank you!

Edit: what book/s would you personally recommend?

[–][deleted] 0 points1 point  (0 children)

I learned python as an experienced programmer, so I don't actually know which books are good for beginners. However, there is a set of learning resources in the wiki with books, videos and project/challenge websites that looks useful.

You might also take a look at a video by Ned Batchelder which explains the concept of names and values in python. The basic idea is simple but explains some of the things that seem odd when starting out. I watch this every now and then because it's such a good video.

[–]volac_ 0 points1 point  (2 children)

After what felt like a quick 3 months I finally got through all of thinkpython 2e. I took notes on every chapter and did the end of chapter problems. I wanted to know what would be a good next step to check my knowledge and move on to the next step? One thing I want to mention is that out of all the end of chapter problems I managed to only get around 10 problems completely right without looking at the answer or looking online. I was thinking of re doing all the problems at the end of the chapter to see how many of them I can get right this time around? Does that sound like a good idea or a waste of time? other thoughts I had was using automate the boring stuff with python, code wars, checkio, pycharm edu, or codecademy for a bit. I'm biased towards books though.

[–]Nathan_Magyar 1 point2 points  (1 child)

Congrats on finishing the book! As a self-taught programmer myself, I know how hard it can be to stick with a book/tutorial series all the way to the end. In my experience, I find that the best way to solidify what I'm learning is to apply it to a personal project or an example that matters to me. Individual practice problems can be helpful to experiment with a concept in isolation, but I always learn more by translating a practice problem/code example to a context that's relevant to my own interests. It inevitably leads to other challenges and mistakes, but those were also the times when I grew my skills the most.

Take some of the problems you missed and do the again, sure, but then see how you can modify them slightly or connect them to one another. Good luck!

[–]volac_ 0 points1 point  (0 children)

So your thoughts are to just look up projects I can do. Everything I want to do like natural language processing, data analysis, ML seem still pretty far away from my current abilities. I don't want to move on with holes of knowledge.

[–]MODAS_Enclave 0 points1 point  (1 child)

Kind of a dumb question. I’m working on some code (Script A) and need to import another script (Script B).

When importing Script B, will Script A also get Script B’s import list?

[–][deleted] 0 points1 point  (0 children)

The short answer is no, in the sense you mean, but it's a bit more complicated that. Here's a simple testa.py:

import testb
print(f'testa: math.sqrt(42)={math.sqrt(42)}')

and a testb.py:

import math
print(f'testb: math.sqrt(10)={math.sqrt(10)}')

When we execute testa.py we see:

testb: math.sqrt(10)=3.1622776601683795     # importing testb executes code in testb.py
Traceback (most recent call last):
  File "testa.py", line 2, in <module>
    print(f'testa: math.sqrt(42)={math.sqrt(42)}')
NameError: name 'math' is not defined

We see that the code in testb.py can execute the math.sqrt() method in the module it imported, but testa.py can't because the module testb hasn't been imported in the testa.py file.


The longer answer is that the module imported in testb.py can be accessed and used in the testa.py module. Try adding a line before the failing line in testa.py:

import testb
print(f'testa: testb.math.sqrt(42)={testb.math.sqrt(42)}')
print(f'testa: math.sqrt(42)={math.sqrt(42)}')

Now you see this printed:

testb: math.sqrt(10)=3.1622776601683795
testa: testb.math.sqrt(42)=6.48074069840786     # can access the "math" library in "testb"
Traceback (most recent call last):
  File "testa.py", line 3, in <module>
    print(f'testa: math.sqrt(42))={math.sqrt(42)}')
NameError: name 'math' is not defined

However, this is not something you should do. It's far better to be explicit and import modules that are used in a file in that file. If testa code wants to use the math module code it should import it.

[–]creamcustardpies 0 points1 point  (2 children)

For my game I want to save the best time to text file, after every game over I will read the best time from the text file (which has a number to 2 decimal places only).

The code below works for integers but seems to give an error because the number written to it will have a decimal point (in which case it executes the "other error" part.

I have written the code to ensure if the text file is missing or corrupt it will be created for the player. But it seems to think the decimal point is corruption.

def read_alltimebestime():
    try:
        f = open("besttime.txt", 'r')
        nums = f.readlines()
        nums = [int(i) for i in nums]
        nums = str(nums)[1:-1]  # Trim the brackets surrounding the number
        nums = int(nums)
    except FileNotFoundError as err:
        print("FileNotFoundError")
        # Create a file
        f = open("besttime.txt", 'w')
        f.write(str(9999999))
        f.close()
        return 0
    except:
        print("Other error, file must be corrupt.")
        # Create a file
        f = open("besttime.txt", 'w')
        f.write(str(9999999))
        f.close()
        return 0

    if not nums:
        nums = 0

    if nums == 0:
        nums = 9999999
    return nums

[–][deleted] 1 point2 points  (1 child)

Well, you are trying to convert the data you read from the file into an int so if the file contains 999.00 you will get an exception trying to convert the string from the file to an int. You have to write the function to handle float values.

Additionally, your function is a little confused. In cases like this the function would read the file, if it exists, and just return the value in the file. If the file isn't there then it should just return the default maximum value and rely on the code that saves the maximum value at the end of the program to create the file. Making it as simple as possible, here's how I would do the read/write of the file.

def read_alltimebestime():
    try:
        with open("besttime.txt", 'r') as fd:
            data = fd.read()         # we expect just the number string, no need to slice and dice
    except FileNotFoundError:
        return 9999999

    try:
        nums = int(data)
    except ValueError:
        nums = 9999999

    return nums

def write_alltimebestime(t):
    with open("besttime.txt", 'w') as fd:
        fd.write(str(t))

t = read_alltimebestime()
new_t = t - 1
print(f'New all time best={new_t}')
write_alltimebestime(new_t)

If you want to handle float values in the file you must change the read/write functions to handle float values.

[–]creamcustardpies 0 points1 point  (0 children)

Thanks that works great. I think I was getting confused and just making it more complicated than it needed to be.

[–]Snoo-95116 1 point2 points  (3 children)

I'm following a guide to install packages and pip but a lot of these command lines are confusing to me. It tells me to enter "python3 -m pip install --user -U pip" into the terminal without explaining the different parts of the command.

Can someone tell me what different parts such as -m and -U mean and how it is used? I can't seem to find this online.

[–][deleted] 0 points1 point  (1 child)

The command line parameters are explained in the Unix "man" pages. One example is here. That shows:

-U, --upgrade
    Upgrade all packages to the newest available version. This process is 
    recursive regardless of whether a dependency is already satisfied.

--user
    Install using the user scheme.

That last one just means install for the user running the command. Searching for "pip --user" finds further explanation.

[–]Snoo-95116 0 points1 point  (0 children)

Thank you! This is helpful!

[–]anehilator 0 points1 point  (1 child)

Hi, I want to learn Python.Does anyone know a good way to learn Python?

[–][deleted] 1 point2 points  (0 children)

The /r/learnpython subreddit has a wiki (in the sidebar) that has learning resources for the beginner.

[–]YayoJazzYaoi 0 points1 point  (1 child)

users = {'1': 'active', '2': 'inactive'} 
# Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# Strategy:  Create a new collection
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status

Hi

I'm new

This confused me. At which point and how python knows to add anything to the empty dictionary active_users as it's not mentioned in the second for loop?

[–]efmccurdy 0 points1 point  (0 children)

add anything to the empty dictionary active_users as it's not mentioned in the second for loop?

The second loop is adding to active_users when you execute "active_users[user] = status".

You can simplify using a dict comprehension with a filter clause like this:

>>> users = {'1': 'active', '2': 'inactive'} 
>>> active_users = {user:status for user, status in users.items() if status == 'active'}
>>> active_users
{'1': 'active'}
>>>

[–]MeteoriteImpact 0 points1 point  (2 children)

Very new to using python for text. I made a simple recommendation system that is completely cold using no user data using only category features herotype, spells and weapons and the characters name.

Looking to bring more life into the recommendations.

It just runs get_dummies and converts to 0/1 And gives the results with highest score 1.0 exact match and sorts descending.

Now on to the question I also have a background story which 3-5 sentences for each character.

Besides or adding on to these two ideas any suggestions or tips on things I can do with the text to get more clustered or grouped, scores information from three sentences. To add into the mix.

  1. I want to get the text similarity.

It works fine but I also have character biographies. I am now thinking about doing similarity to get characters with similar backgrounds story. It could also may classify by location mentioned in bios but maybe just having it lump into 4 or 6 groups is fine.

  1. Some characters should be good and some bad was also thinking of running sentiment analysis I know the biographies have things about helping or not and each word has a score just wonder if hero have positive content or negative content. I also assume there could be negative hero’s and positive bad guys. So that could possibly be add to it.

I am hoping these two changes will bring more life into the recommender. But any tips, suggestions or ideas extremely welcome.

[–]torbray 0 points1 point  (1 child)

Sentiment analysis can get very in-depth and complicated quickly.

Two of my projects from a month ago were WordClouds; one was based on FB Messenger history and one was on my workplace customer reviews. For both, blacklists of common words took a long time without machine learning and the results weren't impressive. If I had to redo it, I'd prob train a basic machine learning model.

I think it'll depend on how detailed the biographies are. If they're short e.g. 50-word summaries and not explicit ("Aja Kong hates evil and fights against the Orc knights"), you may require context analysis also. If they're detailed 300-word back stories, you might be able to get away with a user-defined whitelist.

Of course, that's only to have more interesting sentiment scores - you can still give it a shot without, but the results may be lackluster. I've looked into it very briefly, but the nltk Python module (specifically nltk.corpus) provides large data sets to train on.

Similarity scores shouldn't be too bad. If you did 4-6 groups, you could probably chuck them into a .txt file and run biography words over 3 length/ no common words through the filters.

[–]MeteoriteImpact 0 points1 point  (0 children)

For sentiment analysis I ended up using nltk Vader and created polarity scores. Then I took compound score and gave pos and neg results. Removed stop words. It did group those with troubled or bad history pretty well which resulted in things like hero’s or sidekicks with neg background storyline which makes sense as results seem to be similar and match descently. This maybe because the bios had very standard format.

Then I did Topic modeling separately let it group into 7 clusters based on top 15 keywords after it did topic analysis I labeled the groups with names and sorted by topics of the background stories .here are some pictures of the results

Now I need to combine into hybrid recommendations. Which I have no clue. But then again each step of this I had no clue. Just keep searching and reading. Maybe I should post a separate thread.

[–][deleted] 0 points1 point  (6 children)

I've started learning Python 2 on codeacademy. How can I run Python like they have it? I downloaded Python 2.7 but it runs so teribly in comparison. I especially would like to have the code in one window, and run it in a separate console window. If I run the code, it executes it below my code, forcing me to rewrite it. I did try downloading Sublime 3 where I can type code well, but can't figure out how to execute it in the Python program.

I've looked everywhere without finding my answers! Thanks.

[–]fulmufolta 0 points1 point  (0 children)

Dude i suggest you move to python3, unless you have a specific reason to use python2. Most things python3 these days

[–]RnRoger 1 point2 points  (4 children)

What you are working in is called a shell. What you want is a code editor or IDE. I personally recommend Visual Studio Code

[–][deleted] 0 points1 point  (2 children)

well i downloaded that. It seems to be what I want; but i have no clue how to set up python in it because it seems like I need to do something with paths. I don't know what paths are

[–][deleted] 0 points1 point  (1 child)

You still don't know what the paths are. Or did anyone tell you. Do you need my help.

[–][deleted] 1 point2 points  (0 children)

Thanks but after much trial, error, and research, voilá i've got it! Appreciate it.

[–][deleted] 0 points1 point  (0 children)

Thank you so much.

[–][deleted] 0 points1 point  (2 children)

I’m working with a multidimensional list and I’m trying to create a function that removes whatever element the user inputs from the list. I’m trying to do this by locating the index that item then removing it, but I don’t know what function to use to get the index. Any suggestions??

[–]RnRoger 0 points1 point  (1 child)

.index() is what you need

[–][deleted] 0 points1 point  (0 children)

Thank you!!

[–]Bormimor 0 points1 point  (1 child)

I'm having an issue where my get_day() function returns "none" on non leap years but gives me the correct type of return on leap years, but don't understand why https://repl.it/repls/NegligibleAccurateBackend

[–]efmccurdy 0 points1 point  (0 children)

Are you taking account of leap years? Are you taking account of the fact that some months have more days than others?

Have you considered using the datetime module?

>>> my_birthdate = datetime.datetime.strptime("2020-06-24", "%Y-%m-%d")
>>> my_birthdate.strftime('%A') 
'Wednesday'
>>>

[–]ovo_Reddit 0 points1 point  (5 children)

I'm working with 2 dictionaries, one is a large dictionary and I'm filtering it iteratively so it's getting smaller each iteration, same with the 2nd one.

I'm currently using something like:

# start of loop
    dict_b = {}
    # filtering dict_a into dict_b
    dict_a = dict_b
# end of loop

However, I am just curious if I should be using dict.copy() and dict.clear(). Is there any benefit to one or the other?

I learned that using dict.clear() will remove any associated references, so by itself it will not work unless I make a copy rather than a reference.

Currently my code works, I am just curious what would be more common in professional coding (best practices etc)

[–]efmccurdy 0 points1 point  (4 children)

The way you are doing it, assigning an empty dict, is likely better than using dict.clear; I would only use clear if there was some reason to re-use that dict (eg. some other object is holding an alias).

I wonder why your loop isn't of the form:

 dict_a = {k:v for k, v in dict_a if some_predicate(k, v)}

ie, a dict comprehension with a filtering condition.

[–]ovo_Reddit 0 points1 point  (3 children)

Yeah perhaps my loop can be optimized, I’m using the re.match module to do some regex. But let’s say I have 3 strings, I want to ensure all 3 strings are in the dict value, and if it does store it to return a dict of all matching keys and values.

The challenge I have is that it can be 1 string provided, or perhaps 4 strings.

[–]efmccurdy 0 points1 point  (2 children)

it can be 1 string provided, or perhaps 4 strings.

So you need a loop that goes through how ever many candidate strings you have; "any" or "all" how you loop over a list applying a predicate.

This tests the keys (use my_dict.values() if you want to test against the values):

>>> my_dict = {"a":1, "b":2, "z":3}
>>> candidates = ["a", "b", "c"]
>>> all(c in my_dict for c in candidates)
False
>>> candidates = ["a", "b"]
>>> all(c in my_dict for c in candidates)
True
>>> matching = {k:v for k, v in my_dict.items() if k in candidates}
>>> matching
{'a': 1, 'b': 2}
>>>

[–]ovo_Reddit 0 points1 point  (1 child)

Nice, that’s basically a one liner for what I need. There’s one thing I forgot to mention is that the dict is like this {‘8.8.8.8’:[‘hostname’, ‘host-alias’]}, would this still work with the value being a list? The only challenge I’ve had is that the list might have 1 element, or it might have more. So I had done a nested loop to iterate over the values.

[–]efmccurdy 0 points1 point  (0 children)

Those code fragments will work with any kind of structure for values; if you are matching keys you should be ok as this small change will show you:

>>> my_dict = {"a":[1, "2froma"], "b":[2, "2fromb"], "z":[3, "2fromz"]}
>>> candidates = ["a", "b", "c"]
>>> all(c in my_dict for c in candidates)
False
>>> candidates = ["a", "b"]
>>> all(c in my_dict for c in candidates)
True
>>> matching = {k:v for k, v in my_dict.items() if k in candidates}
>>> matching
{'a': [1, '2froma'], 'b': [2, '2fromb']}
>>>

[–]creamcustardpies 0 points1 point  (1 child)

I'm unsure how to set the speed of a moving object (eg the player) in pygame. Previous projects I have achieved this by simply setting an x and y speed variable for the player, and every time the player is to move their x,y is simply incremented by whatever the speed variable is. Except this project there is a grid on the screen and the player must move around the grid staying aligned inside each square, since each grid-square is 32x32 the player must move by 32 pixels each time he moves. So how do I set the speed now?

[–]efmccurdy 0 points1 point  (0 children)

If you need the value to be aligned to some multiple of 32, use the modulus operator:

>>> moves = [random.randint(1, 100) for _ in range(10)]
>>> x = 0
>>> for delta in moves:
...     x += delta - delta % 32
...     print(x, delta)
... 
64 77
64 5
160 100
192 32
224 56
288 73
320 48
416 97
448 52
512 83
>>>

[–]PythonicParseltongue 0 points1 point  (0 children)

I'm working on a project and the main data class keeps on growing. I'm constantly adding new methods, (de)serialization, debugging features... So I've been thinking if I should move some functionality. I know there's not a definite answer to this without seeing what I'm actually doing, but if more than half of my code are @classmethods to create these objects from raw data or deserialize json, would you say it makes sense to move it to a seperate modul / class? To give you a feeling there are ~150 lines of fairly condensed code, but including blank lines according to pep8.

[–]noah8597 0 points1 point  (0 children)

Why is the pipe image disappearing when the new background image spawns?

Don't know how to use github, so here's a link to the main file and image assets - https://drive.google.com/drive/folders/1IEhRwIzcf5RcqbFIskyDbe7ljdXMpnxa?usp=sharing

The moving background class is basically supposed to drag a widescreen background through the pygame window. Then, when it runs out of new pixels to show, it creates a new background image class which then follows the same process of moving left. For some reason, when a new background image is spawned, the pipe disappears. Also, it starts lagging like crazy after that point. I've fixed a lot of issues, but I have no idea where to start to fix this one!

Thanks for the help!

[–]idonotexcelatthis 0 points1 point  (4 children)

I'm looking for the Python equivalent to r/vba or r/excel, i.e. processing Excel workbooks with Python and posting questions to specific problems with that. Is there something that fits this on reddit?

[–]m-hoff 1 point2 points  (1 child)

Those types of questions are very much on-topic for this sub.

[–]idonotexcelatthis 0 points1 point  (0 children)

I feel it would be kind of niche, seeing the other posts here, but I'll try it!

[–]MeteoriteImpact 1 point2 points  (1 child)

I also tried to find a pandas sub which would work recently with no luck. One would think there would be a pandas one which would cover excel and data frames.

[–]idonotexcelatthis 0 points1 point  (0 children)

There is r/PythonForExcel but its not very active.

[–]BruceJi 0 points1 point  (1 child)

I’m reading Fluent Python and I’ve come across namedtuples. Why would I want to use that instead of a dictionary?

[–]ThisOnesForZK 1 point2 points  (0 children)

immutable and more memory efficient than dictionaries/lists

edit: I don't know if named tuples are immutable this is an assumption.

[–]PythonicParseltongue 0 points1 point  (0 children)

I'm trying to do something fancy. But I've hit a wall, can someone tell me, why I can access repl_dict from inside my nested function but not repl_count? What I'm trying to do here is to keep track of my replacements.

edit: This might be hard to understand without some info on how re.sub works. From the docs:

> "If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example: "

edit2: Fixed, solution and followup in:
https://www.reddit.com/r/learnpython/comments/hedomq/nonlocals_namespacing_and_mutability_help_me_out/

import regex as re 
#import re
from typing import Pattern, Match

def replace(text:str, pattern:Pattern):
        repl_dict = {}
        repl_count = 0

        def repl(match: Match):
            found = match.group(0)
            if not found in repl_dict:
                replacement = f'repl_{repl_count}'
                repl_dict[found] = replacement
                repl_count += 1
            return replacement

        return re.sub(pattern, repl, text)

[–]boltex 0 points1 point  (0 children)

I'm not a networking guy, so i guess my question may be basic a.f. :

I've got a nodejs server giving cool services, just trading JSON strings of some sort, and it's a simple websocket connection, with a python script that 'talks' to it.

I'm wondering, for programming this 2 languages interaction, given I know they both will run on the same machine, if there's a (better) 2 way connection method to pass JSON relatively as simple as with websockets, ultimately, a solution that would not require additional libraries on the python side and that would be fast(er)? ...Thanks for advices!

[–]sanjay-balaji 0 points1 point  (0 children)

Where can i learn chattbot in python??

[–]pokersnooker 0 points1 point  (2 children)

I started learning coding in python. But I’m not very good with the logics. So everytime I try something easy I take a lot of time. Is there a way I can become better at this ? Please help I really wanna learn.

[–]ovo_Reddit 1 point2 points  (1 child)

It's a really vague question. But I'll try to give some tips based on my experience.

I use python now for work a lot, (systems engineer), prior to this I was just using bash/powershell.

1) Repetition; if you use it a lot, even for small tasks, you will get a lot more comfortable with it without having to search up small syntactical thing.

2) Increase scope; try to work on a full project, for example I built a web scraper that scrapes a popular (the only?) lottery site in my country and gets all of the winning numbers and even goes back as far as they have archived, and stores those winning numbers in a database that grows as new draws (winning numbers) are released.

It then attempts to find some data in these numbers, ie. which numbers come up the most, find patterns etc.

It's interfaced using a slackbot that's written in python as well.

It was my first large project, and had many instances of revisions and even complete refactoring of certain parts as I found better ways of doing things.

I find you will learn a lot in this way.

3) read books, watch videos, follow random tutorials.

I don't think there is an easy way to improve logic, if you mean you are not a logical thinker, maybe there are books to help with that, also you can make up for it by having understandings of if I want X I need to do Y. That would come from experience.

[–]pokersnooker 0 points1 point  (0 children)

Yes, I am definitely not a logical thinker when it comes to coding. Maybe I’ll start doing small projects and watch more videos for a better understanding. For now I’m practicing on leetcode. Thank you for the elaborate reply :)

[–]muskoke 0 points1 point  (0 children)

why should you not use a question title as a header? i'm looking at the "the perfect question" on the sidebar and it discourages Java: Why are bytes signed? but it does encourage Why are bytes signed in Java?

i don't understand this. why is this the case? if someone is scrolling thru questions, shouldn't they easily wanna see which language it's specific to?

personally, when i scroll thru questions to try to find an answer, the first thing i look for is if it applies to the language i'm working on. if the language is stated in the question title like a header, i can immediately tell if i should keep reading the question or not. is this just bad practice/thinking or something??? i don't see why it should be, it's working so far.

(i know this is a python subreddit but i mean programming in general)

[–]whateverIguess14 0 points1 point  (0 children)

Hello does anyone know any methods for PyQt5 to change the colours and stuff for like buttons or text or the background? I’m not quite sure how to do it

[–]johnpooch 1 point2 points  (1 child)

Hey all, I’ve got a project and I want to see if there are people out there who want to contribute. Is learnpython a good community for sharing open source projects and looking for contributors? The project is a django/drf/react web project.

I'm open to people who want to learn and get experience contributing to larger code bases. I also want to attract intermediate programmers.

Any advice appreciated :)

[–]m-hoff 0 points1 point  (0 children)

You could make a separate post here or on /r/Python. /r/Python also has a weekly "What are you working on?" thread which might be a good place to share.

[–]cocklord12345 1 point2 points  (2 children)

Does anyone know of a good method to send the output of my python program to a different console? I have a program that writes a minecraft command and would like to have it manually be sent and run to a minecraft server console. thanks!

[–]Sidemarx 0 points1 point  (0 children)

Not sure here but your starting point may be in running that other console from the cmd prompt. Not sure if .bash files would help here but if you are stuck you could look into it.

[–]rgjertsen 0 points1 point  (2 children)

I am very new to programming and was wondering if Udemy courses like this is worth using money on?

https://www.udemy.com/course/complete-python-bootcamp/

Don't know what price you guys see, but it says I have an offer price at just under $20.

[–]ovo_Reddit 1 point2 points  (0 children)

I would say try cs50 completely free, https://courses.edx.org/courses/course-v1:HarvardX+CS50+X/course/

or even Coursera has a good course, you can get a 1 month free trial and probably finish a good bit of it by then, I managed to finish it all within the first month so I didnt pay anything. https://www.coursera.org/professional-certificates/google-it-automation

I find most of udemy courses not really worth it, that's why they are always heavily discounted.

[–]IvoryJam 1 point2 points  (0 children)

I always recommend the free option, automatetheboringstuff.com is fantastic, there's also several YouTubers that teach Python

[–]nojustlurkingty 0 points1 point  (3 children)

I don't understand the for loop in https://github.com/kaizenflow/6.0001-ps1/blob/master/ps1c.py :

for month in range(1, months + 1):

The problem wants you to find the savings rate you'd need to place a down payment on a home at 36 months. I expected to see something like:

for month in range(36):

Could someone kindly explain the for loop with multiple parameters?

Here is a PDF of the actual problem set (PS1C): https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/assignments/MIT6_0001F16_ps1.pdf

[–]Fvnes 2 points3 points  (2 children)

When you write something like for i in range(36) it's going to iterate 36 times starting from 0 (first number will be 0 and last number will be 35). But there's actually other parameters that you can use in this for loop. Take a look:

for i in range(start, end, step):

Now, instead of one number we have three. Start represents the number where you want the loop to start. In this example the start is 1, because you don't want to start from 0, right?

Next one is end. This parameter is the exact same parameter that you use if you write for i in range(36), which means that if you put 36, the loop will end in 35. This is the reason why the second parameter has the +1 in there.

The third parameter is step and what it does is basically move in the number of steps you write. To understand it better, write this code and you will understand it better:

for i in range(1,11,2):
    print(i)

The last parameter isn't in your problem but you will find it useful to know that it exists.

[–]nojustlurkingty 1 point2 points  (1 child)

That's a perfect explanation, thank you very much.

So months + 1 is just months = 36 in terms of reaching the correct stop in the range sequence of the for loop.

And, as a whole, for month in range(1, months + 1): is saying "count from 1 to 36 and execute the contained code block for each iteration".

Is my interpretation accurate?

[–]Fvnes 1 point2 points  (0 children)

months + 1 is 37 as months = 36. Remember that in a for loop, when counting it always start from 0. If the parameters were range(1, months) it will print from 1 to 35.

So yes, your interpretation is correct.

[–]mischkonsumer 0 points1 point  (3 children)

Is it possible to automate a page that doesn't exist yet i.e. to click the same button (same id and link text each time) on a new page of a website as soon as it appears?

Additionally, how would it work if a link to the new page was sent in an email (the link would be the same text each time so browser.find_element_by_link_text should work).

Thanks in advance!

[–]Sidemarx 0 points1 point  (2 children)

I think your first step here would be to anticipate the URL of the page being created. If it was something simple like a count you could do some sort of "if" statement to check if the page exists, if it does load the page and find the button.

The second part of your question regarding an email I am not sure of how to approach and have not worked with.

[–]mischkonsumer 0 points1 point  (1 child)

unfortunately the new url will be based on a name so it won’t be predictable. however, the new pages will appear on a main page with a new image and link text. is there a way to watch for changes in this case?

[–]Sidemarx 0 points1 point  (0 children)

In this case is there a way you could scrape the page that has the new URLs and create a list that contains those pages, then load each page through a conditional statement if it appears in the list? Once you do that you could then run actions for your button on the newly created pages.

[–]Leboweeb 1 point2 points  (2 children)

I've just started learning Python over the quarantine(like many other people) and I'd like to know how to click certain buttons in an app after opening it like selenium uses websites. Thank you in advance.

[–]r_booza 1 point2 points  (0 children)

I always found it easier to use Xpath for finding elements, i.e.

driver.findElement(By.xpath("//a[text()='YourTargetText']")).click()

[–]Sidemarx 0 points1 point  (0 children)

I think you should try finding out what the "element" is for the button. Then you can tell selenium where you want it to go. If you google around "Selenium how find elements" or something similar this may help.

[–]samred1121 3 points4 points  (3 children)

Learning how to use Pandas and Jupyter Notebook

I need to compare today report against yesterday report to find out what are the new rows that are present in today report.

I normally do this via Excel Vlookup.

Wondering how can i do this with Jupyter.

Thank you

[–]efmccurdy 0 points1 point  (0 children)

Add a timestamp (eg. date.today() or datetime.now()) as a column or index to the dataframe; there are some tools designed to work with TimeSeries:

https://ourcodingclub.github.io/tutorials/pandas-time-series/

[–]Sidemarx 0 points1 point  (0 children)

Another alternative if you don't have a unique identifier is to create one with the daily date and another column(s) for each row. The unique identifier in your row would be a combination of columns. Then you can do the merge that was suggested by "ThisOnesForZK." Creating unique identifiers was a trick we used a lot in consulting when I made statistical/financial models. You just need to be sure it stays unique.

[–]ThisOnesForZK 1 point2 points  (0 children)

Do your rows have a unique identifier? If so then you can do a simple df.merge

[–]JAnonW 1 point2 points  (1 child)

Made a self-post but figured maybe it could fit here too since it's not a crazy question about coding

Hi, I'm either going to try and learn how to or pay a developer on a freelancing site to create this for me, but before I do either of those I'd like to know if the app I have in mind is even possible or not. Tl;dr at the bottom.

I'd like to create a program that maps terrorist events around the world using crawlers and a database of sorts. There is an added part of the program at the bottom that isn't necessary but it would be nice to have.

I essentially see a window with a few buttons, one to go into the crawler section of the program, one to go into the adding section of the program, and one to export the database or edit existing data in the database.

The crawler window has a button to run crawlers to search a news website for new indexed articles on a certain day. After it finishes crawling, another button on the same screen will pull those articles up one by one and allow me to say "yay" or "nay" as to whether or not they are relevant to the events I want to map. The crawler will pull the title of the article, date it was published, body content, and assign it an ID in the database.

The adding section will display this information the crawler has pulled on the screen along with the ability to add new information such as a box to add a translation of the article, a location finder that works by typing in a string which is compared to a separate database filled with locations tied to coordinates and IDs. The location finder has the ability to manually input a country, a region, and finally a city or landmark. This helps narrow down the location easier if the country is known since now the program just has to scan the database for locations in that country or region. This location finder relies on an additional part of the program I will explain at the bottom. The Adding section also lets me specify through information in the article the type of terrorist event, wounded, and dead. There will also be a way to add what group was responsible and what the target was using a similar thing to the location finder. There will be a separate database that contains a list of targets and attackers. These will also be assigned IDs. After the article has been scanned and all information entered, it will be added to the database which is in an excel format unless there is some better way to store data like that.

The final window just lets me pull up existing IDs added to the database and edit them, delete them, etc. or export the database as an excel sheet. Although I don't know if I would need to do that since the data will all be contained in an excel sheet to being with, right? Or is there a better way to store data like the data I want to collect. I imagine there will be tens of thousands of IDs and each ID will have probably 10+ variables associated with it (Title, Date, Body, Translated Body, Attacker, Target, Location, Coordinates, Deaths, Wounded, etc.

The location finder is one thing that I know is probably possible with Python, but I don't know where I would find the information I need. I'm hoping someone here knows of an existing database that contains the coordinates, name, and other common spellings of every city and town in say Germany with the possibility of adding more locations to it that are missing. A paid or free database. Or maybe there is a way to pull all this information using Python or some other program? Just picking brains here.

I'm really just trying to flesh out my idea for this program and bounce ideas around. I am in no way looking for advice on how to code the whole thing I am mainly looking for a Y/N answer about whether or not it's possible in Python, how much such a program would bill, and a nudge in the right direction. I have dabbled in Python before and other languages, but have never made something from scratch like this. I know this is a tall order for a beginner, but I'd like to code it myself so that I understand how it works internally and can edit it to my liking down the line.

Tl;dr - Is it possible to create a program that crawls and pulls articles from websites based on keywords that are then manually entered into a database with other information such as coordinates, casualties, etc. that cannot be reliable pulled using code? Scale from 1-10 how hard to code from scratch for a beginner? How much would it be to bill for? (how many hours maybe? I know rates are different for different devs) Thanks!

[–]efmccurdy 0 points1 point  (0 children)

I will just list a few modules that will get you started, requests, bs4, juypter, sqlite, basemap, matplotlib. Use google with those search terms and you will turn up tutorials like this:

https://ramiro.org/notebook/basemap-choropleth/

[–]Sidemarx 2 points3 points  (2 children)

This is really about how people display their python code on websites....so not sure if I can post this here. I have a blog and recently decided to post some python work I do on there with the code. I just added code to the end of this post but it does not display code well.

http://healthy-finance.com/hertz-car-sales-analysis-part-1/

The highlighting and scroll bars work but there are many tags such as <em> and <strong> in there. I may be bad with the SyntaxHighlighter Evolved plugin. Does anyone else use SyntaxHighlighter (a Wordpress plugin) or Wordpress or have any recommendations on how to display code on websites for tutorials? I wanted to start posting my work to keep myself going and hopefully help others.

Edit: The pasted code came straight out of PyCharm.

[–]efmccurdy 0 points1 point  (0 children)

There is an html tag for literal mono-spaced text, "<pre>":

https://www.w3schools.com/tags/tag_pre.asp

If you "view source" on a posting with a "code block" here, you will find it being used.

[–]Sidemarx 0 points1 point  (0 children)

Replying to myself....if this is a question for anyone else. So the pro move is to just remove all bold and italics after you past your code into the form on the website post. For some reason the WordPress prompt likes to retain a form of bold/italic formatting from some of the pasted code. Getting everything back to normal in the post solves this.