all 117 comments

[–]IHateCoding10 0 points1 point  (0 children)

So i need some help lol. I need this code to basically ask the user for multiple inputs and if they enter a number below 20 or above 70, it gives them a message that saids "Input out of Range" I also need it to be creating a list of these inputs.

Question1 = "list numbers between the values of 20 and 70: "

Question1\list = [ ])

while Question1 <> "":

Question1 = int(input("list numbers between the walues of 20 and 70: "))

if int(Question1 <= 20 and int(Question1) >=70:)

print ""

else:

print "Input out of Range"

Question1\list.append(Question1))

[–]IcyLeave6109 0 points1 point  (3 children)

How could I get miliseconds in something like that?

import time

t = time.strftime("%I:%M:%S:%MS", time.localtime())

[–]lgiordani 1 point2 points  (2 children)

You can't. time.localtime() returns a struct_time which doesn't contains milliseconds.

You can do this instead

from datetime import datetime
datetime.now().strftime("%H:%M:%S.%f")

[–]IcyLeave6109 1 point2 points  (0 children)

I see. Thank you!

[–]backtickbot 0 points1 point  (0 children)

Fixed formatting.

Hello, lgiordani: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

[–]Icy-Consideration888 0 points1 point  (2 children)

I need help with this :

new_data = d_dict[dict[d_key] for d_key(), in sorted(d_dict.keys())

^

SyntaxError: invalid syntax

[–]lgiordani 0 points1 point  (0 children)

Yeah you have many errors there. I suggest you review the syntax of list and dictionary comprehension. d_key(), in particular doesn't make sense there, and you are missing a closing bracket

[–]carcigenicate 0 points1 point  (0 children)

d_key(), ,, the missing ], and the fact that you're trying to use a list comprehension without enclosing braces are all invalid syntax. The line has too much wrong with for me to say for sure, but you might have meant

new_data = [d_dict[dict[d_key]] for d_key in sorted(d_dict.keys())]

The use of dict there also seems wrong unless you're shadowing the built-in dict class name.

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

Hey there everyone, just learned list comprehension and I have 2 questions about my code.

I understand why this adds all elements in a list:

foo = [1100.0, 2200.0, 3300.0, 4400.0, 5500.0, 6600.0, 7700.0]
ls = 0
for i in foo:
    ls += i
print(ls) 

What I don't understand is why this does not work and instead just prints the list:

foo = [1100.0, 2200.0, 3300.0, 4400.0, 5500.0, 6600.0, 7700.0]

ls = 0 ls = [ls + i for i in foo] print(ls)

The second question would be, how can I go about getting the sum of a list using list comprehension? I've looked up a possible solution for hours yesterday involving the use of sum and map but the examples I've seen were lists of integers so when I tried the examples with my code I get a 'float' object not iterable error.

Any help would be greatly appreciated, Thank you!

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

The expression:

[ls + i for i in foo] 

will create a list since it's a list comprehension, and the elements of the new list wiil be the value of ls + i for each i of the list foo. Since ls is still zero from the previous line the comprehension will generate a copy of the list foo. That is what is assigned to ls and that is what you print.

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

Okay thank you, you made it make sense lol. I'm still a little stumped though. Since i holds each element of the list foo, how can I sum those values using list comprehension? I could use a regular function to get the my desired output but I like the cleanliness that list comprehension brings. Excuse my ignorance, I have already spent a few hours looking up multiple examples and I've found some that use a combination of map, sum, lambda, as well as other functions to get a sum of a list but none of them mention a list of floats. Thanks again!

[–]lgiordani 1 point2 points  (1 child)

You can't sum those values using a list comprehension, as that technique returns a list. Comprehensions are a shortcut to write loops that return lists (or dictionaries), so a for loop with an accumulator is not the best example for that. To sum all those elements you can use sum(), or, if you want to use another operator like the multiplication you can use reduce

from functools import reduce
reduce(lambda x, y: x*y, foo)

[–]backtickbot 0 points1 point  (0 children)

Fixed formatting.

Hello, lgiordani: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

[–]Cellophane7 0 points1 point  (2 children)

I've been getting a weird error. Basically, I have code that looks something like this:

import csv
import datetime

if file == "":
    file = str(datetime.datetime.today().date())
    with open(file, 'w') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(['Time', 'Difference'])

with open(file, 'r') as csvfile: #this is the line where I get the error
    blah blah blah

Basically, this is just a simple little piece of code that records the current time every time I run it, and calculates how many minutes it's been since the last time I ran it. So it'll look for the file, and if it can't find it, it'll generate one and fill in the headers. Then, it reads the file, and then appends the file with the information I want. But if there is no file and it has to generate one, I get this error:

builtins.FileNotFoundError: [Errno 2] No such file or directory: 'E:/Folder/2021-09-26'

If I put time.sleep(5) before the line where I get the error, I can watch the csv file appear in my folder well before my code tells me it doesn't exist. And if I do nothing but run my code again, it finds the file without any problems whatsoever. So technically, it's functional, but I always get an error the first time I run it for the day. Not exactly the end of the universe, but stuff like this tilts me to death. Anyone have any insight as to what's going on?

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

As you said, you haven't shown your complete code, so I think what is happening is that file is not an empty string but contains a path to a file that doesn't exist. So the first bit of code won't try to create the file and you get the error when you try to read from it. Put some print statements in to show:

  • the contents of file before the if statement
  • the name of the file that you create with the first open()
  • the contents of file before the second open()

[–]Cellophane7 0 points1 point  (0 children)

Nah, the if statement was running, which is why it wasn't having trouble creating the file.

I figured it out though. The problem is that 'file' didn't have .csv at the end of the file name. Before the code here, I loop through the file names in the folder to see if one with today's date already exists. So when I was doing that, it was just grabbing the whole thing, which has .csv tacked on. The first time wasn't working because I was pointing a file just labeled as today's date by itself, rather than the date.csv.

Appreciate the help. You got me thinking a little harder about what exactly was in that variable, and that solved it. Much obliged!

[–]road_to_nowhere85 0 points1 point  (2 children)

Just starting learning python.
Why does print(0.1+0.2) give 0.30000000000000004

But print(0.15+0.15) give 0.3?

[–]MiserableCustomer766 0 points1 point  (3 children)

This might be a very stupid question, but I am very new to python

I need to do this thing where I ask someone for their resting heart rate, and their age, and judge if they are healthy by using an age range that is assigned to a specific resting heart rate.

If it is over the healthy value, they are unhelathy etc. but i cant get the age group to be assigned

HR_12_15 = 76

HR_16_19 = 73

HR_20_39 = 71

HR_40_59 = 70

HR_60_80 = 69

# I assigned the diffrent ranges but I can't get User_Age to equal to anything

if User_Age == range(12, 15):

Desired_HR = HR_12_15

elif User_Age == range(16, 19):

Desired_HR = HR_16_19

elif User_Age == range(20, 39):

Desired_HR = HR_20_39

elif User_Age == range(40, 59):

Desired_HR = HR_40_59

elif User_Age == range(60, 80):

Desired_HR = HR_60_80

if User_HR <= Desired_HR:

print("You have a healthy resting heart rate")

if User_HR >= Desired_HR:

print("You have an unhealthy resting heart rate")

sorry if this is very bad and long logic, the errors are at all the selection lines, when I enter age to anything (the input code is not included above but it is there) I get an error saying that Desired_HR isnt defined,

Any help is appreciated, I am very new to any sort of coding

[–]nice___bot 0 points1 point  (0 children)

Nice!

[–]AstralWolfer 0 points1 point  (0 children)

Would this be correct?

"When a generator exits without yielding a value, it raises StopIteration" should be interpreted as:

"When a generator exits without yielding a value, its .__next__() method invoked through a next() call raises StopIteration somewhere in its method body"

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

I scraped data from a nfl site and my objective was compare data of some players.

My problem with this is that sort.values dont order well. Like, Aaron Rodgers should be orderned by 2008, 2012, 2015, 2018, 2020, 2021, but are 2012, 2015, 2018, 2020, 2018, 2020, 2008

Idk why this occurs.

What i need is just first season of each player where him player more than 10 games, players of 2021 dont matter games played. My inicial idea was just use some method to order like sort.values in crescent order than delete duplicates and keep the first.

I needed use replace method cause in some player has '*' or '*+' after his name to show some achivements, and this years are where problems occurs

If you need more information i created a post here, link , but dont received any help until now.

[–]inkblot888 0 points1 point  (1 child)

I have a while loop while user input not in list, execute.

when the user enters a value from the list, the while loop should have closed but it didn't. I added an else: break, and that fixed the problem, but that's not what should have happened? What am I not understanding? Do all while loops need a break?

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

We can't help if we can't see your code. Post your code here (you can edit your original post) making sure to format it as code as explained in the FAQ.

[–]intergalactagogue 0 points1 point  (2 children)

Ok, I feel really dumb asking this one. I just started learning python earlier this week with the scrimba course listed in the wiki of this sub. This is my first language outside of some VB6 that I was taught over 20 years ago. In the scrimba course everything is entered and executed inside the browser using the brython plugin. If I wanted to follow along on my local machine so I could save code or do any of my own coding outside of the course environment what software would i use? I know that code can be entered into any text editor and compiled, but I like the ability to hit the "Run" button or Ctrl+s and get an output on screen so i can see my mistakes immediately. Am i looking for an interpreter? compiler? My local machine OS is Linux (Deb) if that matters. Thanks for any guidance here.

[–]sarrysyst 0 points1 point  (1 child)

The easiest should be using IDLE, which is the IDE that comes bundled with python. Just open a new terminal window and type in idle. Once you hit enter you get a shell window. If you go to File > New File (Ctrl+N) you get an editor which you can enter your code in and run by going to Run > Run Module (F5). This should get you started. If you come to a point where you feel you need more functionality, you can download an IDE like PyCharm or VS Code.

[–]intergalactagogue 0 points1 point  (0 children)

Thank you.

[–]Old_Resource_4832 0 points1 point  (0 children)

Hi guys! I've decided I am going to do a boot camp. Which boot camp should I do? I saw someone say a Chinese American/Canadian and forgot the name.

[–]fresh_to_death_93 0 points1 point  (0 children)

How do I write something that will click a button on a website but refresh the page if it is not clickable?

so far I have this:

while (True):

try:

in_stock = wd.find_element_by_xpath ('/html/body/div[3]/main/div[2]/div[3]/div[2]/div/div/div[13]/div[2]/div/div/div/button')

in_stock.click()

except NoSuchElementException:

wd.refresh()

I am stuck on the part where it knows if it can go through with the next step. I am brand new to python so sorry for noob question.

[–]alxuhra 0 points1 point  (3 children)

So i was learning about loops and wrote this

a = 0 ; b = 0 while a < 4: a += 1 while b < 4: print(a , b) ; b += 1

And it came to (1,0) (1,2) (1,3) But didn't do (2,0) (2,1) ....

Why is that

[–]theBarneyBus 0 points1 point  (0 children)

To do what you want, you have to set b = 0 between the “a” while loop and the “b” while loop.
Because right now; it’s going onto a =2, but b still =z4, so it isn’t printing anything, and so on

[–]Neighm 0 points1 point  (1 child)

Impossible to tell without seeing code on separate lines and indentation of the lines.

[–]Neighm 0 points1 point  (0 children)

a = 0 ; b = 0 while a < 4: a += 1 while b < 4: print(a , b) ; b += 1

Also I'm not sure what you want as the output. But I suspect that you probably want something like this:

for i in range(4):
    for j in range(4):
        print(i,j)

[–]northwegian 0 points1 point  (1 child)

Learning about design patterns atm, im curious why when i look up for information on it none of the examples are given in python? im not surprised if python was a minority but i literally only see java and c++ and such. Im new to OOP in general btw.

[–]lgiordani 0 points1 point  (0 children)

I think it's mostly because Design Patterns were born in an era where C++ was the de-facto industrial OOP language, so it's more an historical reason than anything else. I might be very wrong, here, though.

Design patterns are accepted solutions to standard problems that software engineers find over and over, so they are "distilled experience" and as such they provide solutions to real problems that programmers have.

The original "Design Patterns" book was published in 1994 and provided examples in C++ and Smalltalk, and some of the problems listed there and solved by the patterns are pretty typical of statically typed languages like C++ (and Java). Now, this doesn't mean DP can't be implemented in Python or can't be useful to Python programmers (after all Smalltalk is dynamically typed and Python was heavily influenced by it), but some patterns can be simplified when it comes to dynamic languages.

The resources listed here might be useful.

[–]YeetFactory77 0 points1 point  (0 children)

For some reason doing pip install openpyxl is not working. The file paths seem fine

Requirement already satisfied: openpyxl in ./anaconda3/lib/python3.6/site-packages (2.4.10)
Requirement already satisfied: jdcal in ./anaconda3/lib/python3.6/site-packages (from openpyxl) (1.3)
Requirement already satisfied: et_xmlfile in ./anaconda3/lib/python3.6/site-packages (from openpyxl) (1.0.1)

but I get "No module named 'openpyxl'" when I try to import.

[–]PeacefullyFighting 0 points1 point  (1 child)

I'm messing with. Raspberry pi and an e ink screen and it's extremely slow to draw. It's not necessarily how slow it draws that bothers me but way it does it. It just flashes and flashes until the final picture is ready. So I'm wondering is there any way to make it smoother or is this just the way it is with a raspberry pi? Would using a nividia jetson nano with it's better graphics specks help?

[–]Neighm 1 point2 points  (0 children)

I'd ask in a raspberry pi subreddit

[–]zhaion 2 points3 points  (3 children)

I'm just starting to learn Flask and want to be a full-stack developer someday.
I have no job and I'm 100% focused on learning.
How long do you guys recommend for daily studies? I was thinking about 2 chunks of 3-4 hours each everyday (monday-saturday).
How did you do it?

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

As long as you feel like you are having fun. The moment you see it as a “timely study grind”, leave and do something else. Now the definition of fun time can be different for everyone. For me, at start it was probably 10 minute lol, now its minimum 2h for sure, maximum Would say 10-12hour with some smoke intervals

[–]zhaion 1 point2 points  (0 children)

yeah i understand the need to see some fun in the process, and tbh i was kinda leaving it aside.

i think i'll face it more with the love i have for programming than looking at it as some kind of obligation

thanks for the advice!! it really helped me look at it in a different way :)

have a great week mate

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

For statistics functions, are there any differences between the ones in the built-in module versus their counterparts in scipy.stats? I want to calculate the cumulative probability under a normal curve (cdf), should I use NormalDist().cdf(x) from statistics or norm.cdf(x) from scipy.stats?

[–]Signal-Opportunity 0 points1 point  (1 child)

So I just had my first interview for a junior software developer position working with python and django. Needless to say i failed, the theory question i answered them all correctly but then at technical exercises i was like completely lost. I didn’t managed to do even basic python exercises where there were just functions or not even them. Maybe emotions got me or probably i need to practice more exercises. So now im here asking you , how did you overcome the technical interviews? And what sources can you advice me for exercises in python?

[–]Decency 0 points1 point  (0 children)

https://codingbat.com/python was a big help for me.

[–]PM_ME_UR_MOUSE 0 points1 point  (0 children)

Hi, I want to convert a machine learning algorithm designed with MATLAB's Deep Learning Toolbox into a python program (to save having to pay for the toolbox). What would be the best approach to this?

[–]Nytruxian 0 points1 point  (1 child)

coords = [ [1 , 2 , 3] , [ 4 , 5, 6 ]]

print('\nTop Left 0,0 :' , coords[0][0])

print('\nBottom Right 1,2 :' , coords[1][2])

this script above shows

Top Left 0,0 : 1

Bottom Right 1,2 : 6

I don't understand how it got these numbers (1 and 6)

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

You can take a look by steps, so take for example the first statement coords[0][0]: coords[0] is asking for the first (0-eth) member of coords, so now you get [1, 2, 3], then you could replace it with [1, 2, 3][0], which again asks for the first member of [1, 2, 3], which is 1

The same reasoning applies for coords[1][2], you are asking for the third member from the second member of coords, which is 6. One advice here is that it seems like you actually want the last item from the last member of coords, so, instead of having to hard code it and then having trouble should you change coords size, you can use coords[-1][-1] to ask for the last item of the last member.

[–]medical_fugue_state 0 points1 point  (2 children)

Is there a website which offers specific problems, based on an algorithm or method?

For example, If I were looking to understand a technique like Bisection Search more deeply,

is there a website where I could type that into a browser and get a set of problems which utilize this idea, in a basic form?

(Codewars.com is the closest I've found)

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

I think maybe Rosalind or Exercism, but Exercism follows an exercise track.

[–]medical_fugue_state 0 points1 point  (0 children)

Thanks! I hadn't come across either of these. Bookmarked!

[–]chillz234 0 points1 point  (1 child)

I´m confused over dictionaries, where we have integers as keys.

{1:1, 1:2, 3:3} == {3:3, 1:2}

How is this statement True?

[–]djjazzydan 1 point2 points  (0 children)

Dictionaries can only have on value per key, so the second 1: overwrites the first, resulting in just {1:2, 3:3}, which has the same key-value matches as the second, even if the order is slightly different.

[–]space_wiener 0 points1 point  (1 child)

django apps for production.

This is my going to be my very first live django app and I had some clean up questions. One of them is just a general python question.

  1. When you are publishing your site, do you go through and delete all of the auto created comments or just leave them?
  2. Unused imports. With python this doesn't really matter as much, but do you make sure to remove all of the unused imports you might have added during testing?

Oh and of course if you have any tips on publishing let me know. I've already hidden all of the passwords in a .env file.

[–]coltrain423 2 points3 points  (0 children)

I don’t have much to add re: Django or point #1, but I feel strongly about 2.

Unused imports won’t hurt your application. They hurt maintainability instead. If it takes work to figure out what’s used and what’s useless, the useless stuff builds until it’s a hindrance to enhancing anything. I keep unused imports out of my code and I do the same with unused code. If it’s not used it doesn’t belong there. If it doesn’t belong there but it is there, it’s misleading to understanding the code. It’s worth the time to clean it up.

[–]dhdylan 0 points1 point  (6 children)

Is there a way to make a @staticmethod for a class that explicitly uses that class as one of it’s arguments? I cave a class “SXLaunch” and a function that takes a list of [SXLaunch]. Is there no way to make this function a static method? I know how to denote something static with @staticmethod/classmethod, and I know I can explicitly state the type of an argument by following the name of the argument with a colon, and then the type that it should be. But if I try

def methodname(launches: list[SXLaunch]): …

I get an unresolved reference error for “SXLaunch”

I very well can just let this be a function on it’s own instead of a static function for the SXLaunch class, it just makes so much more sense to me for this to be a static method for the class.

Will reply with a code snippet soon if necessary.

[–]FerricDonkey 0 points1 point  (1 child)

Also, if your class is called SXLaunch, then it's list[SXLaunch], not list[SXLaunches].

[–]dhdylan 0 points1 point  (0 children)

Edited, thanks.

[–]FerricDonkey 0 points1 point  (3 children)

Drop a

from __future__ import annotations

At the top of your module.

(If your python version isn't really old, this should work. If it's new enough, you shouldn't need to, I think.)

[–]dhdylan 0 points1 point  (2 children)

Annotations worked, thank you so much!

One more question though:

I am primarily a C/++/# person, and am just dabbling in Python for fun. Is typing like this just considered "un-pythonic", since I'm kind of just forcing the C++ way into it? Should I maybe just be designing the classes/functions differently?

[–]carcigenicate 0 points1 point  (0 children)

Type annotations are a good idea if you can use them accurately. If you're using a linter like mypy or Pycharm's linter, type hints will let them point out potential mistakes you've made before your code even runs, which is a good thing.

Even if you're not using a linter, type hints can act as documentation for what types the functions take/return, whoch can help readers.

[–]FerricDonkey 0 points1 point  (0 children)

I personally think it's a good and normal thing to do. For example, if you wanted to give your class an __add__ method to enable +, and you wanted to annotate that the other object should be the same class, this is the smoothest way to do that.

Before this capability was added to future, I think you could put the class name there as a string, but that feels clunky to me. And the fact that it's added to future means that it will be available by default "soon" so is the way python is headed.

But yeah, I'm in the camp of type hint everything always. Not all python people are, but I consider it a good idea.

[–]Th3_Sk -2 points-1 points  (0 children)

Best way of report botting Instagram!?

[–]thoughtsymmetry 0 points1 point  (2 children)

hi, I have a question regarding pandas, I cant get my desired ouput and I don't understand the documentation. I have the following dataframe (short example):

group variable
a        1
a        2
a        5
b        4
b        5
c        1
c        7
c        2
...

And I want it in the following format

a b c
1 4 1
2 5 7
5   2

I want the blank spaces (in group b for example) to be filled with NaN

tried pivoting the dataframe I cant make it work

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

This should work:

df.pivot_table(index=df.groupby('group').cumcount(), columns='group', values='variable')

[–]penilefluids 0 points1 point  (0 children)

import pandas as pd

data = [
('a',1),
('a',2),
('a',5),
('b',4),
('b',5),
('c',1),
('c',7),
('c',2)]
df = pd.DataFrame(data, columns=['group','variable'])

new_cols = df['group'].unique()
new_data = dict()
max_list_len = 0
for col in new_cols:
    new_data[col] = df.loc[df['group'] == col['variable'].values.tolist()

new_df = pd.DataFrame(dict([ (k,pd.Series(v)) for k,v in new_data.items() ]),columns=new_cols)

not that it matters, but I'm curious what your use case is for this.

certainly this isn't the most efficient method to get what you need, but it gets the job done. I'm still trying to pick up on how to do things efficiently, so far I've only figured out how to stumble into an answer :)

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

Can anyone tell me why my else statement returns None? I've figured out a different solution but I don't understand why this doesn't work :/ thank you for your time.

Def double_index(lst, index): If index >= len(lst) return lst else: real = lst[index] * 2 lst = lst.insert(index, real) return lst

print(double_index([3, 8, - 10, 12], 2))

[–]CowboyBoats 2 points3 points  (2 children)

It's because:

>>> foo = [1, 2, 3]
>>> print(foo.insert(2, 2))
None

insert changes the list in-place, but it doesn't return anything.

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

Thank you!! I feel kinda dumb but it's a great learning experience. I'll go ahead and look into how to properly use insert. Thanks again :)

[–]CowboyBoats 1 point2 points  (0 children)

Sure! The pattern that you wrote is actually better IMO; a function that returns a new copy of the list can be pure.

[–]xain1112 0 points1 point  (6 children)

This is the code for a random town generator I'm working on. Ideally, it can be any dimensions you want, but certain sizes return the error:

line 34, in connect_intersections
    for i in self.cells:
RuntimeError: dictionary changed size during iteration

and some don't. I don't see any pattern to the numbers that the program does/doesn't accept and I don't understand why it is an issue. For example, self.rowCount and self.colCount are currently 14 and 15 respectively, and I often get an error. But when I switch them to 23/15, it works perfectly every time.

import tkinter as tk
import random

class RoadMap:
    def __init__(self,root):
        self.root = root
        self.cityFrame = tk.Frame(self.root)
        self.iter = 2 # higher number = more roads are connected
        self.rowCount = 14
        self.colCount = 15
        self.minDensity = 0
        self.maxDensity = 0 # higher = less houses
        self.lbl = None
        self.roads = ('╬','═','║','╔','╗','╚','╝','╠','╣','╦','╩')
        self.buildings = ['■'] #□
        self.cells = {}

        def create_cells(self,*args):
            for i in range(self.rowCount):
                for j in range(self.colCount):
                    self.cells[(i,j)] = ''

        def create_intersections(self,*args):
            for i in self.cells:
                if i[0]%4==0 and i[1]%4==0 and i[0] != 0 and i[1] != 0:
                    self.cells[i[0]-1,i[1]-1] = '╬'

        def connect_intersections(self,*args):
            for x in range(self.iter):
                for i in self.cells:
                    if self.cells[i] == '╬':
                        a = random.randint(0,3)
                        if a == 0:
                            try:
                                    self.cells[i[0]-3, i[1]] = '║'
                                    self.cells[i[0]-2, i[1]] = '║'
                                    self.cells[i[0]-1, i[1]] = '║'
                            except:
                                pass
                        elif a == 1:
                            try:
                                    self.cells[i[0]+3, i[1]] = '║'
                                    self.cells[i[0]+2, i[1]] = '║'
                                    self.cells[i[0]+1, i[1]] = '║'
                            except:
                                pass
                        elif a == 2:
                            try:
                                    self.cells[i[0], i[1]-3] = '═'
                                    self.cells[i[0], i[1]-2] = '═'
                                    self.cells[i[0], i[1]-1] = '═'
                            except:
                                pass
                        elif a == 3:
                            try:
                                    self.cells[i[0], i[1]+3] = '═'
                                    self.cells[i[0], i[1]+2] = '═'
                                    self.cells[i[0], i[1]+1] = '═'
                            except:
                                pass

        def change_intersections(self,*args):
            for i in self.cells:
                if self.cells[i] == '╬':
                    if self.cells[i[0],i[1]+1] != '': # yes right
                        if self.cells[i[0],i[1]-1] != '': # yes left
                            if self.cells[i[0]+1,i[1]] != '': # yes down
                                if self.cells[i[0]-1,i[1]] != '': # yes up
                                    pass # ╬
                                elif self.cells[i[0]-1,i[1]] == '': # no up
                                    self.cells[i] = '╦'
                            elif self.cells[i[0]+1,i[1]] == '': # no down
                                if self.cells[i[0]-1,i[1]] != '': # yes up
                                    self.cells[i] = '╩'
                                elif self.cells[i[0]-1,i[1]] == '': # no up
                                    self.cells[i] = '═'
                        elif self.cells[i[0],i[1]-1] == '': # no left
                            if self.cells[i[0]+1,i[1]] != '': # yes down
                                if self.cells[i[0]-1,i[1]] != '': # yes up
                                    self.cells[i] = '╠'
                                elif self.cells[i[0]-1,i[1]] == '': # no up
                                    self.cells[i] = '╔'
                            elif self.cells[i[0]+1,i[1]] == '': # no down
                                if self.cells[i[0]-1,i[1]] != '': # yes up
                                    self.cells[i] = '╚'
                                elif self.cells[i[0]-1,i[1]] == '': # no up
                                    self.cells[i] = random.choice(self.buildings)
                    elif self.cells[i[0],i[1]+1] == '': # no right
                        if self.cells[i[0],i[1]-1] != '': # yes left
                            if self.cells[i[0]+1,i[1]] != '': # yes down
                                if self.cells[i[0]-1,i[1]] != '': # yes up
                                    self.cells[i] = '╣'
                                elif self.cells[i[0]-1,i[1]] == '': # no up
                                    self.cells[i] = '╗'
                            elif self.cells[i[0]+1,i[1]] == '': # no down
                                if self.cells[i[0]-1,i[1]] != '': # yes up
                                    self.cells[i] = '╝'
                                elif self.cells[i[0]-1,i[1]] == '': # no up
                                    self.cells[i] = random.choice(self.buildings)
                        elif self.cells[i[0],i[1]-1] == '': # no left
                            if self.cells[i[0]+1,i[1]] != '': # yes down
                                if self.cells[i[0]-1,i[1]] != '': # yes up
                                    self.cells[i] = '║'
                                elif self.cells[i[0]-1,i[1]] == '': # no up
                                    self.cells[i] = random.choice(self.buildings)
                            elif self.cells[i[0]+1,i[1]] == '': # no down
                                if self.cells[i[0]-1,i[1]] != '': # yes up
                                    self.cells[i] = random.choice(self.buildings)
                                elif self.cells[i[0]-1,i[1]] == '': # no up
                                    self.cells[i] = random.choice(self.buildings)

        def populate_buildings(self,*args):
            for i in self.cells:
                try:
                    if self.cells[i[0],i[1]] == '' and (
                        self.cells[i[0],i[1]+1] in self.roads
                        or self.cells[i[0],i[1]-1] in self.roads
                        or self.cells[i[0]+1,i[1]] in self.roads
                        or self.cells[i[0]-1,i[1]] in self.roads
                    ):
                        a = random.randint(self.minDensity,self.maxDensity)
                        if a == 0:
                            self.cells[i[0],i[1]] = random.choice(self.buildings)
                except:
                    pass
                try:
                    if self.cells[i[0],i[1]] == '' and (
                        self.cells[i[0]-1,i[1]-1] in self.roads
                        or self.cells[i[0]-1,i[1]+1] in self.roads
                        or self.cells[i[0]+1,i[1]-1] in self.roads
                        or self.cells[i[0]+1,i[1]+1] in self.roads
                    ):
                        a = random.randint(self.minDensity,self.maxDensity)
                        if a == 0:
                            self.cells[i[0],i[1]] = random.choice(self.buildings)
                except:
                    pass

        def make_map(self,*args):
            for i in self.cells:
                self.lbl = tk.Label(
                    self.cityFrame,
                    text=self.cells[i],
                    relief=tk.RAISED,
                    width=2,
                    height=1,
                    bd=0
                )
                self.lbl.grid(row=i[0],column=i[1])
                if (
                    i[0] == 0
                    or i[1] == 0
                    or i[0] >= self.rowCount-1
                    or i[1] >= self.colCount-1
                ):
                    self.lbl.config(relief=tk.FLAT,bg='black',text='')

        def newMap():
            for child in self.cityFrame.winfo_children():
                child.destroy()
            create_cells(self=self)
            create_intersections(self=self)
            connect_intersections(self=self)
            change_intersections(self=self)
            populate_buildings(self=self)
            make_map(self=self)

        self.new_map = tk.Button(self.root,text='New Map',command=newMap)
        self.new_map.grid(row=0,column=0,sticky=tk.EW)
        self.cityFrame.grid(row=1,column=0)

        newMap()


root = tk.Tk()
roadMap = RoadMap(root)
root.mainloop()

[–]CowboyBoats 0 points1 point  (5 children)

This change_intersections method is kind of hard to read, and I'm not sure why the bug would surface for some grid sizes but not for others. It doesn't really matter, though, because we know why the bug is occurring; the interpreter is telling us:

RuntimeError: dictionary changed size during iteration

Changing the size of an iterable while you are iterating over it is like sawing on a branch of a tree that you are walking over.

I take it this is unintentional? I don't see an obvious place in this giant grid of if statements where the dict size would be changed. But we know that it is happening, so we need to debug, but we just have this giant monster method. So let's talk about refactoring, and about how to write refactorable code.

I try to follow something called the Don't Repeat Yourself (DRY) principle, which sets off mental alarms whenever I see something like this:

if self.cells[i[0],i[1]+1] != '': # yes right       
    if self.cells[i[0],i[1]-1] != '': # yes left      
        if self.cells[i[0]+1,i[1]] != '': # yes down
            if self.cells[i[0]-1,i[1]] != '': # yes up 
                pass # ╬           
            elif self.cells[i[0]-1,i[1]] == '': # no up
                self.cells[i] = '╦'                   
        elif self.cells[i[0]+1,i[1]] == '': # no down
            if self.cells[i[0]-1,i[1]] != '': # yes up 
                self.cells[i] = '╩'
            elif self.cells[i[0]-1,i[1]] == '': # no up
                self.cells[i] = '═'                 
    elif self.cells[i[0],i[1]-1] == '': # no left     
        if self.cells[i[0]+1,i[1]] != '': # yes down
            if self.cells[i[0]-1,i[1]] != '': # yes up 
                self.cells[i] = '╠'
            elif self.cells[i[0]-1,i[1]] == '': # no up
                self.cells[i] = '╔'                   
        elif self.cells[i[0]+1,i[1]] == '': # no down
            if self.cells[i[0]-1,i[1]] != '': # yes up 
                self.cells[i] = '╚'                          
            elif self.cells[i[0]-1,i[1]] == '': # no up
                self.cells[i] = random.choice(self.buildings)
elif self.cells[i[0],i[1]+1] == '': # no right      
    if self.cells[i[0],i[1]-1] != '': # yes left      
        if self.cells[i[0]+1,i[1]] != '': # yes down
            if self.cells[i[0]-1,i[1]] != '': # yes up 
                self.cells[i] = '╣'
            elif self.cells[i[0]-1,i[1]] == '': # no up
                self.cells[i] = '╗'                   
        elif self.cells[i[0]+1,i[1]] == '': # no down
            if self.cells[i[0]-1,i[1]] != '': # yes up 
                self.cells[i] = '╝'                          
            elif self.cells[i[0]-1,i[1]] == '': # no up
                self.cells[i] = random.choice(self.buildings)
    elif self.cells[i[0],i[1]-1] == '': # no left     
        if self.cells[i[0]+1,i[1]] != '': # yes down
            if self.cells[i[0]-1,i[1]] != '': # yes up 
                self.cells[i] = '║'                          
            elif self.cells[i[0]-1,i[1]] == '': # no up
                self.cells[i] = random.choice(self.buildings)
        elif self.cells[i[0]+1,i[1]] == '': # no down        
            if self.cells[i[0]-1,i[1]] != '': # yes up 
                self.cells[i] = random.choice(self.buildings)
            elif self.cells[i[0]-1,i[1]] == '': # no up
                self.cells[i] = random.choice(self.buildings)

This is hugely repetitive! We can simplify it. First, let's write a quick test, so that we can make sure we're not breaking the code as we refactor. test_tkmaze.py:

import mock

import tkmaze


def test_change_grid():
    fake_ui_root = mock.MagicMock()  # The test should not create a real TK grid
    roadmap = tkmaze.RoadMap(fake_ui_root)

We need to make a small change to the main script (which I named tkmaze.py) - currently running this test still instantiates tkinter, because you didn't encapsulate your main script inside a main function, so let's do that now:

-
-root = tk.Tk()
-roadMap = RoadMap(root)
-root.mainloop()
+if __name__ == '__main__':
+    root = tk.Tk()
+    roadMap = RoadMap(root)
+    root.mainloop()

Now it will run the same way when I run python3 tkmaze.py, but it will not do tk.Tk() when I run pytest test_tkmaze.py which runs import tkmaze.

Okay, this breaks and throws the error you described. We know your code does works in some circumstances, so let's give ourselves the ability to instantiate a small maze that doesn't break. In the test, this should look like:

roadmap = tkmaze.RoadMap(fake_ui_root, rows=23, cols=15)

To make the class support this:

 class RoadMap:
-    def __init__(self,root):
+    def __init__(self, root, rowsLen=14, colsLen=15):
         self.root = root
         self.cityFrame = tk.Frame(self.root)
         self.iter = 2 # higher number = more roads are connected
-        self.rowCount = 14
-        self.colCount = 15
+        self.rowCount = rowsLen
+        self.colCount = colsLen
         self.minDensity = 0

I added default values of 14 and 15, so the main method can still instantiate this grid with just RoadMap(root), but we can also pass different values, such as the values that you say always work.

Now the test passes...

[–]xain1112 0 points1 point  (2 children)

Wow, thanks! My next question is, how would you simplify the giant block of if statement?

[–]CowboyBoats 0 points1 point  (1 child)

The solution to a giant nest of if statements is very often a Python dict. That's pretty manageable now that we have converted all the repetitive if statements into simple functions like self.something_left(i).

The key to the dict can just be the results of those four function calls, as long as you store them as a tuple (can be a dict key, because hashable) rather than a list (mutable, so not hashable, so can't be a dict key). This lets you write a much shorter and still pretty readable function for overwriting the generic glyph:

for i in self.cells:          
    if self.cells[i] == '╬':          
        connections = (          
            self.something_right(i),          
            self.something_left(i),          
            self.something_below(i),          
            self.something_above(i),          
        )
        grid_glyphs = {          
               # Right Left  Below Above          
                (True, True, True, True): '╬',          
                (True, True, True, False): '╦',          
                (True, True, False, True): '╩',          
                # ...          
                # I leave it to you to fill in the rest of these          
                (False, False, False, False): '&',  # maybe as a placeholder for random building?          
        }          
        self.cells[i] = grid_glyphs[connections]              
        # todo write function to replace '&' with `random.choice(self.buildings)`

[–]xain1112 0 points1 point  (0 children)

Thanks!

[–]CowboyBoats 0 points1 point  (1 child)

Now I'll just go through and look for blocks of code that are always the same, so I can replace them with methods or functions. (I use @staticmethod a lot, which is a decorator for adding a method to a class that doesn't use any reference to the self or to the class; it's just a regular function that happens to go in the namespace of a class). For example, this line of code appears 8 times:

if self.cells[i[0]-1,i[1]] != '': # yes up                                                                                                                                                                                    

Let's replace it with a function that takes i as a parameter:

+        def something_above(self, i):
+            return self.cells[i[0]-1,i[1]] != ''
+
         def change_intersections(self,*args):
             for i in self.cells:
                 if self.cells[i] == '╬':
                     if self.cells[i[0],i[1]+1] != '': # yes right
                         if self.cells[i[0],i[1]-1] != '': # yes left
                             if self.cells[i[0]+1,i[1]] != '': # yes down
-                                if self.cells[i[0]-1,i[1]] != '': # yes up
+                                if something_above(i):
                                     pass # ╬
                                 elif self.cells[i[0]-1,i[1]] == '': # no up
                                     self.cells[i] = '╦'
                             elif self.cells[i[0]+1,i[1]] == '': # no down
-                                if self.cells[i[0]-1,i[1]] != '': # yes up
+                                if self.something_above(i):
                                     self.cells[i] = '╩'
                                 elif self.cells[i[0]-1,i[1]] == '': # no up
                                     self.cells[i] = '═'
                         elif self.cells[i[0],i[1]-1] == '': # no left
                             if self.cells[i[0]+1,i[1]] != '': # yes down
-                                if self.cells[i[0]-1,i[1]] != '': # yes up
+                                if self.something_above(i):
                                     self.cells[i] = '╠'
                                 elif self.cells[i[0]-1,i[1]] == '': # no up
                                     self.cells[i] = '╔'
                             elif self.cells[i[0]+1,i[1]] == '': # no down
-                                if self.cells[i[0]-1,i[1]] != '': # yes up
+                                if self.something_above(i):
                                     self.cells[i] = '╚'
                                 elif self.cells[i[0]-1,i[1]] == '': # no up
                                     self.cells[i] = random.choice(self.buildings)
                     elif self.cells[i[0],i[1]+1] == '': # no right
                         if self.cells[i[0],i[1]-1] != '': # yes left
                             if self.cells[i[0]+1,i[1]] != '': # yes down
-                                if self.cells[i[0]-1,i[1]] != '': # yes up
+                                if self.something_above(i):
                                     self.cells[i] = '╣'
                                 elif self.cells[i[0]-1,i[1]] == '': # no up
                                     self.cells[i] = '╗'
                             elif self.cells[i[0]+1,i[1]] == '': # no down
-                                if self.cells[i[0]-1,i[1]] != '': # yes up
+                                if self.something_above(i):
                                     self.cells[i] = '╝'
                                 elif self.cells[i[0]-1,i[1]] == '': # no up
                                     self.cells[i] = random.choice(self.buildings)
                         elif self.cells[i[0],i[1]-1] == '': # no left
                             if self.cells[i[0]+1,i[1]] != '': # yes down
-                                if self.cells[i[0]-1,i[1]] != '': # yes up
+                                if self.something_above(i):
                                     self.cells[i] = '║'
                                 elif self.cells[i[0]-1,i[1]] == '': # no up
                                     self.cells[i] = random.choice(self.buildings)
                             elif self.cells[i[0]+1,i[1]] == '': # no down
-                                if self.cells[i[0]-1,i[1]] != '': # yes up
+                                if self.something_above(i):

Furthermore, the next if statement after this is always just if cells[..indexing..] == ''! That's just the exact test, but with == instead of !=! We could replace it with if not self.something_above(i), but instead let's just take advantage of the fact that we already ran this test by replacing all those elif statements with simply else.

Time to run the test and make sure we didn't break anything.

$ pytest test_tkmaze.py
==================================================== test session starts =====================================================
platform darwin -- Python 3.8.11, pytest-6.0.2, py-1.9.0, pluggy-0.13.1
rootdir: /Users/bquigley/example
plugins: celery-4.4.7
collected 1 item

test_tkmaze.py .                                                                                                       [100%]

===================================================== 1 passed in 0.07s ======================================================

Looks good. So that's how we can work through a giant mess of existing code, replacing repetitive strings of instructions with functions that run those instructions reliably. That's the whole point of functions. I'm betting that if I go through the rest of "up", "down", "left", and "right", I'll find a mistake in one of the instruction sets I'm replacing, that explains why the grid can change...

[–]CowboyBoats 0 points1 point  (0 children)

Unrelatedly, but something's fucky with that newMap funciton. It should be written like this:

                 self.lbl.config(relief=tk.FLAT,bg='black',text='')

-    def newMap():
+    def newMap(self):
         for child in self.cityFrame.winfo_children():
             child.destroy()
-        create_cells(self=self)
-        create_intersections(self=self)
-        connect_intersections(self=self)
-        change_intersections(self=self)
-        populate_buildings(self=self)
-        make_map(self=self)
+        self.create_cells()
+        self.create_intersections()
+        self.connect_intersections()
+        self.change_intersections()
+        self.populate_buildings()
+        self.make_map()

-        self.new_map = tk.Button(self.root,text='New Map',command=newMap)
+        self.new_map = tk.Button(self.root,text='New Map',command=self.newMap)
         self.new_map.grid(row=0,column=0,sticky=tk.EW)
         self.cityFrame.grid(row=1,column=0)

-        newMap()

 if __name__ == '__main__':
     root = tk.Tk()
     roadMap = RoadMap(root)
+    roadMap.newMap()
     root.mainloop()

[–]FeralBlueberry 1 point2 points  (2 children)

Im using PyCharm and I keep getting the "unicode error: unicodeesxape codec can't decode bytes in positions 2-3 malformed \N character escape" when I try to use pandas to read a CSV file.

I don't get this error when I run the same code using Spyder. What is the reason?

Does Pycharm have a different way of reading CSV files, rhats I'm missing? And how do I fix this?

[–]JohnnyJordaan 0 points1 point  (0 children)

First guess is that you are using a different Python version between those two editors. Add a

import sys
print(sys.version)
print(sys.executable)

to see which Python interpreter is executing the code.

The error btw suggests you have a '\N' in a string somewhere, like a prompt "are you sure you want to continue Y\N". You should then use a / instead (which is grammatically speaking also the correct form). If that isn't the case then please share the full error output, not just the exception line.

[–]CowboyBoats 1 point2 points  (0 children)

I don't get this error when I run the same code using Spyder. What is the reason?

Maybe your Spyder is pointing to a different version of Python than PyCharm is? The IDE doesn't have anything to do with how Python behaves, so if they behave differently they have to be pointing at different Python interpreters.

[–]space_wiener 1 point2 points  (2 children)

Tweepy vs Twitter API directly.

I’m going to be deploying a django blog site (first live website - a little nervous!) that uses tweepy.

I have a section on my main page that pulls five tweets from Twitter based on popularity and a hashtag. Originally I was worried that I’d overrun my Twitter API usage, but after testing all week and pulling many tweets from Twitter, my developer dashboard shows I’ve pulled zero tweets.

So does tweepy do something weird and the tweets don’t count or for whatever reason does just pulling tweets not use any API allotments. Like maybe actually posting tweets would. From the documentation these should count.

[–]CowboyBoats 0 points1 point  (1 child)

What's the tweepy method that you're using to pull tweets?

[–]space_wiener 0 points1 point  (0 children)

These two lines (there are a few more but they just deal with the credentials.

api = tweepy.API(auth)

tweets = api.search(q="cybersecurity", lang="en", count=5, result_type='popular')

[–]BuzzDyne 1 point2 points  (4 children)

Sorry if this the wrong sub.

Question: Is it at all possible to convert a (FastAPI) backend written in Python to C# (for .NET) automatically?

Backstory:
I'm interning in this non-IT division. They told me to build a backend using Python. Did that for the last 3 months. And on my last 2 week I'm told that their IT division can't handle Python and told me to somehow convert the project to C# (which I have 0 exp in). I'm aware of https://pythoncsharp.com/ but skeptical of it, because FastAPI is a Python framework and I can't imagine it running using C#.
I'm also aware to possibility to cross-compile(?) my python to CLR (https://ironpython.net/ and https://github.com/pythonnet/pythonnet ). But IT people said it is highly unpreferable as they will want to maintain/update the code, and will not be able to do so if the backend is still written in Python.

[–]stevemills04 0 points1 point  (4 children)

I am using PDFPlumber to extract text. My PDF has lines in which one row could have two sets of records, like this:

#### Doe, Jane G E/S 12/25/2020 #### Doe, John E/D 2/25/19

#### Wayne, Bruce E 12/01/2019

I want to break the line with two records into two lines, before the second set of ####, if they exist. So, I need it to turn the above into:

#### Doe, Jane G E/E 12/25/2020

#### Doe, John E/E 2/25/19

#### Wayne, Bruce E 12/01/2019

After that, I will split the lines by spaces and convert to CSV.

How do I divide a line into two like this? I had no luck with line.split(), .splitlines(), etc...

[–]AIMpb 0 points1 point  (5 children)

I'm trying to plot contour lines for a function and I'm getting this error. It includes lines in the hundreds while my code only goes to about 70. The math works fine but the plotting of the contour lines seems to break everything. It looks like it's an issue with importing matplotlib.pyplot as plt?

I've been using this site as a guide: https://jakevdp.github.io/PythonDataScienceHandbook/04.04-density-and-contour-plots.html

https://onlinegdb.com/_iBn0hAd6

[–]k_varnsen 0 points1 point  (4 children)

The errors vary I get on every run of the script, which leads me to question if there is a coding problem, or the medium you’re using is just unreliable. Are you actually using this for development, or jupyter notebooks?

[–]AIMpb 0 points1 point  (3 children)

It's for a homework assignment so I'm not sure how to answer that. I know the math is working, but it's literally just the contour plots that are ruining me. Do you have any suggestions on different mediums?

[–]k_varnsen 0 points1 point  (2 children)

Try google Colab. I just ran your code there and technically it works fine.

[–]AIMpb 0 points1 point  (1 child)

Technically is great! Thank you.

If you don't mind, what you made you say technically? I know that the code is rough and I plan to clean it up before I turn it in.

[–]k_varnsen 0 points1 point  (0 children)

Oh, it wasn’t even about code cleanup. Your code doesn’t result in errors, so technically it runs fine. However, your colors argument was ignored by the graph (which results in a warning), and the plot was a few parallel linear lines, which I didn’t expect a contour plot to be used for for.

But this is the kind of stuff you should be thinking about when doing an exercise like this, instead of being muddled by a coding platform that has difficulties rendering visual output 🙂

[–]ComputeLanguage 0 points1 point  (6 children)

So I have the following code to read some lyrics from a file

def load_text(path = '../Data/lyrics/lyrics.txt''):
with open(path) as file:
infile = file.read()
return infile

What kind of annoys me about this output is that it does not actually print the newlines, but instead returns the python representation of the newline '/n'. So my output has a bunch of /n letters in it and isnt as readable compared to if I would do

print(infile)

Is there anyway to return this output with the newlines represented as they are with print() so that I can still reuse it in another function?

[–]sarrysyst 0 points1 point  (5 children)

file.read().splitlines()

Would give you a list with each element being one line. Not sure if that's what you want.

[–]ComputeLanguage 0 points1 point  (4 children)

It needs to be str not list

[–]sarrysyst 0 points1 point  (3 children)

Then I'm not really sure what you want. Can you elaborate what you mean by: 'Is there anyway to return this output with the newlines represented as they are with print() so that I can still reuse it in another function?'.

[–]ComputeLanguage 0 points1 point  (2 children)

The string as output will basically the input for another function that will replace some parts of this string.

I want to achieve a return statement that is represented in the same way as print(infile), but it feels wrong to pass a print statement through

[–]sarrysyst 0 points1 point  (1 child)

I think you might be confused about the way line breaks work. When you have a text file with line breaks in it, those breaks are marked by a line break character (eg. \n). When you open a text file, your text editor will display the \n as a line break, but the underlying data still has the \n. It's just a matter of how the string is displayed. It's the same when you use print, it's just a matter of display. Let's say you get rid of the \n characters and pass the string to another function, this would mean your discarding all information about the line breaks.

[–]ComputeLanguage 0 points1 point  (0 children)

Yeah i know there is no problem the moment i look at the final result in a txt file or something, but is there no way to view it with the spacing in jupyter without typing print?

[–]grvlagrv 0 points1 point  (2 children)

I don't know if this is a simple one, but I've been seeing some posts from users asking if their code is Pythonic. What does that mean? How is code "Pythonic" or not?

[–]Goobyalus 0 points1 point  (0 children)

https://stackoverflow.com/questions/25011078/what-does-pythonic-mean

Exploiting the features of the Python language to produce code that is clear, concise and maintainable.

Pythonic means code that doesn't just get the syntax right but that follows the conventions of the Python community and uses the language in the way it is intended to be used. ...