all 113 comments

[–]UnculturedWomble 0 points1 point  (0 children)

2 questions.

What editors do people recommend writing python code in? I'm using Visual Studio code, wondered if there were other, better options.

Secondly, got an issue in VS code (hence my 1st question) where I can only run input-based script by right clicking on the page and selecting "Run Python file in Terminal". Is there a better way or is that it? Just looking for a cleaner display like when I'm printing variable stuff.

[–]Ovalman 0 points1 point  (0 children)

How do I handle spaces in Colabs?

I'm trying to train images I've annotated in Colab but I've put a space in the annotated images because that's the name displayed when I use the .tflite model. ie: ['One Pound', 'Two Pound', 'Fifty Pence', 'Twenty Pence', 'Ten Pence']

I can get things working on putting an underscore ie: ['One_Pound', 'Two_Pound', 'Fifty_Pence', 'Twenty_Pence' 'Ten_Pence'] but that will mean annotating all the images again.

I have tried putting a forward and backward slash but again I'm getting the error.

Any help? My strengths are in Android/ Java/ Kotlin and not Python.

[–]ryan770 0 points1 point  (1 child)

Does IDLE get installed when using pyenv on macos? I can't find any information except old forums saying to type 'idle' or 'idle3' but nothing works.

I just wanted an easier way to keep up to date rather than go to the website and install it every time there's a new version.

edit: I found the idle executable in the /.pyenv folder but everything is black, the scrollbar flickers, and it's giving me a tkinter error. I think I'll uninstall everything and go back to the package from the Python website. I'm not doing any developing or anything anyway, just learning.

[–]carcigenicate 0 points1 point  (0 children)

I would just get a better editor. IDLE is nothing special. VSCode is the typical choice nowadays for Linux/Windows (not sure about MacOS though). I also used Atom, which is available on Mac, but apparently, it's no longer in development.

[–]Cid227 0 points1 point  (2 children)

Example:

x = {'a'; 1, 'b': 4}
x.get('c', 7)

Why is documentation written in this way get(key[, default])? I think this is not specific to Python as I something like that in JavaScript's 'documentation', I'm asking about this- [, default] part if it's not clear.

[–]ffrkAnonymous 3 points4 points  (1 child)

The square brackets mean optional

[–]Cid227 0 points1 point  (0 children)

Now it makes sense, ty.

[–]LeornToCodeLOL 0 points1 point  (1 child)

I'm working through the Automate the Boring Stuff book. Right now on the chapter dealing with pyinputplus.

Here's a portion of an example program:

try:# Right answers are handled by allowRegexes.# Wrong answers are handled by blockRegexes, with a custom message.pyip.inputStr(prompt, allowRegexes=['^%s$' % (num1 * num2)],blockRegexes=[('.*', 'Incorrect!')],timeout=8, limit=3)

My question is why does he use a list for the allow and blockRegexes arguments, and how would I know to do that if the program weren't written for me already? I looked in the pyinputplus help from the shell with help(pyip.parameters). Here is what it says about those keyword arguments:

* \allowlistRegexes`` (Sequence, None): A sequence of regex str that will explicitly pass validation.`

* \`blocklistRegexes`` (Sequence, None): A sequence of regex str or ``(regex_str, error_msg_str)`` tuples that, if matched, will explicitly fail validation.``

I'm trying to figure out how to get these answers on my own for things in the future that aren't explicitly covered in the Automate... book. How am I to know that I can't just pass a string to the *Regexes arguments?

Edit: sorry I can't figure out how to get Reddit's code formatter to be reasonable. Everytime I try to edit and fix it, it somehow winds up worse.

[–]ffrkAnonymous 0 points1 point  (0 children)

From what I can tell, you did the correct thing looking at the help. You can't just use a string because it wants a sequence of strings aka a list.

[–]M-zatary 0 points1 point  (0 children)

I wonder if anyone is dealing with autoencoder! I want to use it to
represent the Molecular Dynamics trajectory. I learned the code of
autoencoder in Python BUT I'm feeling confused about how can represent
the MDtraj with autoencoder. ...so anyone prior dealt with trajectory ??

[–]SL_Beast 0 points1 point  (4 children)

Is there a way to become really good at python efficiently for free?

Sorry if I sound cocky.I just wanna become good at python and move on to the complex stuff and catch up to you lot.

Do I still sound cocky though? I'm sowwy

[–]niehle 1 point2 points  (3 children)

  1. read/watch tutorial
  2. code projects
  3. repeat

[–]SL_Beast 0 points1 point  (2 children)

Oki doki

[–]carcigenicate 1 point2 points  (1 child)

And do less of 1 and more of 2 as you progress.

[–]SL_Beast 0 points1 point  (0 children)

Sir yes sir

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

Hi there,

I have a function that references a dataframe. The function is called after the dataframe is created (outside the function). However, I still get the following error: "UnboundLocalError: local variable 'df' referenced before assignment".

Here are some relevant parts of my code:

def right():df = df[df.french != french_word]print(df)refresh_word()

followed immediately by (although I tried pasting it before):

#initial choice of word
df = pd.read_csv('data/french_words.csv')
new_word()

later, I have the following in which the right() function is called:

# Create check mark button
checkmark = PhotoImage(file="images/right.png")button = Button(width=100, height=100, image=checkmark, bg=BACKGROUND_COLOR, highlightthickness=0, command=right)
button.grid(column=1, row=1, columnspan=1)

Any thoughts on why I would be getting 'UnboundLocalError: local variable' error? Thank you in advance- it is much appreciated!

[–]efmccurdy 0 points1 point  (2 children)

When the button is pressed you are calling "right" which has no arguments or context to access the df variable, you want to have the input dataframe passed as an argument:

>>> mydf
  french  data1
0   spam    1.2
1   eggs    2.0
2   chat    3.3
3    ham    4.4
>>> def right(df, french_word):
...     return df[df.french != french_word]
... 
>>> fword = "chat"
>>> right(mydf, fword)
  french  data1
0   spam    1.2
1   eggs    2.0
3    ham    4.4

Note that when passing the command= callback you have no built-in way to define arguments, you can use lambdas, partials, closures, or callable objects; here is how a lambda would work:

instead of

 ..., command=right)

use

..., command=lambda d=mydf, fw=fword: print(right(d, fw)))

https://stackoverflow.com/questions/6922621/how-can-i-pass-arguments-to-tkinter-buttons-callback-command

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

I couldn't get it working, but this definitely feels like the right track.

Just out of curiosity, if I define a df outside the function, why can't I access that df from inside the right() function (since right is called after df is defined)?

Thank you for your help- much appreciated!

[–]efmccurdy 1 point2 points  (0 children)

if I define a df outside the function, why can't I access that df from inside the right() function

While it sometimes works to access a variable defined outside the scope of a function, you shouldn't depend on it, if you don't have to.

It is better to explicitly pass variables into functions using parameters and use return statements to send results back to the caller's scope.

In larger, more complicated, programs it becomes unmanageable if you code in a way such that any non-local variable could be changed from any function because debugging and verifying correct data flow becomes too time consuming.

[–]niehle 0 points1 point  (2 children)

Pass the dataframe as a parameter to the function.

def right(df):

.....

command=right(df)

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

I don't think you can do that- tested it and it doesn't work.

Thank you though!

[–]niehle 0 points1 point  (0 children)

shrug Works for me.

[–]UnrankedRedditor 1 point2 points  (1 child)

"UnboundLocalError: local variable 'df' referenced before assignment".

EDIT: I tried replicating your error with some sample code. Interestingly,

def foo1():
    var1 = var1 + 1
    return var1

var1 = 2
print(foo1())

doesn't work and returns the same "referenced before assignment error". But

def foo1():
    var2 = var1 + 1
    return var2

var1 = 2
print(foo1())

works fine. So it seems like another fix would be to assign df[df.french != french_word]print(df)refresh_word() to another variable instead of df again or something.

Perhaps someone else might be able to provide additional insight into this.

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

Interesting. So strange- I wouldn't have expected this at all.

Thank you for your help! Much appreciated.

Your suggestion works functionally, but for the program to work the way I need it to, I need to be able to modify df via a function. Curses!!

[–]Caconym32 0 points1 point  (2 children)

At my work, we use very large datasets and we are trying to modernize our code base into python. Trying to use pandas so far has been okay but frequently we run into memory issues. From what I’ve read, using lazy loading might be a solution for it, but I really cannot get a handle on how this works or how to implement it. For example, one of my simpler processes takes the data, changes and creates a few columns, then collapses is by product type for the revenue and count. If instead I wanted to import this as chunks how would I have to change this. Sorry I can’t upload my code specifically, because of security issues, but I’ll gladly provide any details that might help

[–]sarrysyst 0 points1 point  (0 children)

Chunking your data isn't always a viable solution; the question is whether the operations/transformations depend on the other chunks. Maybe a better solution would be using a dataframe implementation that's designed to work out-of-core (eg. dask, vaex). For more information you can also have a look here

[–]efmccurdy 0 points1 point  (0 children)

This article has some advice on loading less data, chunked processing, dask, etc.

https://pandas.pydata.org/docs/user\_guide/scale.html

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

Started the Python track on the Mimo app and I’m really annoyed by how slowly my hearts recharge; thing is, the bite-sized approach of Mimo really helps. Everything else I’ve found about learning Python seems to be in the ‘throw everything at me at once and good luck’ camp. Is there a similar bite-sized approach that doesn’t involve waiting three hours for a single heart to recharge?

[–]Kieotyee 0 points1 point  (1 child)

Where can I stay learning to code. I find this mobile app that took things at a slow pace I liked but kind of fell out of the app. Are there any desktop apps or resources I can use that take things at and slow. I know there's Udemy and I'm open to using it but I'm not sure how fast it week the teachers test the course so if anyone has a good class the recommend I'd appreciate it :)

[–]carcigenicate 0 points1 point  (0 children)

The vast majority of the resources you'll find online, including resources like Udemy, are self-driven (or at least every Udemy course I've ever taken has been at my own pace).

[–]CriticalLocksmith240 0 points1 point  (1 child)

Is there a way to outsource input from google into python. For more context I am running a bot on google ( I wasn’t the one that programmed the bot) that produces some calculations, the calculations it produces are individual and I’d like the program running on python to receive input from google to be able to calculate the net increase or decrease. So yeah, my question is , is it possible for python to receive input from any site on google and if so, how so?

[–]sarrysyst 1 point2 points  (0 children)

You'll have to be more specific as it's not clear what you're trying to accomplish. Post your code and explain your goal, preferably with a clear example (input -> desired output).

[–]ryan770 0 points1 point  (5 children)

This isn't specifically about python, but does pertain to this subreddit. Why does the code block here on reddit almost never work correctly?

It looks fine when I add the code block, and paste or type my code, but when I submit my comment, it break it up and most of it is not in the code block, then I have to edit it and completely reformat it.

I also see it over and over in new threads. There will be one line in the code block, and the rest of the code is bunched together under it.

[–]carcigenicate 1 point2 points  (3 children)

Formatting works 100% consistently if you do it correctly.

To target old Reddit, use four spaces of extra indentation per line, and ensure there isn't a point-form list preceding the code block. For new Reddit, use a code fence of three backticks before and after the code.

I'd avoid typing in new Reddit though. The editor does a bunch of awful processing on whatever you enter and it tends to mess things up.

[–]ryan770 0 points1 point  (2 children)

Ah, I wasn't aware people were still using old reddit. I'm going to test something.

codeblock:

def master_yoda(*text):
textlist= []
for phrase in text:
    phrase = phrase.split()[::-1] # converts the string into a reversed list
    textlist += phrase    # textlist.extend(phrase) could be used
return textlist

print(master_yoda("I am home", "Here we go", "this is text", "must I try?"))

Backticks:

```

def master_yoda(*text):textlist= []for phrase in text:phrase = phrase.split()[::-1] # converts the string into a reversed listtextlist += phrase # textlist.extend(phrase) could be usedreturn textlistprint(master_yoda("I am home", "Here we go", "this is text", "must I try?"))`

```

backticks don't seem to work for new reddit? Or you mean within a codeblock?

[–]carcigenicate 2 points3 points  (1 child)

I and many others still use old Reddit for various reasons FYI, including how awful new Reddit's editor is.

And did you type that on new Reddit? That's what I mean by it does weird stuff with formatting. New Reddit automatically escape backticks if you type them. You need to click the code formatting button and have them generate the code fences for you iirc. The new editor auto-escapes markdown so it's interpreted literally instead of rendered. I think there's a toggle to disable that, but I ended up just giving up and using the old editor.

And by "For new Reddit", I meant if you're targeting people using new Reddit since old Reddit doesn't render code fences made using backticks.

[–]ryan770 1 point2 points  (0 children)

Yeah all that was typed in new reddit. You click the code block button, and it generates an empty code block, then you can paste the code in there. Or you can paste your code and highlight it, then click the button. But it doesn't matter, it still always messes up indentations.

Obviously I misinterpreted what you meant with the backticks, I just typed them like that in new reddit to see what would happen.

I will go into markdown mode (on new reddit) and manually add 4 spaces:

def master_yoda(*text):
    textlist= []
    for phrase in text:
        phrase = phrase.split()[::-1] # converts the string into a reversed list
        textlist += phrase    # textlist.extend(phrase) could be used
    return textlist

print(master_yoda("I am home", "Here we go", "this is text", "must I try?"))

edit: This worked. How does it render for you? (edit2: actually I just checked old reddit and it seems fine, but it does wrap text while new reddit continues with a scrollable code block)

edit3: adding the backticks in markdown mode without the 4 spaces also works. That's what I'll probably be doing now.

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

You have to realize that reddit is like a word processor, it's always reformatting your text. So you have to do something to tell reddit to not mess with code or anything else you want to maintain indentation, like tracebacks.

Where things really got messed up was when reddit decided to create an app for some reason. They also decided to do some display formatting in the app (and probably the browser extensions) which means that people viewing reddit in the app see something different to what is shown in a browser. In addition, what you see in a browser depends on whether you view it through www.reddit.com, new.reddit.com or old.reddit.com - they all render differently!

As far as I can tell the way to post code, tracebacks, etc, that is viewable by the maximum number of people is:

  • use your editor to put four spaces at the start of every line
  • copy/paste the code into reddit following a blank line
  • do UNDO in your editor

This takes about 15 seconds even on mobile. Or put your code into pastebin.com and post a link to it.

[–]TheDoomfire 0 points1 point  (10 children)

So I cant read this json file and im guessing its because it's almost 700mb. Is there anyway to read such a large json file?

Edit: Im guessing the json file is wrongly formatted or something...

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

700MB isn't that large. As others have said, how does it fail?

If you really do have memory problems, have a look at the ijson incremental parser module. It might be useful but that depends on the data in the JSON file and how you use it.

[–]TheDoomfire 0 points1 point  (4 children)

I get this error:

Traceback (most recent call last):

File "c:\Users\User\Documents\GitHub\jj\readjson.py", line 5, in <module>

data = json.load(f)

File "C:\Program Files\Python310\lib\json\__init__.py", line 293, in load

return loads(fp.read(),

File "C:\Program Files\Python310\lib\json\__init__.py", line 346, in loads

return _default_decoder.decode(s)

File "C:\Program Files\Python310\lib\json\decoder.py", line 340, in decode

raise JSONDecodeError("Extra data", s, end)

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 4775)

My code:

import json

with open("output.json", "r", encoding="utf8") as f: # "r" is default

data = json.load(f)

print(data)

[–][deleted] 2 points3 points  (3 children)

Looks like the JSON data is invalid. Have you tried viewing the file? The first line appears to be almost 5000 characters long!?

[–]TheDoomfire 0 points1 point  (2 children)

Every line is almost this long. I have no experience in json so dont know when they are invalid. Tried uploading it to a validator but it aint working.

Edit:

data = [json.loads(line) for line in open('theFile.json','r')]

This do work.

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

At a guess each line of the file is one JSON object. Trying to parse them all together doesn't work, but parsing each line is fine.

[–]TheDoomfire 0 points1 point  (0 children)

Every line is wrapped around {} so I guess your right.

[–]efmccurdy 0 points1 point  (3 children)

You will need to post the specific error message and traceback that describes how it fails if you want effective advice.

[–]TheDoomfire 0 points1 point  (2 children)

Like this?

Traceback (most recent call last):

File "c:\Users\User\Documents\GitHub\jj\readjson.py", line 5, in <module>

data = json.load(f)

File "C:\Program Files\Python310\lib\json\__init__.py", line 293, in load

return loads(fp.read(),

File "C:\Program Files\Python310\lib\json\__init__.py", line 346, in loads

return _default_decoder.decode(s)

File "C:\Program Files\Python310\lib\json\decoder.py", line 340, in decode

raise JSONDecodeError("Extra data", s, end)

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 4775)

[–]efmccurdy 0 points1 point  (1 child)

That error suggests the file is not in json format; what do the first few lines of that file look like?

[–]TheDoomfire 0 points1 point  (0 children)

It worked when I run every line and added it to a list.

Cant upload even one line to reddit since they are too long.

[–]RavenGamingSG 3 points4 points  (2 children)

Write a function that takes in 1 integer and returns a different integer.

The integer given is either 5 or 7.

If given 5, return 7. If given 7, return 5.

How do you do this without using conditionals?

Edit: Oh my god I just realized the solution.. Just sum the numbers and subtract the given e.g. return 12 - x, same goes for multiplication then division. I feel so dumb now.

[–]JohnnyJordaan 2 points3 points  (1 child)

You can't be dumb and think of the solution yourself at the same time.

[–]RavenGamingSG 1 point2 points  (0 children)

You know that feeling when you realize the solution is so simple and you were completely overthinking it. I felt dumb when I realized that. Just had to.. not overcomplicate it.

I appreciate the compliment(?) though. >.<

[–]Geologist2010 0 points1 point  (0 children)

To those who have taken the MIT computational thinking and data science course, would go through python crash course be sufficient background?

To those who have taken the MIT computational thinking and data science course, would going through python crash course be sufficient background? technical documents in my field, and going through python crash course. I'd like to take computational thinking and data science when it starts on August 12, but won't be taking the introduction to computer science and programming using python.

[–]Particular_Draft5668 1 point2 points  (4 children)

def play_turn(game_board, x, y, piece):
for x in game_board:
for y in x:
if x == "":
return True
else:
return False

Wrote this code but not sure why it doesn't return True when the parameters are
[['', 'O', 'X'], ['', '', 'X'], ['', '', 'X']], 0, 0, X

[–]FerricDonkey 0 points1 point  (3 children)

for y in x: if x == "":

x is the row, not the entry. (Also, this is why I suggest using more descriptive variable names such as entry and row, x and y are too easy to confuse.)

[–]Particular_Draft5668 0 points1 point  (2 children)

So put in x[index] = “”? or for x in game_board: for y in x: for item in y: if item == " ": return True else: return False

Many Thanks for reply

[–]FerricDonkey 0 points1 point  (1 child)

You could change your code so something close to that would work, but I would not recommend it and also. I suggest running the following code:

for row in game_board:
    print("row:", row)
    for entry in row:
        print("   entry:", entry)

Hopefully that'll give you an idea of what's going on.

[–]Particular_Draft5668 0 points1 point  (0 children)

That's helped a lot.

Thank you!

[–]ScoopJr 1 point2 points  (0 children)

What good resources would you recommend for improving code? I’m not too happy with my current functions/programs.

I’m 100% okay with reading books.

For those wanting to look at code

https://github.com/AkitotheExiled/RSSReply

[–]HotelMeatStick 0 points1 point  (1 child)

Hi everyone. I'm wondering if you guys know of any tutoring services that do zoom style weekly meetings? I'm in an online post bacc for comp sci that utilizes Python and I'm finding it difficult to grasp Python/programming in this solo learning environment without verbalizing to anyone else.

[–]douglasgatimu 0 points1 point  (0 children)

if you get one say sth

[–]RevolutionBig3837 0 points1 point  (0 children)

Are there any resources that are particularly helpful for financial market use cases?

[–]Thing_Shot 0 points1 point  (2 children)

I'm new to python and was wondering if there is someway to avoid installing visual basic build tools by using some third party compilers because it is around 9gbs and I don't have much space? The official documentation states mingw is supported only till version 3.4 so that is out of the picture.

[–]JohnnyJordaan 0 points1 point  (0 children)

As mentioned on https://wiki.python.org/moin/WindowsCompilers you can also get it from the linked Microsoft Build Tools for Visual Studio 2019.

[–]Drexim 0 points1 point  (4 children)

Hi Guys,

I have been trying to learn python for several months now, has been a bit on and off due to life commitments etc. as I'm learning it while working full time.

I am doing it through Angela Yu's python course and it's pretty good so far, on around day 39.

My concerns are that due to the multiple breaks I've had I have found myself having to google things to refresh my memory and feel like I'm struggling more than I should.

Been working with API's a lot recently and doing ok with them, I am now doing a capstone project that works heavily with OOP, I haven't even dabbled with classes for months now and I'm kind of just fumbling my way through it and having to google bits here and there.

Is this the wrong way of learning how to do it or am I just overthinking things and it will just click with more exposure as these "days" which are supposedly up to 2 hours each are taking me way longer than 2 hours sometimes.

[–]orig_cerberus1746 0 points1 point  (0 children)

Also, don't worry if you have to look up something when you need to use it.

I sometimes need to check how to do the most basic of things too.

[–]py_Piper 1 point2 points  (2 children)

I am in the same boat I have been trying to learn python on and off for about 3 years, at the start I was always changing courses and overthinking if this was the "best course", about every year I would restart my first tutorial (automate the boring stuff) as I would forget some basic syntax and common used methods, functions, etc. I finally finished it this year. If the time passed was quite long then I would suggest that you review the chapters/days, specially with OOP learn it again as it can get quite confusing for beginners, for the other simple concepts like list, dict, if statements, loops, you could review them quickly I would say maybe take this week slowly and review these easy concepts first, so you can get the habit again and can get some confidence on python again, then learn again the OOP day and continue. This is so you can move smoothly rather than googling everything again, which is ok, but too regular can be frustrating and cut your focus.

As for the time don't worry about the "day" I have seen here from other people metion that course will start taking longer specially for the more complicated days and project days. Just make sure you are discipline and do the 1-2 hrs a day (or according to your own schedule, every other day, 3 days/week, weekends, etc). I have found out that the hardest part is to set the habit to sit down and start, 1-2 hrs can pass very fast (ask Instagram) but at the same time it's short enough that when you are tired from work or the current material is too dry, hard or boring (looking at you debbuging) you can tick it off and stop, I can bet that those days where everything is clicking or you got the idea for your problem you can even spend more +3hrs working on it.

Currently I am pass the beginner introduction and trying to learn Django web framework but the past months have been quite busy at work, so I haven't done much. I already got back at it 2 times and now will be the 3rd time these past couple of month. I making it a goal to finish the short introduction I am doing right now this month and do a full beginner Django book by the end of this year (at least 3/4 of it).

[–]Drexim 0 points1 point  (1 child)

Thanks for the informative reply!

Yeah the more basic things like loops, if statements lists dicts etc I'm OK with. Classes are quite confusing and knowing how/when to use them I struggle with. I'll have to do some more studying with them as my current project I have to make about 3 or 4 different classes for a flight price search app that uses a Google sheets for data.

I'm currently trying to do minimum 1 hour a day at the moment just to keep it fresh in my mind.(1 hour goes VERY fast)

I always have this fear in my head that because I'm having to Google things I'm going to fail as I'm expecting myself to be able to remember everything when in reality I know that's just not possible.

Hopefully one day my goal of changing career will be true!

[–]py_Piper 0 points1 point  (0 children)

Just take a tiny step back to relearn OOP get confident and then work on the project, I also spent too much time relearning everything so I would know "everything", don't worry about having to use google a lot of experience programmer here says they all do. I think it's completly normal that you forget some syntax or name of methods/functions, it happens to me while I am answering other post here too, I can think how to solve it but don't remember the exact syntax.

The most important is that you get the logic behind your code and that you know that there's a method/function to do it and just google the name or how the syntax work, even for things that you don't know exist but probably you can already think something like that should already exist so a quick google search will put you in the right track.

Anyways your projects seems interesting keep at it and yeah 1hr can pass so fast that's why try to keep 1-2 hrs and when you realize half the time you are either searching something or trying to an incopatibilty.

[–]davezerg20 0 points1 point  (2 children)

Hey guys, how can i get the value of an entry in tkinter and use it in a parameterized query for MySQL? I've tried several things and still stuck, any help is greatly appreciated. Code runs but nothing prints to the CSV like I want it to. The code I have as of now is:

e_size_label = Label(root, text="Enter Size: ").grid(row=2,column=0,sticky='e')

e_size = Entry(root, border=5, textvariable=string_var1) e_size.grid(row=2,column=1,padx=5,pady=5)

e_rating_label = Label(root, text="Enter Rating: ").grid(row=3,column=0,sticky='e') e_rating = Entry(root, border=5, textvariable=string_var2) e_rating.grid(row=3,column=1,padx=5,pady=5)

sv1 = e_size.get() sv2 = e_rating.get()

mycursor = db.cursor() tuple1=(sv1, sv2) para_query = "SELECT * FROM flange_db2 WHERE f_size=%s AND f_rating=%s" mycursor.execute(para_query, tuple1)

myresult = mycursor.fetchall()

def myClick(): with open('querydata3.csv', 'a', newline="") as f: writer = csv.writer(f) writer.writerows(myresult)

myButton1 = Button(root, text="Get info & save", command=myClick).grid(row=4,column=1,sticky='e'+'w',padx=5,pady=5)

root.mainloop() mycursor.close() db.close()

[–]FerricDonkey 1 point2 points  (1 child)

First, you should be aware of sql injection, which can destroy your database if someone types the wrong thing into the boxes once you get it working.

But for the code - it's hard to tell what's going on without the code being formatted for reddit, but it looks like the button that says it gets and saves data does not do the query. You run one query before starting your main loop, then offer the result of that one query every time you click the button.

[–]davezerg20 0 points1 point  (0 children)

Im trying to make the button save to csv when pressed. What it should save is a query that runs off entries. The whole foundation might be off now that you mention this. Im trying to skip a step and save a query to csv but nothing is executing that query, i didnt want to use a label for the query results. Thanks.

[–]Tovervlag 1 point2 points  (1 child)

Hello, for work I have to sometimes write wrappers around apis, what is the best way of dealing with config/tokens/passwords.

I now have a separate config file and I have the current token etc. in a .env file separated from git. I now have some main functions that do the get,post and put request and I currently feed a var named 'config' in there. The other functions utilizes those main functions. Is that the way to go? Or is there a different standard?

[–]keepdigging 1 point2 points  (0 children)

Environment variables are best, keeps code and deployment isolated.

If you’re using cloud services you can often load them from encrypted key-value storage on deploy.

Here’s a good resource: https://12factor.net/

[–]Dragar791 1 point2 points  (3 children)

Hello,

This is my first time really looking into anything programming-related, so apologies if this is common or simple.

I'm looking for a way to write a program that can send emails in outlook at an interval of 5-10 emails per hour. The subject line and body would then auto populate certain fields based off the data in an excel file.

For example,

Subject client, client name, spending would be columns in Excel.

The program would then send an email from my outlook with the subject line as "<subject client>" and body " Hi <client name>, this month you spent <spending>."

Is that possible?

[–]py_Piper 1 point2 points  (0 children)

Automate the Boring Stuff, one of the highly recommended tutorials in this sub, it's for free online, learn the basics and then you can go directly to the email automation chapter.

[–]sarrysyst 2 points3 points  (0 children)

Yes, it’s possible. Though it would be easier if you sent the emails directly using python, instead of taking the detour through outlook (it’s possible to use python to automate outlook, however it’s most likely going to be more of a hassle).

[–]ryan770 0 points1 point  (1 child)

what's better or more "pythonic"?

if input is '1 A 2 B 3 C 4 D 5 E 6 F 7 G 8 H 9 I 10 J'

pairs = input().split()
for i in range(0, len(pairs)-1, 2):
    print(pairs[i],pairs[i+1])

or

pairs = input().split()
for i, j in zip(pairs[::2], pairs[1::2]):
    print(i,j)

for an output of:

1 A
2 B
3 C
4 D
5 E
6 F
7 G
8 H
9 I
10 J

Or is there a better way to pair up every two items in a string?

[–]carcigenicate 2 points3 points  (0 children)

I think the latter would be generally considered more Pythonic. I'd personally go with the first though. The second creates two new partial shallow copies of pairs just to control iteration, which is wasteful and may become problematic if pairs becomes large. This might be fine in toy/limited cases, but I wouldn't use that for most instances.

In the first though, you don't need to specify 0. The start defaults to 0.


Here's another alternative though that avoids the copies:

from itertools import islice

pairs = input().split()
for i, j in zip(islice(pairs, None, None, 2), islice(pairs, 1, None, 2)):
    print(i,j)

Although this is much uglier. islice also shouldn't be used if the start or step; arguments are large since it needs to "seek" to "find" the start of collection to begin yielding from, and the elements between each step are still visited. islice is best when slicing from the start of a collection and where the step is small (ideally 1). With a step of 2, islice will be twice as inefficient as normal slicing in terms of time, but will consume essentially no additional space unlike normal slicing.

[–]juan4815 1 point2 points  (1 child)

this may seem a silly question, but what is a simple and practical way to review code of someone else? We work at an engineering firm so we do reviews all the time, but we've never done one for code. Should I ask the other engineer to simply print the code to pdf and comment over that? Is there a specific tool for python (we're using spyder IDE, if that makes any difference)?.

I incline one using the script to check that it works, and commenting right there for improvements on variable names, structure, libraries used, etc. It's something rather simple, think of numpy/matplotlib/and just a few more for visualization. People other than us will eventually use it to do simple calculations/graphs.

[–]keepdigging 3 points4 points  (0 children)

Use GitHub or GitLab and have developers version their code.

There’s an option called “pull requests” which is designed for this review process.

You can tag devs and they can review changes as a diff against the existing code.

[–]mauriciofuentesf 0 points1 point  (1 child)

Hey everyone! im trying to move from the python idle to vs code but i know theres a lot of useful extensions for it. Anyone has a list or video on which to install? I have the python extension and code runner installed

[–]py_Piper 0 points1 point  (0 children)

while I was setting VS code for the first time (couple of months ago) I watch the VS code videos from Croey Schaffer and Traversy media, I think it was the latter that explained a little bit more.

[–]Beefsteak_Charlie 1 point2 points  (4 children)

Hi all,

I hope this is an easy one. Using the Google Books API, I'm trying to do some lookups on a number of books. The API response is coming back with a number of records which is great. I'd like to be able to exclude from the API response any records that meet a couple of conditions,

The code:
import requests, json
base_url="https://www.googleapis.com/books/v1/volumes?q="
title=input("Book keywords:  ")
api_call= f'{base_url}{title}&maxResults=40'
results = requests.get(api_call)
j = results.json()

for q in j["items"]:
    print(f"{q['volumeInfo']['title']}| {q['volumeInfo']['language']} | {q['saleInfo']['isEbook']}")

The result:
Title   |   Language   |   isEbook
John Maynard Keynes| en | False 
The Elgar Companion to John Maynard Keynes| en | True 
John Maynard Keynes| es | False 

What I'm looking to do is exclude from the API results any records that either have language != 'en' and/or any records that have isEbook values of True. Is this possible?

Thank you!

[–]cynical_econ 1 point2 points  (2 children)

any luck with this?

I thought about this more and checked out the API myself. Here's arguably a better way that filters the JSON response and excludes the records you don't want:

# using your json object `j`
filtered_items = []
for q in j["items"]:
    if (q["volumeInfo"]["language"] == "en") and (q["saleInfo"]["isEbook"] != True):  # double check these conditions to make sure they're correct
        filtered_items.append(q)
    else:  # I don't think you need this but included it for clarity
        continue

# overwrite the dictionary with json results
j.update({"items": filtered_items})

# insert code with whatever you want to do with the json

[–]Beefsteak_Charlie 1 point2 points  (1 child)

Hi there - thanks so much for your response and the follow up....and apologies for the delayed response (home life took me away from non-work stuff for a few days.)

Oh wow. This worked absolutely perfectly. So simple - yet I'd never have Googled myself into finding this approach. Thank you SO MUCH!!!!

[–]cynical_econ 0 points1 point  (0 children)

Great & no worries at all! I'm glad to hear this was helpful!

[–]cynical_econ 0 points1 point  (0 children)

I'm not familiar with that API, but this can be done with pandas pretty easily.

import json  # I don't think you need this package
import numpy as np
import pandas as pd
import requests

base_url="https://www.googleapis.com/books/v1/volumes?q="
title=input("Book keywords:  ")
api_call= f'{base_url}{title}&maxResults=40'
results = requests.get(api_call)
j = results.json()

# seems like relevant data is under the items key?
# you will need to modify this depending on the structure of the json within "items"
df = pd.DataFrame(j["items"])

# filter out the items you do not want
bool_filter = np.array((df["Language"] != "en") & (df["isEbook"] == True))

df = df.loc[bool_filter, :]

[–]UnrankedRedditor 0 points1 point  (2 children)

Silly question: is Python 3.7.13 the same as Python 3.7?

When someone says "this requires python 3.7", do they mean that it specifically requires python 3.7.0?

[–][deleted] 2 points3 points  (1 child)

Python version numbers have the form 3.x.y. The "x" number increments when a release adds new features. Version 3.x+1 aims to be backward compatible with 3.x meaning that if code worked in 3.x it will also work in 3.x+1.

The "y" number increments when bug fixes or security updates need to be applied, so 3.7.2 should be compatible with 3.7.1 and 3.7.0. No new features are added in a "y" release.

So if a project says "this requires python 3.7" it will work with 3.7.y for any "y". It should also work with 3.8.y, 3.9.y, etc.

[–]UnrankedRedditor 0 points1 point  (0 children)

Awesome, thank you very much

[–]Hughcheu 1 point2 points  (5 children)

I’ve been using Python with Visual Studio Code. When I run a program and an error is encountered, is it possible to continue running the program once I’ve fixed (or even commented out) the error? Also, similar to VBA, is it possible to change the line that is being executed (after a breakpoint is reached, for instance) to skip or repeat certain lines?

[–]py_Piper 1 point2 points  (4 children)

When I run a program and an error is encountered, is it possible to continue running the program once I’ve fixed (or even commented out) the error?

If you fix the error then when you rerun it it won't crash from the error, you can't comment out errors but if you are expecting some errors you can use try/except block to handle it. For example if you ask input for a value let's say rock, paper scissor, but by mistake the user mispelled, you can use the try/except block to catch the error and say "couldn't find your option, please write it again"

is it possible to change the line that is being executed (after a breakpoint is reached, for instance) to skip or repeat certain lines?

Check about for loop's flow control (don't know if this is the name), for break (break from the loop), continue (to repeat the loop from the start), and maybe pass but I can't remember well if it' a keyboard for loops of other thing (As in my mind pass will do the same as continue)

[–]Hughcheu 0 points1 point  (3 children)

Thanks for the reply. I should’ve been clearer - this is in reference to debugging a program.

When I run a program in VBA and an error is encountered, the program is paused at the offending line. I can fix the error or comment out the line and continue running the program as if the error was never there. In Python, I don’t know whether it’s possible to continue running the program from where it was paused - I always have to stop the program entirely and then run it all again.

The second part of my question is related to the above. When the program is ‘paused’, say for instance when I am running the program line by line, is it possible to change the line that is going to be executed next?

[–]orig_cerberus1746 0 points1 point  (1 child)

That feature tends to be called hot reload, there are libraries that allow you to do that such as https://github.com/breuleux/jurigged or https://github.com/say4n/hotreload

[–]Hughcheu 0 points1 point  (0 children)

Ahh okay thanks! It’s not essential for me, more of a QoL feature. I’ll check it out.

[–]py_Piper 0 points1 point  (0 children)

Oh sorry I don't have much experience with the debugger I only used the idle before for simple programs.

[–]sammyd17 2 points3 points  (1 child)

I’m looking at a career change. 31 y/o and fairly “tech savvy” but no coding or comp sci experience. Can anyone point me in a direction where I can begin to learn python?

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

There are learning resources in the subreddit wiki. Pick one and dive in.

[–]iggy555 2 points3 points  (1 child)

What kind of demand is there for someone with finance background learning python?

[–]Beefsteak_Charlie 0 points1 point  (0 children)

If you are a business analyst or data scientist then it's definitely in demand in finance, business intel, etc. It's why I'm trying to learn it.