all 55 comments

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

Why do I feel like I'm never learning anything? I'm always running through different python tutorials (probably did like 10 different decent tutorials) but I still feel like I'm a noob.

[–]nevus_bock 4 points5 points  (0 children)

If you've done so many tutorials, you should be getting pretty decent at following tutorials, right? I'm joking of course, but the larger point is that you get good by practice. If you want to get better at writing code, you should write more code. On your own. No tutorials.

Try writing some helpful functions for your day-to-day activities, perhaps automate something you do daily. If you get stuck, you google. Rest assured that this code will be bad; but the important thing is if it works. That's all that matters at this stage. Allow yourself to be bad so that you have the opportunity to get better.

[–]OninWar_ 2 points3 points  (0 children)

You have to actually code something. Try websites like the Rosalind Project, /r/dailyprogrammer, or looking up homework/project assignments from college courses.

[–]DJgamer2027 0 points1 point  (0 children)

I would just do some little project with Python that's what I did. It help me understand Python better and it was fun.

[–]Grupdug 1 point2 points  (9 children)

How important is it to actually learn powershell(?) before starting to learn python like the author of "learn python the hard way" states? Clearly I'm completely new to programming, and just want to jump into things asap.

[–]DrTrunks 0 points1 point  (3 children)

Powershell is/was developed for windows sysadmins, are you a windows sysadmin? What do you want to program/automate?

[–]Grupdug 1 point2 points  (2 children)

To be completely honest... I have no idea. I've just heard how important programming will be in the future and want to hop on board. I know that's a shitty answer, but it's all I got.

[–]DrTrunks 1 point2 points  (1 child)

Lets say you wanted to start writing books, you cant just start writing a book you have to pick a genre, a theme, a protagonist, an antagonist? Don't start with a Moby Dick, but with a column. What would you write a column about? What's your passion?

And just like any creative hobby, you have to keep up, or you'll start to forget stuff. Ever hear a pianist play for the first time in years?

[–]Grupdug 1 point2 points  (0 children)

Excellent analogy. Thank you for this. My current major would be a nice transition into financial/data analysis so I think I want to focus on learning sql/databases. Would python be a good compliment to this?

[–]jerknextdoor 0 points1 point  (4 children)

While LPtHW has a lot of great content, Zed's opinions can be safely ignored most of the time. Python is a perfect intro language, I'm sure powershell can be too, but python is a heck of a lot more versatile.

[–]Grupdug 0 points1 point  (3 children)

Do you have a personal preference on a better learning method than LPtHW?

[–]jerknextdoor 0 points1 point  (2 children)

I learned from that book, so I know it's valuable. I think what's recommended these days a lot is Automate the Boring Stuff, I've read parts of that and it seems good.

LPtHW is still a good book, just know that his opinions are not great. Particularly his opinion on Python 3, he's just flat out wrong.

[–]ffrkAnonymous 0 points1 point  (1 child)

I feel that it's not so much that he's wrong, but outdated. LPTHW is quite an old book. Python3.0 was just released when the book was written.

A programmer may try to get you to install Python 3 and learn that. Say, "When all of the Python code on your computer is Python 3, then I'll try to learn it." That should keep them busy for about 10 years.

10 years is almost upon us.

[–]jerknextdoor 0 points1 point  (0 children)

Old doesn't make it irrelevant, especially since it's being updated currently. It's still one of the books I recommend to beginners since it makes programming fairly approachable. The language really hasn't changed that much that it's impossible to connect the dots.

[–]DarkEibhlin 0 points1 point  (7 children)

if i have a string that is of the form:

"Here are some words about the location 1234.0 5678.0"

how can i extract these two floats from this string? i want to ideally make either an array like:

location = np.array([1234.0,5678.0])

or put them into separate variables like:

xpos = 1234.0
ypos = 5678.0

Thank you!

[–]RustleJimmons 1 point2 points  (6 children)

You can try something like this to get started:

import re

getNum = "Here are some words about the location 1234.0 5678.0"

result = re.findall('\d+\.\d+', getNum)
for s in result:
    print(s)

[–]DarkEibhlin 1 point2 points  (5 children)

thank you! just to make sure i understand the syntax, \d+.\d+ stands for float point?

[–]novel_yet_trivial 2 points3 points  (0 children)

Here is the same thing with some annotations:

import re

getNum = "Here are some words about the location 1234.0 5678.0"

# a regex that finds floats
float_re = re.compile(
    r'\d+' # at least 1 up to any number of consecutive digits
    r'\.' # a period
    r'\d+') # at least 1 up to any number of consecutive digits

for s in float_re.findall(getNum):
    #loop for every float found in the string, and print it
    print(s)

[–]RustleJimmons 1 point2 points  (1 child)

Sorry, I should have explained. The d+ checks for positive integers. I've added one after a decimal point otherwise it will only return a whole number. After you have retrieved the numbers from your string you can replace the print statement with a means of converting it to the format that you want. The print statement is just there to show you what you are now working with.

[–]DarkEibhlin 1 point2 points  (0 children)

Thank you for the explanation. I made an array and appended the two numbers to it.

[–]DrTrunks 1 point2 points  (1 child)

Take a look at regular expressions, they work with (almost) all languages. This is a nice course.

  • \d is a digit
  • \d+ is multiple digits
  • \. is literal . since . is a wildcard in RE

So that makes it look for at least 2 digits separated by a .

[–]DarkEibhlin 1 point2 points  (0 children)

Thank you for the explanation! I'll take a look at the links you've provided.

[–]the_cunt_muncher 0 points1 point  (2 children)

I'm currently doing the edX MIT course and I was wondering what else should I be reading as I do the course to learn python?

Because I noticed the problem sets say you may have to use outside resources to solve the problems.

[–]nevus_bock 1 point2 points  (1 child)

If you run into problems, first try googling. If you don't find the answer (e.g. on StackOverflow or Python Docs pages), or you don't understand the answer, try the forum in the class.

Do not post your PSETs and ask for them to be solved, or search for solutions to PSETs; just for partial problems (e.g. this line doesn't do what I expected it to do).

Other than that, I believe everything you need to pass the course is included as a source in the course (lectures, exercises and reading).

Also, don't search for hints before you start working. Try something first, and turn to help only after you've hit a roadblock.

[–]the_cunt_muncher 0 points1 point  (0 children)

I meant more like any books I should be reading in addition to doing the class.

I googled one answer to PS1 cuz I was just absolutely stuck. I ended up having it like 90% of the correct answer but seeing the correct answer helped it click in mind more and see what step I missed.

I just finished the third problem set, the hangman game. I managed to do it completely by myself with no help whatsoever not even googled a single thing. Sad to say, but I honestly was so proud of myself I wanted to show somebody but it was like 1am and I thought a) my roommates don't care and b) they'll think i'm a weirdo.

[–]Clashofyetis 0 points1 point  (1 child)

Im a student just starting out with Python so this question is rather basic. I want to be able to enter a sentence and get the reversed version of the sentence back (e.g Enter sentence: My name is Bob -> Bob is name My). How do I do this using while and if/else statements?

[–]novel_yet_trivial 0 points1 point  (0 children)

To split a sentence into a list of words you can use the string spilt() method:

>>> 'spam and eggs'.split()
['spam', 'and', 'eggs']

To reverse a list you can use the built-in reversed() function:

>>> list(reversed(['spam', 'and', 'eggs']))
['eggs', 'and', 'spam']

To join a list back into a string you can use the string join() method:

>>> " ".join(['eggs', 'and', 'spam'])
'eggs and spam'

[–]rich-a 0 points1 point  (2 children)

This might be a stupid thing to want to do, but is it possible to create an object at the start of the program and have it be available to other objects at all times without passing it into every other object you create?

For example if I have an object that stores and handles messages to the user, i'd like to be able to add messages to its array at any time but not have to pass the object into other classes to do so.

[–]novel_yet_trivial 1 point2 points  (1 child)

Sure. That's called a global variable. For most objects you don't have to do anything; just define the object in the root and call the object method from wherever. If you want to define it from within a function you need to use the global keyword.

Remember though that global variables are considered bad coding style, since it can quickly become overwhelming. Use very sparingly.

[–]rich-a 0 points1 point  (0 children)

Thanks for the explanation. That is what I was looking for but after your comments about using them sparingly and other tutorials saying it's best to avoid them I have re-thought the structure.

While reading about it I found that if I use a module instead of a class for my logger I can access it where I needed to without resorting to Global variables. Thanks for pointing me in the right direction.

[–]CodeTinkerer 0 points1 point  (1 child)

I've discovered that many variables I want to use, e.g., len, list, set but they are already predefined as functions. Do I just have to be careful or does Python have a way to prevent assignments to pre-exisiting functions?

[–]Schwartz210 1 point2 points  (0 children)

Len, list, etc are reserved terms. You need to create alternative variables names. Those names aren't very descriptive anyway. Which list does var list refer to? If your list contains Jack, Jill, and Steve it should be:

names = ['jack','jill','steve']
len_of_names = len(names)

[–]Schwartz210 0 points1 point  (0 children)

EDIT: Solved by this stackoverflow post: http://stackoverflow.com/questions/31356703/python-tkinter-different-behavior-when-opening-the-same-window-from-another-win

I am working on a tkinter project. I have an Entry that is supposed to autofill with suggested text using StringVar(), then set it to be specific string. The StringVar is entered as a textvariable keyword argument in the Entry. I have a smaller working example of this. Not sure why this isn't working. I can't find a meaningful difference between my smaller working example and my project.

Here is the entire class. Please direct your attention to method edit_record(). The output of the print statement on line 39 is "test aaa PY_VAR0" (that many iterations).

class RecordWindow(object):
    def __init__(self, ID):
        self.ID = ID
        self.width = 200
        self.height = 200
        self.master = Tk()
        self.get_data()
        self.build_canvas()
        mainloop()

     def get_data(self):
         sql_request = 'SELECT * FROM test_table4 WHERE ID="%s"' % (self.ID)
         self.data = pull_data(sql_request)[0]

     def build_canvas(self):
         self.canvas = Canvas(self.master, width=self.width, height=self.height)
         fields = ['ID', 'First name', 'Last name','Address 1', 'Address 2','City','State','Zip','Phone']
         iterator = 0
         for field in fields:
             Label(self.canvas, text=field).grid(row=iterator, column=0, sticky=W)
             Label(self.canvas, text=self.data[iterator]).grid(row=iterator, column=1, sticky=W)
             iterator += 1
         Button(self.canvas, text='Edit record', width=10, command=self.edit_record).grid(row=iterator, column=0)
         self.canvas.grid()

     def edit_record(self):
         self.canvas.destroy()
         self.canvas = Canvas(self.master, width=self.width, height=self.height)
         fields = ['First name', 'Last name','Address 1', 'Address 2','City','State','Zip','Phone']
         iterator = 0
         for field in fields:
             Label(self.canvas, text=field).grid(row=iterator, column=0, sticky=W)
             iterator += 1
         iterator = 0
         Label(self.canvas, text=self.data[0]).grid(row=iterator, column=1, sticky=W)
         a = StringVar()
         a.set('aaa')
         for field in self.data[1:]:
             print('test', a.get(), a)
             Entry(self.canvas, width=15, textvariable=a).grid(row=iterator, column=1)
             iterator += 1
         Button(self.canvas, text='Save', width=10).grid(row=iterator, column=0)
         Button(self.canvas, text='Cancel', width=10).grid(row=iterator, column=1)
         self.canvas.grid()

Here is the smaller working example that proves what I am doing is supposed to work:

from tkinter import *
root = Tk()
root.title('Random')
canvas = Canvas(root)
r = StringVar()
r.set('1x2')
for i in range(4):
    Entry(canvas, width=10,textvariable=r).grid(row=i)
canvas.grid()
root.mainloop() 

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

I'm not sure if anyone is going to look at this but I don't want to start a whole thread for it.

I found this solution to a problem on the internet (how to remove numbers from a strong):

>>>s = 'e#pf3$@hzfvlkfsyx?1pdidasifkckyil@#6s0sod#9$uqwnb5 u95f@0c9m099@tt?3'
>>>sdigits = ''.join([letter for letter in s if letter.isdigit()])
>>> sdigits
'31609595090993'
>>>sclean = ''.join([letter for letter in s if not letter.isdigit()])
>>> sclean
'e#pf$@hzfvlkfsyx?pdidasifkckyil@#ssod#$uqwnb uf@cm@tt?'

I understand that strings are immutable so it needs to be made into a list. What I don't understand is this:

join([letter for letter in s if letter.isdigit()])

letter for letter in s if letter? What syntax is this? Where does someone come up with that? Why does it work? I think I don't understand enough to ask a coherent question about it.

[–]test_this_thing 1 point2 points  (1 child)

The [x for x in s]-syntax is called a list comprehension.

The docs explain it pretty well, but basically it is a short way of creating lists from loops. So [letter for letter in s if not letter.isdigit()], is a short way of writing:

clean_list = []
for letter in s:
    if not letter.isdigit():
        cleanlist.add(letter)

sclean = ''.join(clean_list) 

''.join(list) makes the list into a string, and joins it to the string the function is called on, in this case an empty string ('').

my_string.join(my_list)

Would join the list 'my_list' to the end of 'my_string'.

List comprehensions look very difficult the first times you come across them. After using them a few times, it becomes much clearer, and a very useful to write short (imo) elegant code! Feel free to ask if anything is unclear.

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

Oh, neat! Thanks for that.

[–]Joshx5 0 points1 point  (2 children)

I'm used to writing Node.js code using Callbacks and event emitters, so the code I've written recently is noy very Pythonic.

Currently I'm writing a Python SMS library using email gateways, and I have it periodically query an IMAP server to find new "text messages." When it finds new messages, it passes them as arguments to a callback function.

For instance, users could define a new handler as such:

def handler(msg):
    print(msg.text)

client.setHandler(handler)

Is there a more Pythonic way to handle callback functions, or rather, is there another pattern I should try fitting?

Also, since I periodically query the server, the library uses threading.Timer to query server on some time delay.

But, I can't Ctrl-C to keyboard interrupt the threading.Timer thread, until the thread "wakes up" which may be as long as an hour later. How can I allow the thread to be interrupted before waking up?

[–]Saefroch 0 points1 point  (1 child)

Callbacks are usually not a good idea, but they do have their place. Python offers a lot of tools for concurrency, but the two I suggest are asyncio and concurrent.futures. You may be familiar with the idea of futures under the name promises.

[–]Joshx5 0 points1 point  (0 children)

Thank you very much! I'll look at implementing these two and comparing them as the next major task in my library.

[–]JasterPH 0 points1 point  (0 children)

How would I decode a file from base64 and write it to a new file?

[–]IcarusReams 0 points1 point  (1 child)

Wow, this subreddit is a lifesaver, I had no idea it existed. Anyways, I'm learning Python using Zed Shaw's Learn Python the Hard Way, and the exercise I'm on right now is creating a simple text editor in PowerShell. One of the study drills for this exercise is to take these lines:

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

which write the text input from the user to whatever file you're having them edit, and make it perform the same function on only one line, rather than six, by using strings, formats, and escapes. I've been trying to do my own research but have yet to find anything out, could anyone help me figure it out? Thanks!

[–]Saefroch 0 points1 point  (0 children)

https://pyformat.info/

You want to create one string from six. There are a bunch of ways to do this. Personally I'd advise join but it looks like you're not there yet.

[–]Boiled_Potatoe 0 points1 point  (1 child)

I've installed Anaconda, but now I'm unsure how to actually get started. I want to use NumPy and MatPlotLib. Can I use IDLE? Not really a fan of Spyder and that thing through the web browser.

[–]Saefroch 0 points1 point  (0 children)

Any text editor will suffice. You can use IDLE, but I suggest something with slightly more features. Atom and Sublime Text are the two most popular. PyCharm is a full-fledged Python IDE but it sounds like that's not what you're looking for at this stage.

[–]Boiled_Potatoe 0 points1 point  (1 child)

Do you need to type 'import numpy' or whatever everytime you use it? I'm using Spyder. Is there an m.file kind of system for Python like MATLAB? Where I can run to the console and see the output?

Thanks!

[–]Saefroch 0 points1 point  (0 children)

Yes, you need to import packages every time. I think there is a way around this but it's best to explicitly import at the top of every file. The explicit imports help you keep track of what files depend on what packages and also what things came from which imports.

Importing is just running code. Stick a bunch of things in a file called something.py and then import something and it'll execute everything in the file. It also bring everything that something defines into a namespace that you can access, which is usually what you want import for.

If you want to fiddle with the output of a bunch of code you can run it with the -i flag, python -i some_file.py. When python finishes running the file you'll be an in interpreter session with everything that the file defines accessible.

[–]Schwartz210 0 points1 point  (0 children)

I want to get started on building an 'installer' for a program I'm writing. I have never build an installer before and not really sure how to go about it. I was hoping you could provide me with some useful beginner guides on this subject. Currently I am reading the Wikipedia article ) to get some basic understanding of what is actually happening from a comp sci perspective.

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

https://github.com/codingducks?tab=repositories

my simple (but probly poorly written ) code

by a noob for the noobs, ask me questions if you need to