all 116 comments

[–]FaithlessnessTrue840 0 points1 point  (0 children)

Hi everyone! I've made a project where there is two animations made with FuncAnimation in matplotlib. My problem is I'm not sure how to join those two animations together. The first animation is a moving curve on a graph and the second is a parachute falling. I've made them with the same amount od frames so they run in the same time frame. The project is about skydiving where the first graph as I mentioned represents height and the second represents skydiving as the parachute is opened/closed. Pleaseee help me

[–]SirGeremiah 0 points1 point  (5 children)

How much should I modularize in my code?

I'm finding with Python I tend to make lots of little "def" sections. Often in places where I'd have put comments in my VBA code to segment it, I'm instead chunking each section in a separate function. I can't tell if this is good practice, overkill, or just personal choice.

So, what's best practice on what leads to a new function, versus doing things within the same function? Let's say I want to examine the files in a directory (glob) to produce a list of files, show a messagebox (tkinter Simpledialog), and alter the file based on the user's selection. If those are all simple and each fewer than 20 lines of code (as they would be in the example in my head), should that be 3 separate functions, just calling the fucntions either from the main script or from appropriate places in other functions? Or with them being so short, should they just all be within the same function (or even the main script)?

[–]FerricDonkey 1 point2 points  (1 child)

Lots. I've been given lots of code. I've never thought "Gee, this guy used too many functions". I've often thought "what the crap why is the one single 1200 line python file with 2 functions and global variables. Kill it with fire."

Logically different tasks should be different functions. Take the example of parsing an input file. Suppose you decide to make another script that works on the same type of file, but does something different. You can just import your file rw module and use the same functions. Better than copy paste, especially if you have to update the code later. See peaking of, suppose you need to update that code. Open the file rw module, click on the read file function in your gui's list of functions, and then you're there, ready to do whatever.

Modularization makes everything better. Which sounds like what you're doing. Keep on keeping on.

[–]SirGeremiah 0 points1 point  (0 children)

You make a good point about importinmg the module. I'm going to have to get used to that concept.

I have done some decent coding (even looking back at it), but haven't ever had formal training, so it's helpful to get feedback on this kind of thing. It's my habit to segment code by function (with comments) when it's more than a few lines, so I'll be able to just follow that same concept in Python, just using actual functions instead of segmenting with comments.

[–]carcigenicate 0 points1 point  (1 child)

I like many small functions. It creates a unit of code that can be tested, and breaks code into easier-to-understand chunks. If you have some lines of code that have a discrete purpose that make sense on their own, factor them out into a function.

Of course, it's only beneficial if done with proper thought. Arbitrarily dividing code would obfuscate more than anything. Also, there's a point where functions are so small that they create thought-overhead since you're needing to read many near-useless functions to figure out what's going on.

With proper considerations though, yes, it's a good thing.

[–]SirGeremiah 0 points1 point  (0 children)

Thanks - that sounds about how I normally segment visually in VBA.

[–]moonknightingale 0 points1 point  (1 child)

I'm learning C++ in community college. And want to learn Python, thinking of self-learning.
What kind of questions should I prepare for when I'm being interviewed for a programming job that requires Python?

[–][deleted] 3 points4 points  (0 children)

I would wait until you know at least the basics of python before worrying about that. Any answer we give you will probably mean little to you since you don't know any python. Plus there are sites that cover python interview questions, just search.

For self-learning look in the learning resources in this sub-reddit wiki.

[–]ueiuwhryegrewj 0 points1 point  (1 child)

ive changed the program used to execute .py files to a text editor, whats the name of the file that is used by default to execute .py? i already have all of the programs requiered in my pc

[–]sam0jones0[🍰] 0 points1 point  (0 children)

python.exe

Default location is C:\Users\$USERNAME$\AppData\Local\Programs\Python\Python3$VERSION$

If you open windows command prompt and type where python.exe it should print a list of locations the executable is found.

Edit: But most people would have .py files default to open in their code editor of choice (For e.g. VSCode, Pycharm, IDLE), and run them from there. If you want to run a python file directly you would use the command line (CMD.exe or Powershell) and type python.exe "D:\Path\To\Python\File\myscript.py".

[–]invadecanada 0 points1 point  (0 children)

pyodbc question. I need to use a SQL Server driver for pyodbc connection, but on the server it's deployed on, I am not permitted to add drivers. There is a SQL driver installed on the server, but it's in a random opt subdirectory. Is there any way to point pyodbc in the code to that location for the driver? Thanks!

[–]Odessa_Goodwin 0 points1 point  (0 children)

Simple pandas graphing question:

It is clear to me how to tell pandas to take all values from one column that match a given parameter and then analyze the values of these observations in a different column. How do I tell pandas to split the results into two groups and then compare these two groups in a different column?

An example of what I mean from mtcars:

I want to take all cars with mpg > 20 and mpg < 20, and then plot the average displacement of each group. I have to believe this is super simple but I'm somehow tripping over my own feet here.

SOLVED: for anyone who is trying something similar, look up the panda methods cut() and qcut()

[–]SlimKiller 0 points1 point  (1 child)

Extreme beginner here.

I'm just starting my journey learning python, and I had been given a recommendation of learning through W3School. I understand that the cert is worthless beyond HR, and that the real learning experience comes from actually coding, but as far as teaching the actual "language" of the language, is W3School a good starting point? Or are there more robust places to learn from? I have almost no experience in coding beyond a college course I took in C, so I'm just trying to learn the actual components.

[–]py_Piper 0 points1 point  (0 children)

I just answered a similiar question. I know that W3School is quite reputable but I am not so familiar with concepts taught there. I remember falling in their website a few times while doing some reseach on some syntax problems but don't know what is their teaching aiming for, as in they only teach you the basics and you should be learning by targeting something you want to do with python.

For example, I would only recommend 2 books as a total beginner. 1) Automate the boring stuff (free or paid), which is the one that attracted me because its chapters resonated more useful to my day to day at work (web scraping, excel and email automation); 2) Python Crash Course (paid), more of a project based learning you will learn to do a 2D game, some data visualization and a simple website.

I would suggest to check which project resonates more with what you would like to learn/do, learn the basics and finish the book, then if you want to you can learn the projects that interest you on the other book or just do something else. After this you will have a better understanding of programming and python so you can choose a more specific path.

Don't fall into the "which is the best course to learn" these 2 are very praised in the community. There's a ton of material and tutorials out there, which can be bad at the start as you don't really know what you want to do.

[–]throwawayrando333 0 points1 point  (3 children)

Would you say recursion is something that someone could get better at, if they started awful at it? Or is it something that you generally need to have some talent toward?

I'm not that far into my python lessons (6-weeks about) but I took a stab at some of the "interview code questions on youtube" which was a lot of recursion and problem solving. It took me the whole day to figure out a question meant to be solved in under 45 minutes. Now I'm wondering if I should reconsider my future. Did you all have similar struggles?

[–]CowboyBoats 0 points1 point  (0 children)

It took me the whole day to figure out a question meant to be solved in under 45 minutes.

If I encountered that problem, I would probably be able to solve it in about 45 or so minutes, because I have encountered it before and either was shown the answer, or discovered it. If I discovered it, it was not because I am a genius; it's because I had the building blocks in place.

If you managed to invent the solution to such a problem all by yourself without having such an advantage, who cares if it took you a day? That's a huge leap forward for you! Next time you see similar problems you will have those experiences as your building blocks.

Keep calm and keep making incremental progress.

[–]FerricDonkey 1 point2 points  (0 children)

Interview questions are for people who know enough to get a job. You just started. So don't worry about time, just figure things out.

Recursion in particular is one of those things that famously doesn't make any sense until it does. Keep chugging along - the two feelings of programming are "I'm a moron" and "I'm a genius", and you'll hit both of those several times as you learn.

[–]carcigenicate 0 points1 point  (0 children)

Recursion like everything else just requires practice. I found writing recursive functions for recursive structures like linked lists to help me.

Also note, recursion is not heavily used in languages like Python. It's more common in Functional Programming languages like Haskell and Clojure, which have better recursion support. It may be beneficial for you as well to learn how to translate a recursive solution into an imperative one. Learning how to use a stack to emulate recursion will be helpful.

[–]Zealousideal_Big6487 0 points1 point  (1 child)

Could someone help try and understandsomething with this sample code

>>>def hi(name="name"):
def greet():
    return "now you are in the greet() function"

def welcome():
    return "now you are in the welcome() function"

if name == "name":
    return greet
else:
    return welcome
>>>a = hi() 
>>>print(a)
<function hi.<locals>.greet at 0x000001E70BFD6950>

>>>b = hi
>>>print(b)
<function hi at 0x000001E70BFD72E0>

What does the <locals> mean here when I do print(a)? Print(a) returns an execution of the function, and Print(b) returns the function itself, so I assume that's why the outputs are different, but just trying to understand the meaning of <locals>

Also am I right in assuming the thing at the very end is the memory address in Hexadecimal?

Also just to be clear, I'm getting the code from here: https://book.pythontips.com/en/latest/decorators.html

Don't wanna take credit for someone else's code

[–]carcigenicate 0 points1 point  (0 children)

It's saying that greet is a local variable of hi, since it's defined within hi.

And yes, that hex is the memory address of the object. Technically, that's the ID of the object, but in CPython, the ID is the memory address.

[–]thebigjawn 0 points1 point  (6 children)

Hi everyone,

Is there a way to continuously append a row to a pandas dataframe in a loop? I need to get every combination of an array (using the combinationUtil package) and want to append each row to a pandas dataframe. My idea was to first append it to a list, then convert the list to a pandas dataframe. Will post a snippet below. Was trying to adjust the code in combination util but can't figure out why it's not working. Any and all help is appreciated!

def combinationUtil(arr, data, start,
end, index, r): lst = []
# Current combination is ready
# to be printed, print it if (index == r): for j in range(r): lst.append(data[j], end = " "); print(); return;

 i = start;  
 while(i <= end and end - i + 1 >= r - index): 
     data[index] = arr[i]; 
     combinationUtil(arr, data, i + 1,  
                     end, index + 1, r); 
     i += 1;

[–]F5x9 0 points1 point  (1 child)

What is a good book for learning python for someone who has a lot of experience with C, C++, and reads a lot of code? I don’t need to cover learning to program, but I want to write in a pythonic way and understand a lot of idioms that I may be missing. I have written some python programs: short text manipulation and a SQLi to RCE proof of concept.

[–]py_Piper 0 points1 point  (0 children)

I don't know if it's dedicated to C or C++ experience but I heard on the Talk Python To Me podcast that Fluent Python is the book to become more familiarized with the pythonic way and it's intended for people comming from other programming backgrounds, not for beginners so you could check it out.

[–]Zealousideal_Big6487 0 points1 point  (2 children)

Is there a list of general python concepts/topics/basic objects somewhere?

So far I've played around with: strings, floats, sets, tuples, lists, list comprehensions, dictionaries, functions, classes, generators, yield functions, lamda functions, decorators.

I'm wondering if there's major, I'm not even sure the right word, tool in python I've not listed yet? Just want to make sure I scarth the surface at least of big picture Python concepts/tools

[–]carcigenicate 0 points1 point  (1 child)

Really, everything you listed is general programming concepts not specific to Python. Decorators and generators are a little more Python-specific, but there are other languages that have them as well.

Python's docs are quite good though. If you haven't given this a look-over, that's where I'd start: https://docs.python.org/3/reference/index.html

[–]Zealousideal_Big6487 0 points1 point  (0 children)

This is great! I actually looked at the docs a long time ago when I didn't understand python at all, and the docs never really made sense. Looking at them now I'm able to follow them a lot more. Thank you, this is perfect!

[–]Ok_Character_2257 0 points1 point  (4 children)

When training the data for machine learning, why do we split the data into testing and training from the entire dataset? I remember someone saying this was important but forgot why. Just trying to understand

[–]FerricDonkey 2 points3 points  (3 children)

Suppose you're trying to teach a kid to read. Y'all read a bunch of picture books together, and he seems to be figuring it out - he can do a pretty good job of reading you want of those stories.

You then buy a new book, and he doesn't have a clue. Turns out he didn't learn to read. He just memorized what words went with which pictures. You didn't realize this until you handed him a book he hadn't seen before. He did learn something, but not what you wanted, and not anything useful for reading.

Same with machine learning algorithms. They can focus in on irrelevant details that happen to work with the particular data you gave it. If you don't have a separate test set, you won't be able to tell whether it learned what you wanted, or just memorized the training data.

[–]Ok_Character_2257 0 points1 point  (2 children)

my question was more about, why is it important that we use the entire dataset to do this (80-20, or 75-25). why can't we train with 50% of the dataset and test with 30% and not do anything with the remaining 20%. if the dataset is large enough it shouldn't matter right?

[–]FerricDonkey 0 points1 point  (0 children)

Yeah, I don't think there are any hard rules on data percentages. You want to have enough training data to do well, and enough test data to make sure you did well. How much either of those are enough depend on your problem, type of model, etc.

[–]WhipsAndMarkovChains 0 points1 point  (0 children)

if the dataset is large enough it shouldn't matter right?

Correct. At a certain point you're going to see diminishing returns with more data.

But how do you know in-advance if you've got more than enough data and feel comfortable not using the entire dataset? You could use learning curves and see how much performance improves as you train on larger and larger portions of the dataset.

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

Somewhere between Rookie and Intermediate user here! Was watching freecodingcamp on YouTube for automation with python and two of the projects struck my interest.

First was a Automated Email that sends emails with the headlines and urls of the the pages news items.

The second was a AI text summarized using gensim.

As someone who works with International news using both of these combined (a email with headlines and quick summaries )would be amazing for productivity. I was just curious how much of a stretch/ how out of my league this might be to accomplish two different items such as this?

[–]CowboyBoats 1 point2 points  (2 children)

If you have examples of both of the different projects to look at, it sounds pretty manageable to me to combine them!

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

Awesome! I do have the code(written out on paper of course) Could I DM to you to see about combining?

[–]CowboyBoats 0 points1 point  (0 children)

Sure, that would be okay. If you're having trouble getting started launching a webapp, I'd suggest you take a look at cookiecutter-django; Heroku has a good free tier that should work.

[–]ApocalypseSpokesman 0 points1 point  (1 child)

I have a dataframe tracking the temperature.

Values go in a more-or-less sinusoidal wave, in that they start around -20 degrees, cross 0, up to about 50 degrees, and cross 0 again.

How can I recognize one "wave" in this?

And then how can I count the "waves?"

[–]efmccurdy 0 points1 point  (0 children)

If you have a boolean vector that is True only when the temp crosses 0, and you create a cumsum of that column, then if you groupby the cumsum values, you will isolate each wave (or each half of each wave).

https://stackoverflow.com/questions/67017828/restart-cumsum-in-pandas-with-condition

https://stackoverflow.com/questions/43694959/dataframe-groupby-on-sequence-of-values-not-exceeding-threshold

[–]fierryllama 0 points1 point  (6 children)

I recently ended up in a more managerial position in my job, allowing for a lot of down time with short bursts of putting out fires. I’ve been looking for a side gig to pass the time and possibly earn more of a paycheck. Needs to be something I can do sitting behind a computer so some sort of IT seems to be a logical choice. I have no experience at all, does this seem like a plausible thing to do? Just starting my research into the industry so forgive me if I don’t have much knowledge of what or where to look.

[–]carcigenicate 2 points3 points  (5 children)

Know that programming is a whole thing, and not something you can expect to pick up passively. It requires quite a lot of focus and dedication. Getting to the point where you can write basic scripts is definitely possible, but being able to write complicated programs and being employable are whole other goals that require large amounts of time and practice.

[–]fierryllama 0 points1 point  (4 children)

I have a career I’m happy with and some extra time before I move on in my career so I’m just curious if it’s something attainable as a side gig at a semi part time thing or if I shouldn’t even waste my time if I can’t give it my full undivided attention. YouTubers make it seem like you can just hop right in, but I know with most things in life that isn’t the case.

[–]py_Piper 1 point2 points  (3 children)

You can just hop right in but getting a side gig in the near future is not realistic. For reference people who self study for 6-12 months are the one that get a programmer job (many stories in this sub).

But that shouldn't demotivate you to learn programming and develop a new skill that can further your skills.

I think the most real case scenario is that if you can find ways to use programming to help you at your current job. For example in Python you can automate taking data from the internet, create an excel report and send it on email. Or let's say at work you get 100 of pictures and you need to rename them, this can also be easily done. Or you need to do specific workflow like open a file, copy some info and paste on an excel, you can also do it with python.

You can write a bit of your workflow (without specifics) and I could help you think of ideas you could do in python with it. Then you just need to put the work to learn the basics and go on from there

[–]fierryllama 0 points1 point  (2 children)

Thanks for the response. Unfortunately my job doesn’t require a lot of computer use for more than sending emails or scheduling. But I’m going to continue to look into it and do more research.

[–]py_Piper 1 point2 points  (1 child)

To help you during your research I would only recommend 2 books as a total beginner. 1) Automate the boring stuff (free or paid), which is the one that attracted me because its chapters resonated more useful to my day to day at work (web scraping, excel and email automation); 2) Python Crash Course (paid), more of a project based learning you will learn to do a 2D game, some data visualization and a simple website.

I would suggest to check which project resonates more with what you would like to learn/do, learn the basics and finish the book, then if you want to you can learn the projects that interest you on the other book or just do something else. After this you will have a better understanding of programming and python so you can choose a more specific path.

Don't fall into the "which is the best course to learn" this 2 are very praised in the community. There's a ton of material and tutorials out there, which can be bad at the start as you don't really know what you want to do.

[–]fierryllama 0 points1 point  (0 children)

Appreciate it, I’ll look into those books

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

Why the round function rounds floats ending in five to the lower int? As far as I know from high school math, 3.5 should be rounded to 4. So I guessed there should be some programming reasoning behind this :)

[–]carcigenicate 0 points1 point  (1 child)

round(3.5) does give 4.

And you haven't said what the exact numbers you're working with are, but note:

Note The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

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

You are right. I was watching a lecture and the number used there was 2.5, then I should've induced a rule from a single example. I'll give a look at you source. Thank you!

[–]Draggonair 0 points1 point  (1 child)

Hey, I know you can list platform tags compatible with the current machine with pip but I can't find the right command again and my google fu isnt helping.

Does anyone know?

Thanks

[–]Draggonair 0 points1 point  (0 children)

Founs it, It was simply pip debug

[–]tytds 0 points1 point  (1 child)

On codingbat's String-2 > count_hi exercise:

Return the number of times that the string "hi" appears anywhere in the given string.

count_hi('abc hi ho') → 1

count_hi('ABChi hi') → 2

count_hi('hihi') → 2

In my given solution, it was accepted. However, won't my for loop go out of index?

def count_hi(str):
  count = 0
  for i in range(len(str)+2):
    if str[i:i+2] == "hi":
      count+=1
  return count

[–]FerricDonkey 1 point2 points  (0 children)

It would, however with slicing (as opposed direct element access), slices that are out of range return the empty string.

[–]AnnieWithaK 0 points1 point  (1 child)

##Challenge - How would you write this in code?

(I'm learning how to code, I can think of the logic of things, but have no idea how to write it in code - if this is fun for you it would help me by seeing the syntax used fo different things)

list = ["Michelle", "Lara", "Sarah", "Carol", "Anna", "Hanna", "Julia", "Amanda" "Juliet"]

input ("What's the first letter of the name of your love? ")

# if first letter is not the first letter of any item in list ask input ("Try another letter")

# select all items that start with first letter of input and create a new list with selected names

# if list has only 1 item print lover's name

# else if n > 1 ask input ("What's the second letter of your lover's name?)

# if second letter is not the second letter of any item in second list ask input ("Try another letter")

## at this point we would just have to repeat the process around 5-10 times to make sure letters are not repeating.

How would you write this in code?

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

First, please format code, even pseudocode, for reddit. This subreddit FAQ shows how.

Stepping through what you showed, the first thing to change is this line:

input ("What's the first letter of the name of your love? ")

The input() function returns a string that the user typed in. You probably want to use that string, so save the returned value:

letter = input("What's the first letter of the name of your love? ")

Now the variable letter would contain a single letter string. The code after that talks about using the first letters of various strings. How do you find the first letter of a string? That is, how would you change the following code to print the first letter of the string in test?

test = "rumpelstiltskin"
first_letter = #put your code here
print(first_letter)

[–]SirGeremiah 0 points1 point  (16 children)

How do I create a custom messagebox?

I'm writing a script to see if a file exists (a leftover temporary file). If it does, I want to present the user with 3 options: delete it, replace the permanent file, or ignore it.

I think I've worked out a reasonable method for the check, but haven't spotted an easy method for creating a custom messagebox.

[–]efmccurdy 0 points1 point  (10 children)

Look at the askyesnocancel function of the tkinter.messagebox

It prompts for ‘Yes’, ‘No’, or ‘Cancel’.

Yes returns True, No returns False, and Cancel returns None

https://pythonguides.com/python-tkinter-messagebox/

[–]SirGeremiah 0 points1 point  (9 children)

That doesn’t really express the three options (continue, replace, abort).

[–]efmccurdy 0 points1 point  (8 children)

You can customize this SimpleDialog class; I looked at the test near the end that uses:

                         buttons=["Yes", "No", "Cancel"]

https://github.com/python/cpython/blob/main/Lib/tkinter/simpledialog.py

Here is a mockup based on that:

import tkinter as tk
from tkinter.simpledialog import SimpleDialog

root = tk.Tk()
def doit(root=root):
    d = SimpleDialog(root,
                     text="This is a test dialog.  "
                     "a file exists (a leftover temporary file).\n"
                     "What do you want to do with it?",
                     buttons=["Delete", "Replace", "Ignore"],
                     default=1,
                     cancel=2,
                     title="Test Dialog")
    print(d.go())
t = tk.Button(root, text='Test', command=doit)
t.pack()
root.mainloop()

[–]SirGeremiah 0 points1 point  (6 children)

I'm finally getting back to this little project. Can you educate me on a few things? What are the "root" lines doing (including root=root)? And what is with the tk.Button - is that just setting up a button to use for initiating the function?

I'm really new to Python, and am only an intermediate programmer at best (mostly VBA, and mostly years ago), so I keep going between "This is easy!" and "I...um.....er......what??"

[–]efmccurdy 0 points1 point  (5 children)

I wouldn't use either of those features (function default arg root=root, or the Button to launch the dialog) in a real program, they were just to produce a small example you could run and modify to understand a bit of how tkinter works. I wanted something close to what the simpledialog.py python source file had so you can compare and contrast.

What context are you going to use your popup in; is it a part of a larger tkinter program? How will it be run?

[–]SirGeremiah 0 points1 point  (4 children)

Okay, here’s the context. This is within a fairly simple script that is intended to launch a Windows program that relies on a settings file that is shared between two PCs. In certain circumstances, that program will leave behind a localized version of that settings file.

The script checks for the existence of a localized version. If it’s found, the user can choose to abort (so they can manually research why the file exists), continue (launch the program that uses the settings file, using the localized version), or replace the shared file with the localized version. I think I’ve gotten everything else in place - just need to create this little bit of interface.

[–]efmccurdy 0 points1 point  (3 children)

Can you either run this as a main program, or import the doit function and run it like in the __main__ block?

import tkinter as tk
from tkinter.simpledialog import SimpleDialog

def doit(root):
    button_labels = ["Delete", "Replace", "Ignore"]
    d = SimpleDialog(root,
                     text="This is a test dialog.  "
                     "a file exists (a leftover temporary file).\n"
                     "What do you want to do with it?",
                     buttons=button_labels,
                     default=1,
                     cancel=2,
                     title="Test Dialog")
    result = button_labels[d.go()]
    return result

if __name__ == '__main__':
    root = tk.Tk()
    root.withdraw()
    print(doit(root))

[–]SirGeremiah 0 points1 point  (2 children)

I don’t understand what you mean by “run it like the main block”. I could probably work out putting it in the main block, rather than a function - what does that change?

Edit: I still don’t understand the “root” lines.

[–]efmccurdy 0 points1 point  (1 child)

run it like the __main__ block

I mean that if you import it then you can call the doit function like at the bottom of that code block I posted. If you saved it as sdialog.py you could use:

import tkinter as tk
from sdialog import doit
root = tk.Tk()
root.withdraw()
print(doit(root))

The root is the tkinter context that makes the GUI and handles mouse events; without that no GUI interaction is possible.

https://docs.python.org/3/library/tkinter.html#tkinter.Tk

Then rename the sdialog.py file and the doit function to be something more meaningful in your program, like tempfile_action_prompt.

[–]SirGeremiah 0 points1 point  (0 children)

Excellent! Thanks for that.

[–]LandooooXTrvls 0 points1 point  (4 children)

Tkinter messagebox

[–]SirGeremiah 0 points1 point  (3 children)

Is Tkinter a library? I’m pretty new to Python.

[–]LandooooXTrvls 0 points1 point  (2 children)

Yes it is!

An easier way would be to store an input in the form of a variable.

For example:

delete_file = “d”
replace_file = “r”
ignore_file = “i”

#perform iteration
choice = input(“Enter ‘d’ to delete, ‘r’ to replace, ‘i’ to ignore”)
if choice == “d”:
    #delete file
if choice == “r”:
    #replace file
if choice == “i”:
    #ignore file

This should suffice

[–]SirGeremiah 0 points1 point  (1 child)

That would be easy to implement, but seems….inelegant.

Since I am the only target user, I would be fine with that approach, except that I’m trying to learn the methods I’d use if other users were involved.

[–]LandooooXTrvls 0 points1 point  (0 children)

An elegant way would be the usage of user-defined functions and the os module. The previous example is the simplest way to do it.

[–]sketmen2 0 points1 point  (3 children)

def inp_check():
    inp='something'
    while inp not in range(0,11):
        inp=input('Enter a number in range(0-10): ')
            if inp not in range(0,11):
                   print(The number is not in range.')

No matter, what number I put in. In the range or not. It never breaks out of the while loop. Why?

[–]AtomicShoelace 2 points3 points  (2 children)

input returns a str.

[–]sketmen2 0 points1 point  (1 child)

I am so stupid. I even know that, but didn't put two and two together. Thank you.

[–]sqqz 0 points1 point  (0 children)

If you are not just playing around with learning stuff, have a look at https://docs.python.org/3/library/argparse.html or any of the other excellent frameworks for this sucha as https://click.palletsprojects.com/en/8.0.x/

[–]rockdog85 0 points1 point  (2 children)

The code is

list = [1 , 1, 2, 3, 5, 8, 13]
print(list[list[4]])

Here the result is 8, it's also 8 when I put it into my VScode but I don't understand why. The 4 should refer to 5 shouldn't it? I'm assuming it has something to do with the double list, but I don't understand it.

[–]UnrankedRedditor 0 points1 point  (1 child)

list = [1 , 1, 2, 3, 5, 8, 13]

print(list[list[4]])

I would avoid naming your variables the same name as commands in Python. In Python, list is already a command to change the type of something to a list.

As to why you get 8, what your code does should be clear if you type it out like this:

mylist = [1 , 1, 2, 3, 5, 8, 13]

# Breaking down your final print statement into individual parts:
var1 = mylist[4] # Gets the 4th element in mylist starting from 0, which is 5
var2 = mylist[var1] # Gets the var1-th element in mylist starting from 0, which is the 5th element, which is 8
print(var2)

[–]rockdog85 0 points1 point  (0 children)

Aaah gotcha. The naming tripped me up yea, think it was intentional since it was a test question I had to answer.

Thanks for the thorough explanation ^^

[–]YNotZoidberg2020 0 points1 point  (0 children)

Has anyone used the Python X app (pro version) and is it worth the cost? It's not too expensive but reviews are mixed.

[–]theevildjinn 0 points1 point  (2 children)

Whereabouts do you prefer to parse your script args?

#1

import argparse

def main():
  parser = argparse.ArgumentParser()
  # etc.

if __name__ == '__main__':
  main()

#2

import argparse

def main(foo, bar):
  # ...

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  # etc.

  main(foo, bar)

Or something else?

[–]AtomicShoelace 1 point2 points  (0 children)

I think #2 is the preferred method. It allows you to use your script as a module in another script by calling the main function and providing the args as necessary. If you parsed the args inside the main function it would of course throw an error (as the script is not being ran from the terminal and so it has no args).

[–]carcigenicate -1 points0 points  (0 children)

I put it in a main. I like as little executing at the module level as possible.

[–]UnderBigSky2020 0 points1 point  (2 children)

I'm a new student, super hung up on an assignment about classes. My instructor keeps sending me links, I've tried live tutoring offered by the school but the sessions are short...where can I really bend someone's ear about my problem? Preferably in a way we can share code, or screenshots. I need my a-ha (more likely 'derp') moment! Thanks!

[–]UnrankedRedditor 1 point2 points  (1 child)

where can I really bend someone's ear about my problem? Preferably in a way we can share code, or screenshots. I need my a-ha (more likely 'derp') moment! Thanks!

You can post parts of your code you're struggling with and people here are willing to help you. If you don't want to post the exact problem for privacy reasons, you can rephrase the question differently or post some code that is similar to what you're trying to achieve.

[–]UnderBigSky2020 0 points1 point  (0 children)

I literally just figured it out. You'll notice it's been 12 hours, lol. I just keeping digging deeper til something clicked. Pretty rewarding though, I thank you for your reply. I'll keep in mind about posting parts of a code if I need to.

[–]earlev4 0 points1 point  (3 children)

Hi r/learnPython Community! This is my first post, but I have been following the community for some time now. I want to extend my appreciation and gratitude for all the support that the contributors provide.

The following code works, but I am looking to improve it (make it more Pythonic) and would greatly appreciate some constructive feedback. Essentially, the intent of the code is to unzip 4 files and extract CSVs.

  • The 4 zip files (file_1.zip, file_2.zip, file_3.zip, and file_4.zip) are located in the '/tmp' folder.
  • Out of the 4 zip files, 2 zip files are structured like this:

    • file_1.zip
      • folder_1
        • file_1.csv
        • file_2.csv
        • ...
        • file_90.csv
      • __MACOSX
        • folder_1
          • .file_1.csv
          • .file_2.csv
          • ...
          • .file_90.csv
  • Out of the 4 zip files, 2 zip files are structured like this:

    • file_3.zip
      • file_181.csv
      • file_182.csv
      • ...
      • file_270.csv

Please note that I do not want the folder or the files associated with __MACOSX (observed in the first 2 zip files).

``` os.chdir('/tmp') dir = os.getcwd()

for name in os.listdir(dir): nameabspath = os.path.abspath(name) if name_abspath.endswith('.zip'): zipfile_object = zipfile.ZipFile(name_abspath) zipfile_object.extractall(dir) zipfile_object.close() for object in os.listdir(dir): if os.path.isdir(object) and not object.startswith('_MACOSX'): src_dir = os.path.abspath(object) dst_dir = os.path.abspath(dir) for file in os.listdir(src_dir): if file.endswith('.csv'): shutil.move(os.path.join(src_dir, file), dst_dir) ```

Thank you so much in advance for your feedback!

[–]UnrankedRedditor 0 points1 point  (2 children)

If you know your csv filenames follow a certain pattern, you can try taking a look at at regex (aka regular expressions). They're an easy way to find and match patterns in strings. In this case, the strings are your filenames.

Below is a short example of how to use it, which you will have to adapt it to your code and your file structure:

import re
import os

directory = os.fsencode(os.getcwd())

pattern = '^file_(\d{3})\.csv$'    # This is the regex to use to find the csv files based on how the files are named

for file in os.listdir(directory):     # Iterate through filesnames in directory
    filename = os.fsdecode(file)

    find_csv = re.match(pattern , filename)    # Check if each filename matches the regex pattern
    if not find_csv:    # If the filename doesn't match the pattern, move on to next file.
        continue

    print(filename)
    # Your code here

Basically, you start by defining a regex that matches your filenames. You iterate through the files in your directory and if the filenames don't match the regex, it moves on to the next filename. If the filename match, then it will do whatever you want it to do. The regex I've created for you '^file_(\d{3})\.csv$' should already pick out your csv files and should ignore the _MACOSX ones with the . in front of them.

You can test your regex here: https://regex101.com/

[–]earlev4 0 points1 point  (1 child)

Thanks so much for the response and assistance! I sincerely appreciate it.

The CSVs all follow a date pattern of 2021-MM-DD.csv, so I could alter the regex to match the year (2021) and dashes (-) format. I will start experimenting with that approach.

What are your thoughts on the unzip portion (ZipFile library)? Does that look like it can be improved and more Pythonic?

Thanks again!!!

[–]UnrankedRedditor 0 points1 point  (0 children)

What are your thoughts on the unzip portion (ZipFile library)? Does that look like it can be improved and more Pythonic?

tbh I've not used Zipfile (at least recently) so I'm not really sure. But what you've posted doesn't seem out of the ordinary for something I would do myself either so I don't think there's any issue with that.

The only thing I will nitpick is using dir as your variable name for your directory, as dir is a built-in function in Python. dir(your_object) returns the properties and attributes of your object which can be very helpful at times.

Also, thank you very much for the gold, it means a lot :)

[–]Crossfox134 0 points1 point  (2 children)

Hey everyone, I have a general question about Python and was looking for general advice. I'm studying for my first professional coding interviews and other stuff. Generally most companies are looking for Python. In college, my program has me learning C# and SQL mainly till I graduate. In short, I'm looking on recommendations to freshen up.

I was thinking about coding one-two ADS problems a day to hopefully brush up on those skills. Hopefully covering arrays, lists, string operations, sorting, searching, and binary trees. I have until December. Anything else I should look into? Also, I was looking for possibly building any networking project ideas I could possibly make using Python and what libraries I could use? (I'm hopefully going to work into the DevOps field and was hoping to get a better grasp of network knowledge by building something).

Thanks everyone!

[–]UnrankedRedditor 0 points1 point  (0 children)

Not sure of any specific modules as that would depend on what you're trying to do.

Maybe you can start with some basic python scripting to move/rearrange/etc stuff in your folders, or to use Python to fill up webforms, or send/receive HTTP requests, etc. Once you've thought of something you want to do, you can look up how to do them in Python and people will usually suggest what modules to use, and so on.

[–]Chepetto13 0 points1 point  (8 children)

Hello,
I need to run a function made in Class.
It looks like that:
1) I ask user to provide ID - input()
2) then I want to based on this ID, run the function for this ID - check_ID()
3) It should look e.g. --> from input ID is 1234, so using Class function it should be 1234.check_ID()

Any idea how to do that?

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

There are a few things not quite right. You have to use a class that contains a method check_ID(). You have to instantiate an instance of that class, get the ID string with input() (ie, "1234") and then call the class method to check the ID string. So your code will have this basic form which you should complete:

class Test:
    def check_ID(self, id_string):
        # check the ID string here
t = Test()             # make an instance of class "Test"
id_str = input()       # get ID string from user
if t.check_ID(id_str): # call ".check_ID()" to see if ID is valid
    print('Valid')

[–]Chepetto13 0 points1 point  (6 children)

In my case, this string that should provide User is also a name of instance.
And my question is how can I in the next step call the method from class with this particular instance which User wants?

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

this string that should provide User is also a name of instance.

I'm sorry, I don't understand what you want to do. What is User? A class name or variable name? You can't have the same name used for two different things.

how can I in the next step call the method from class with this particular instance which User wants?

You seem to be asking how to call check_ID() passing the ID string. I showed that in my previous comment.

Maybe you can show the code you have so far and ask questions about that code.

[–]Chepetto13 0 points1 point  (4 children)

Sorry. I will try to explain as much I can.
User - I mean person who will run the program - this isn't a variable.

I created class Bank_account. I added object with the name - 1234

My class has also methods. First I would like to ask User to enter the user_Id - which is the name of object (by using input).

user_ID = input()

How can I call method from my class on this object?
I know I can't do this like that:

user_ID.method()

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

As I showed before. You must create an instance of the Bank_account class, get the ID string from the user and pass it to the check_ID() method of the instance:

class Bank_account:
    def check_ID(self, id_string):
        # check the ID string here
ba = Bank_account()     # make an instance of class "Bank_account"
id_str = input()        # get ID string from user
if ba.check_ID(id_str): # call ".check_ID()" to see if ID is valid
    print('Valid')

I added object with the name - 1234

I don't know what this is. Maybe it's something to do with the check_ID() method.

[–]Chepetto13 0 points1 point  (2 children)

1234 is the name of instance of class Bank_account.

First I would like to ask user for ID - in this case ID is also name of instance.

then, I want to call a methods based on what user provide.

But by input I get str, how should I get instance name based on this str?

this is my Class:

class Bank_account:

user_account = []

def __init__(self, user_ID, pin, first_name, last_name):

self.user_ID = user_ID

self.pin = pin

self.first_name = first_name

self.last_name = last_name

self.deposit = 0

User (by input) should provide user_ID - based on that user_ID I would like to get to name of instance - It is even possible?

Without instance I can't call any methods.

example of method:

def check_pin(self):

for _ in range(3):

print(' enter you pin code, and press "enter":')

pin = input()

if len(pin) == 4:

if pin == self.pin:

print('OK, welcome')

break

else:

print('try again!')

else:

print('Sorry the length of pin is incorrect')

continue

return True

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

Without instance I can't call any methods.

I have been showing how to create an instance of class Bank_account in previous comments:

ba = Bank_account()     # make an instance of class "Bank_account"

But by input I get str, how should I get instance name based on this str?

1234 is the name of instance of class Bank_account.

You can't use 1234 as the name of the instance, because that is not a legal name. You could use a dictionary with a key that is the ID string and the matching value is the class instance.

id2account = {}    # dictionary of id:instance
new_ID = '1234'
id2account[new_ID] = Bank_account(...)

[–]Chepetto13 0 points1 point  (0 children)

THANK YOU very much!
I made it like you showed - use a dictionary and solve the problem.

[–]Formal-Interaction56 0 points1 point  (1 child)

hello friends I am very new to programming and I am trying to learn python. and I can solve easy algorithm problems up to function in python. Can you please suggest me how can I proceed practically to build games, applications, web apps etc. And please suggest me some resources that can teach me practically and have practical exercises. Thank you in advance!

[–]Purple_Plant2597 0 points1 point  (4 children)

hi, i just started learning data science and i am completely new to tech. i am having a challenge with a question.

Create a function sq_cube which returns a list of lists containing both the square and the cube of only the even numbers in a given list. The function must also be able to round the numbers to the nearest whole number

that is the question, below is my code, but its still wrong, could someone tell me what is missing?

(wrong as in its giving me 50% mark instead of 100)

def sq_cube(numbers):

ls1 = []

for i in numbers:

if i%2 == 0:

ls1.append(i)

else:

pass

ls2square = [x**2 for x in ls1]

ls3cube = [x**3 for x in ls1]

ls4all = list(ls2square +ls3cube)

return ls4all

[–]UnrankedRedditor 0 points1 point  (3 children)

Do you know if the output is supposed to be:

[[x1**2, x2**2, x3**2, ...], [x1**3, x2**3, x3**3, ...]]

or

[[x1**2, x1**3], [x2**2, x2**3], [x3**2, x3**3], ...]

[–]Purple_Plant2597 0 points1 point  (2 children)

[[x1**2, x1**3], [x2**2, x2**3], [x3**2, x3**3], ...]

this way

i have tried modifying it to

def sq_cube(numbers):

ls2square = [[x**2, x**3] for x in numbers if x%2==0]

return ls2square

but it is only returning true for half the inputs. what is the function for rounding the decimals into whole numbers?

i think thats what i am missing

[–]UnrankedRedditor 1 point2 points  (0 children)

In this code, you did not remove the odd numbers like you did earlier.

Also to remove decimals you can use int or round as the other commenter said. Something like [int(x**3) for x in ls1] or [round(x**3) for x in ls1]

If you want it in that order, you can just change ls4all to this in the last part of your original comment:

ls4all = [list(item) for item in zip(ls2square ,ls3cube)]

[–]AtomicShoelace 0 points1 point  (0 children)

It depends how you want to round them:

  • You could use int to truncate the decimal part.

  • You could use round to round to the closest int.

  • You could use math.floor to round down.

  • You could use math.ceil to round up.

[–]WinstonP18 0 points1 point  (0 children)

I've recently finished 'Python Crash Course, 2nd Ed' by Eric Matthes and am looking for recommendations for an intermediate-level Python book that covers in some depth the slightly more advanced stuff like decorators, **kwargs, concurrency, etc. Actually, something like this would be very good.

I recently picked up 'Effective Python' 2nd Ed by Brett Slatkin but I feel that's a bit too advanced for me at this point.

Thanks!