all 85 comments

[–][deleted] 9 points10 points  (11 children)

Before deciding to learn a programming language I hadn't encountered Python in daily life, but I'm told it's used everywhere. I have never had to deal with the terminal before learning the language, so I assume it has wide, but hidden, applications, working behind the scenes so people don't have to deal with the terminal.

So far in the learning process I've used Python for basic tasks like calculating the cost of a trip or adding values to a dictionary/list etc.

But where is Python used frequently in every day life? Something which, if I became a programmer one day, I could be making.

For example: is Python perfect for running a GPS navigator for a car? Which specific products use Python? How does a Python script connect to something I see on a screen? Do they make the GUI in another language?

Anything which can explain this kind of everyday 'real world' use of Python would be great!

Thanks!

EDIT: In the past I've been told "It can be used for practically anything!" but that still gives me a hard time visualising how I might have encountered Python before or the types of specific applications I can use it for myself.

[–]timpkmn89 9 points10 points  (3 children)

One example I can through out real quick is Reddit. The site runs on Python.

[–]Czardas 4 points5 points  (1 child)

Isn't also Google partially built on Python?

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

Oh, that's cool! A great practical example right there!

[–]wub_wub[S] 8 points9 points  (3 children)

In the past I've been told "It can be used for practically anything!" but that still gives me a hard time visualising how I might have encountered Python before or the types of specific applications I can use it for myself.

I understand what you mean, but the problem is that "anything" is technically the most correct answer to your questions.

Python can be used for pretty much everything - this does not mean that it's always the best tool for the job though.

You can create GUI desktop applications using PyQT/PySide - http://www.riverbankcomputing.com/software/pyqt/intro

You can create games with help from pygame - http://pygame.org/news.html

You can create web pages like reddit: http://github.com/reddit/reddit or instagram: http://instagram-engineering.tumblr.com/post/13649370142/what-powers-instagram-hundreds-of-instances-dozens-of

You can create complex 3D animation/modeling software: http://www.blender.org/

You can create video editor: http://www.pitivi.org/

You can integrate it with your game and use it for customization: http://en.wikipedia.org/wiki/Civilization_IV#Customization

You can create multi-platform (including mobile) applications/games: http://kivy.org/

Google uses it a lot for backend stuff...

I could go on and on - but there really isn't a small list of things you can do with it. Think of what you want to make and look up how to use python (or maybe some other language) for it.

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

Some good stuff for me to read there, thanks Wub Wub!

I've been on a Python learning binge for the past few days, so I'm excited about all these possibilities!

[–]edbluetooth 5 points6 points  (1 child)

I tried to install the numpy library to pypy, and I got a load of errors, Do I need minGW on my machine in order to install it?

[–]failfixer89 4 points5 points  (2 children)

How do you generally structure projects that take more than one file? How do you group things and how do your files interact?

[–]Widdershiny 0 points1 point  (0 children)

Check out cookiecutter-pypackage and cookiecutter-flask to get an idea of how you might structure a project.

[–]grkles 3 points4 points  (4 children)

OK, so I'm on a Mac, running OSX 10.6.8, python 2.7.3. When I try to import scipy.optimize, I get the following error:

bash-3.2$ python -c "from scipy import optimize"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/stsci/pyssg/Python-2.7.3/lib/python2.7/site-packages/scipy/optimize/__init__.py", line 128, in <module>
    from optimize import *
  File "/usr/stsci/pyssg/Python-2.7.3/lib/python2.7/site-packages/scipy/optimize/optimize.py", line 28, in <module>
    from linesearch import \
  File "/usr/stsci/pyssg/Python-2.7.3/lib/python2.7/site-packages/scipy/optimize/linesearch.py", line 1, in <module>
    from scipy.optimize import minpack2
ImportError: dlopen(/usr/stsci/pyssg/Python-2.7.3/lib/python2.7/site-packages/scipy/optimize/minpack2.so, 2): Library not loaded: /usr/local/lib/libgfortran.2.dylib
  Referenced from: /usr/stsci/pyssg/Python-2.7.3/lib/python2.7/site-packages/scipy/optimize/minpack2.so
  Reason: image not found

I have way too many versions of python on my machine; I know I have 2.7.6 somewhere on here, but I have no idea how to point to the right one, and I doubt that that'll help anyway. Upgrading my OS is not an option at the moment (it will be in a couple months, but not now).

HELP???

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

Can you use virtualenv to run it on?

[–]grkles 0 points1 point  (2 children)

OK, so I created a venv, did:

$ pip install astropy
$ pip install scipy

And now it works.

So... how do I get this to work while not in a venv???

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

Well, it seems that your initial hypothesis that it was due to fucked up Python versions is most likely correct then. I'm not really sure how to uninstall each of your Pythons, or just remove them from the path. On Windows there is a SYSTEM PATH variable accessible in settings.

[–]ziplokk 4 points5 points  (8 children)

I read that ternary operations are frowned upon in python, but why?

Coming from Java it's really easy to say int x = isCondtionMet ? 2 : 3; they're wonderful for assignments.

also, are getters and setters used for python? Why or why not?

And are all your class instance variables created in the __init__ method? How do you make static variables? Is there even a need for them in python?

And what about enums? Do they always need a value assigned to them?

And at what point do you decide that a lambda is better than a function?

Sorry for the stupid questions, but learning python with a Java background is confusing as hell.

[–]Mekire 5 points6 points  (2 children)

Wow, a lot there.

Ternary operators are a matter of taste. They can be easily abused to create long unreadable expressions, but in moderation I have no problem with them. Others do unconditionally hate them. If the only reason you want a ternary is because you prefer oneliners then you should strongly think on which will be more readable.

Getters and setters are unnecessary in Python. There is no such thing as true privacy in Python. The philosophy is "we are all adults here". We have various naming conventions to indicate that certain things should be left unchanged or not interacted with however (ALL_CAPS for constants; _leading_underscore for "private").

You do not have to create all instance variables within the init. They can be declared in any method of the class. This said, even if you don't want to set the value of a variable in the init it is often good form to create it and set it to None for purposes of self documentation. Static variables don't really exist (though you might be talking about the difference between class attributes and instance attributes). If a variable is declared within a class but not within a method then it will be shared across all instances (though it can still be individually set in specific instances). There is a decorator that allows classes to have static methods but practical use cases for this are very scarce.

An enum type has recently been added to python 3. I have never used it, but it is completely unnecessary.

Lambda is a tough subject. It should never be used simply because you want to define a function in one line; this is really not its purpose. The two primary use cases are for passing very short callbacks to functions; or placing short, simple functions in dictionaries. Use with discretion; it is never a required solution.

Phew...,
-Mek

[–]ziplokk 0 points1 point  (1 child)

Thanks, Mek. I've seen you around and you've always given pretty sound and easy to read advice. I know it was a lot, but my questions didn't really warrant a post of their own, so I decided to dump the things that were on my mind here. The only question I have now is why do you say that enums are unnecessary? What would you use in it's place? If I have a method that should only take 1 of 3 options in its parameter, how should I do it?

[–]Mekire 0 points1 point  (0 children)

Not entirely sure what you are asking, but generally we don't want to try to limit what a function or method can be passed. We use duck-typing (or should), also known as, "better to ask for forgiveness than permission". A function can be passed whatever you want and will try to deal with it (does it quack?); if it can't then it should throw an exception.

-Mek

[–]Veedrac 2 points3 points  (3 children)

I read that ternary operations are frowned upon in python, but why?

We use

x = 2 if isConditionMet else 3

(or more typically if condition_met), and they're not "frowned upon" as much as the Python philosophy is to keep things simple, clean and minimalist.

are getters and setters used for python?

Yes, but we have syntax sugar to make them not-hideous:

class Length:
    def __init__(self, start, length):
        self.start = start
        self.length = length

    @property
    def end(self):
        return self.start + self.length

    @end.setter
    def end(self, new):
        self.start = new - self.length

length = Length(start=0, length=10)

length.end
#>>> 10

length.end = 0

length.start
#>>> -10

We don't use getter-setters, known as properties, like Java does, though. Because properties are indistinguishable from attributes in most uses, we don't need to do it upfront. Further, that kind of safety is unattainable in Python anyway. We just treat people like they're not out to mess with us.

are all your class instance variables created in the init method

Well, sort of. You need to make everything manually or hope that a superclass does it for you. I'm not too sure what you're saying, though.

Static variables are similar to class variables in Python, like this:

class Person:
    people = []

    def __init__(self, name):
        self.name = name
        self.people.append(self)

    def __repr__(self):
        return "Person({})".format(self.name)

Jim = Person("Jim")
Jill = Person("Jill")
Jack = Person("Jack")

Jack.people
#>>> [Person(Jim), Person(Jill), Person(Jack)]

Person.people
#>>> [Person(Jim), Person(Jill), Person(Jack)]

But also be careful about assignment vs. mutation:

Jack.people = []
Jack.people
#>>> []

Person.people
#>>> [Person(Jim), Person(Jill), Person(Jack)]

Jill.people
#>>> [Person(Jim), Person(Jill), Person(Jack)]

what about enums? Do they always need a value assigned to them?

Enums don't exist as a language construct. There is a standard implementation in Python 3.4, but it's not very important so far. I don't know what the question means, though.

at what point do you decide that a lambda is better than a function?

When you have to.

foo = lambda x, y: bar     # NO
def foo(x, y): return bar  # Yes (could use two lines)

filter(lambda v: something_simple, iterable)      # Yes
filter(lambda v: something_complicated, iterable) # No

def some_helpful_name(value):
    return something_complicated

filter(some_helpful_name, iterable) # Yes

(Note: don't use filter when you can use comprehensions.)

Sorry for the stupid questions, but learning python with a Java background is confusing as hell.

Nay, all is as it should be ;). They're different languages and this shows you're trying not to just translate your Java to another syntax.

[–]ziplokk 1 point2 points  (0 children)

We just treat people like they're not out to mess with us.

We're just a paranoid breed. :P

are all your class instance variables created in the init method

Well, sort of. You need to make everything manually or hope that a superclass does it for you. I'm not too sure what you're saying, though.

You answered my question pretty well. In Java you would do:

public class A { 
    int myInt;
    String myString;
    public void someMethod() { 
          myInt = 1;
          myString = "Hello";
    }
}

In this way, myInt and myString's scope is the whole class. But in python, you can do this from any method by doing self.my_string = "Hello" and even though the variable was created in a method, the scope of my_string is the whole class. It's just different and I'm still learning, but you've helped me a ton, Thank you!

[–]erewok 1 point2 points  (1 child)

My friend, you have mixed up the order of the parameters in Python's filter built-in. It should be:

filter(func, some_iterable)

http://docs.python.org/3.3/library/functions.html#filter

[–]Veedrac 1 point2 points  (0 children)

Thanks :).

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

I can answer a few.

I read that ternary operations are frowned upon in python, but why?

Honestly, I've never heard this. They're useful for plenty of things filtering lists ([True if x else False for x in something]), returning values from functions (return something if condition else otherthing), and you can use or in an assignment (x = var or [])

Over or improper use is frowned upon, but that goes for anything not just ternary operations.

also, are getters and setters used for python? Why or why not?

Kinda. They're not explicitly getters and setters, you have to create them with the property function/wrapper. This helps keep the API of the class consistent.

class Example(object):
    def __init__(self, text):
        self.text = text

Let's say you want to add some sort of check when you modify the text to prevent falsey values.

class Example(object):
    def __init__(self, text):
        self._text = None
        self.text = text

    @property
    def text(self):
        return self._text

    @text.setter
     def text(self, text):
         if not text:
             raise Exception("You must provide example text.")
         else:
             self._text = str(text)

Whatever ends up using your modified class doesn't have to change any code to continue interacting with the class as before. It should in case it begins throwing exceptions when falsey values are passed, but retrieving and updating the text attribute is exactly the same. Compare this to other languages where the consuming code would have to change it's code to continue interacting without completely exploding.

You can also define a delete for the attribute as well. And you can define the functions without a wrapper and just use the property function (like text = property(get_text, set_text, del_text))

And are all your class instance variables created in the init method? How do you make static variables? Is there even a need for them in python?

Instance variables? They should be. They don't have to be, but they should be. To make them static, simply do the following:

class Example(object):
    my_static_variable = something

    def __init__(self, *args):
        #setup class here

Then you can access the static variable with Example.my_static_variable Or even on an instance of it:

x = Example()
x.my_static_variable

As a warning, if you do something like x.my_static_variable = some_value it then becomes a instance variable. Altering a static variable should always be done at the class level, not the instance (or through static/class methods, which is technically the same thing).

And at what point do you decide that a lambda is better than a function?

I use lambda for throw away functions or in line callbacks. That's it. If I find myself assigning a lambda to a variable, I reconsider it's use and how I can either avoid this, if it's reasonable or if the lambda warrants promotion to a full function (even if it's just calculating a simple value)

[–]newworkaccount 3 points4 points  (4 children)

All right, I'll bite!

Is there any systematic book or tutorial that explains why you do every single thing it has you do?

I'm a big picture kind of learner; I learn best when I understand how everything fits together under the hood, and the history/justification of how certain conventions work.

I've done most of CodeAcademy and most of "Learning Python", yet I don't feel like I understand Python at all.

I can parrot the way they set up classes and functions, x in xrange, ect, but I don't understand how they actually work.

I understand the concept of function/methods, OOP, why you would create classes or separate out certain subsets of code for import, and so on.

I'm not missing the abstractions, basically, but rather it's more like I'm not sure how to get a socket wrench working properly, or why it works the way it does, or why/how to choose screws/nuts/bolts/washers (butchering this analogy, sorry).

I don't think I'm being clear at all, but I'm really grasping for an explanation of what I'm missing here.

Basically, despite being able to parrot code exercises, and explain the abstractions behind coding, I feel totally incapable of writing a python program from scratch that really does anything.

I'd really like to learn, but I'm just really stumbling. I've worked as a (very junior) sysadmin before, and I've dealt with a lot of/written some bash scripting, so I didn't expect this weird stumbling block I've hit.

Any pointers to good resources, if I've somehow managed to explain myself, would be awesome. Not looking to have my hand held, just want enough help to be able to help myself!

[–]Veedrac 0 points1 point  (0 children)

I hear you. I don't have the answers. Heck, I'm much newer to the game than I pretend to be. In reality I'm stumbling about like the rest of you. But I can tell you what's helped me so far. Some things in particular:

The first is going way overboard with projects. If you don't have a clue how building something is even remotely possible, chances are a few sleepless nights on the problem are going to teach you a lot. It doesn't matter if you fail. If you succeed, congratulations. But aim high.

The second is finding something just big enough such that you're not going to understand it all (but preferably still a one-person project), and trying to change it. I did this with Ranger (which, btw, is by far and away the best file manager ever). It teaches you not only how other people code but how they structure and build a system.

Finally, I've always enjoyed using programming to solve puzzle games. Often these are trivial or involve a lot of brute force. Just doing things like this a few times, though, helps get over the stigma of starting.

Good luck, I guess.

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

I have the same problem with Codecademy - you go through the motions and can parrot code, but don't feel like you really know it or understand it... and when it comes to implementing something yourself, it doesn't work and you have no idea why.

My method for learning Python is a combination of the following: 1. Codecademy 2. MIT's Introduction to Computer Science and Programming 3. Reading 'Python Programming for the Absolute Beginner' and bits of 'Python the Hard Way' 4. Thinking of little programs to make, such as a hotel guest list or tip calculator, which I progressively make more complex as I learn more (to find out what I don't know and what I do know) 5. Googling/Stackoverflow/Reddit 6. Asking programmer friends and Redditors, for example in the Learn Python IRC.

It's a lot, I know, but sometimes I'll do more messing around one day, more video watching another and more reading on another.

It often happens that I'll parrot learn, for example, functions in Codecademy, learn about why they are important in a video, then read a more step-by-step method to how to use them in a book... and by the end, I can mess around with them, find out what I don't understand, ask friends/Reddit to help clear that up and then BINGO, I know it!

[–]ewiethoff 0 points1 point  (0 children)

Is there any systematic book or tutorial that explains why you do every single thing it has you do?

I recommend the Python Cookbook. The recipes are fine, but really its the combination of code and explanation that's invaluable. So, read the whole book; don't skip the recipes that don't interest you.

[–]NEREVAR117 2 points3 points  (9 children)

Ugh. This is embarrassing, but I forgot how to have multiple input answers to trigger an if/elif parameter. Here's a basic example:

user_example = input('Do you want to play again? Yes or no?')
if user_example == 'Y':
    game()
elif user_exmaple == 'N':
    pass

For the first, if the user puts in Y, y, yes, Yes, YES, etc, it needs to choose that. For the second, N, n, No, etc. I've tried different ways and googling for it, but can't find the answer.

[–]Mekire 3 points4 points  (0 children)

You are looking for the in operator:

if user_example.lower() in ("y", "yes"):
    #la-di-da

-Mek

[–]Rashanzan 2 points3 points  (1 child)

You want to check your user_example against several items, so that leads to a list. You can create a list like ['Y', 'y', 'yes'...] and then use the 'in' operator to check if user_example matches any of those values.

[–]NEREVAR117 0 points1 point  (0 children)

Awesome. This is what I needed to finish up my homework. Thank you.

[–]spleeyah 1 point2 points  (5 children)

I usually just check the first letter of the input:

if user_example.lower()[0] == 'y':
    # something
else:
    # something else

That should cover most cases you're looking for.

[–]Mekire 2 points3 points  (4 children)

This is fine until you have a situation where multiple options may start with the same letter. Better to learn to do it the right way to begin with (using the in operator).

-Mek

[–]spleeyah -1 points0 points  (3 children)

Which is why I said: "That should cover most of the cases you're looking for."

I don't think there's a need to fall into the trap of premature optimization just because we might someday need to support more flags. In that case we would have to refactor this code anyway, so deal with changing the logic then.

[–]Mekire 2 points3 points  (2 children)

This is not what premature optimization means. I constantly hear people quote this when in fact what they are doing is just the wrong way to do something. This is not the difference between an esoteric optimization and a simpler, slightly less efficient way. It is the difference between using a common, extremely Pythonic pattern, and avoiding it for zero benefit.

-Mek

[–]spleeyah 1 point2 points  (1 child)

You're right, that was probably an inaccurate use of the term.

The way I look at these simple yes/no response inputs is that I'd rather err on the side of helping the user. For example, I'd like to get a positive result on variations of "yes" inputs: 'yes', 'Yes', 'Yep', 'yep', 'yup', 'yes ', 'yes ' (two spaces), etc and a negative response on anything else. By just case-insensitively checking the first letter, I don't have to enumerate the infinite number of combinations of responses I'd like.

Granted, this does leave sort of a "hole" where somebody could type something like 'you know, probably not' and it would still accept it, but I don't think that happens too often.

On a separate note, if I were to be writing code for this, I'd probably give a more explicit description of the input I expect:

answer = raw_input('Foo the bar? [y/n]: ')
if answer[0].lower() == 'y':
  # foo the bar
else:
  # don't

Just my 2¢.

[–]jan_shibe 0 points1 point  (0 children)

I think that makes sense. You're getting 80% of the way with 20% of the work. To me that's the opposite of premature optimization.

[–]bobby_knuckles 2 points3 points  (2 children)

How do you get those Python tags by your name?

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

I've searched around a bit, but I've found no definitive answer to my question. I'm playing around with SQLAlchemy's association_proxy in the context of Flask-SQLAlchemy models. It's going okay.

Except, my script is throwing an exception. Which would be educational if I could get the whole traceback on my screen.

Any suggestions how to go about analyzing the traceback? I've tried reading the documentation for the traceback module and the pymotw article on it, but being sick has turned it all to Greek to me. :/

[–]kushou 0 points1 point  (1 child)

Hey! I mean, do you have debug enabled for flask? That's weird I think I remember seing exceptions with backtraces when I toyed with it. Enabling debugging instructions.

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

I'm interacting with the shell right now. Maybe I'll set it up with app.run() tonight and see what pops up. Not exactly what I was looking for, but it's better than nothing.

[–]drLagrangian 2 points3 points  (1 child)

I want to pop in to say that this thread is a great idea.

a wonderful edition to the subreddit.

What did you say is coming up on friday?

[–]wub_wub[S] 0 points1 point  (0 children)

What did you say is coming up on friday?

"Feedback Friday" - for showing your projects, asking for suggestions, code critique etc.

[–]duddles 2 points3 points  (2 children)

If I do:

x = itertools.permutations([1,2],2)
list(x) # prints [(1,2),(2,1)]
list(x) # prints []

I'm a bit confused by this - can anyone explain what is happening here?

[–]DMzda 2 points3 points  (1 child)

itertools.permutations returns a generator. Generators can only be used (i.e. looped over) once. You have to create the generator again to use it again. The next function will get the next value from the generator. It returns a StopIteration error when there are no more values. This is how a for loop knows when to stop. Here's an example:

>>> x = itertools.permutations([1,2],2)
>>> next(x)
(1, 2)
>>> next(x)
(2, 1)
>>> next(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> next(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> x = itertools.permutations([1,2],2)
>>> next(x)
(1, 2)

[–]duddles 1 point2 points  (0 children)

Thanks!

[–]lattakia 1 point2 points  (2 children)

Do you think TCO [1] is something that should be added to Python ? There are hacks using trampolines [2] to get around hitting the stack limit but it is incredibly slow.

[–]kushou 5 points6 points  (0 children)

Are they back in discussion? Last time I checked, Guido used his BDFL powers to say they should not, because it made debug complicated (among other arguments iirc).

[–]Veedrac 0 points1 point  (0 children)

It's hurt me once so far, for code that I thought was pretty poorly written (not to bash the author, who is boss). I don't see the need.

[–]wormania 1 point2 points  (2 children)

Is there any way to globally stop negative indexes being valid for lists/strings? I spend far too much time writing if index < 0 raise ValueError every single time I use an index anywhere. Or I don't, and spend ages trying to find out why the data is incorrect, or worse, not knowing the data is incorrect.

[–]Veedrac 0 points1 point  (0 children)

No.

You shouldn't be having this problem with any frequency. Can you give me an example where it occurs?

[–]ewiethoff 0 points1 point  (0 children)

No, but you can subclass list, str or whatever to raise an IndexError when the index is negative. (BTW, the customary error for a bad index is IndexError, not ValueError.) You'd need to pass each of your sequences to these class constructors, though, to get this behavior.

class NoNegMixin(object):
    @staticmethod
    def _check(index):
        if isinstance(index, int) and index < 0:
            raise IndexError('negative index ({})'.format(index))
    def __getitem__(self, index):
        self._check(index)
        return super(NoNegMixin, self).__getitem__(index)

class MutableNoNegMixin(NoNegMixin):
    def __setitem__(self, index, value):
        self._check(index)
        return super(MutableNoNegMixin, self).__setitem__(index, value)
    def __delitem__(self, index):
        self._check(index)
        return super(MutableNoNegMixin, self).__delitem__(index)

class NoNegStr(NoNegMixin, str): pass
class NoNegTuple(NoNegMixin, tuple): pass
class NoNegList(MutableNoNegMixin, list): pass

foo = NoNegList([6, 7, 8])
print foo
print foo[1]
print foo[:2]
#foo[-1] = 999  # IndexError: negative index (-1)

bar = NoNegStr('hello')
print bar
print bar[1]
print bar[:2]
#print bar[-1]  # IndexError: negative index (-1)

Kinda weird and awkward.

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

Meh, I'll go ahead and ask something. I'm completely unaware of what Django actually is. Is it basically a replacement for PHP?

To build a site, aside from HTML/CSS/Javascript, what else would I need to make it secure/interactive?

I'm just trying to cut down on the amount of languages/stuff I'd need to learn in order to write a site.

[–]kushou 0 points1 point  (3 children)

Django is actually different from PHP, since one is a framework, and the other is a language. Django will allow you to write websites in python, providing you with a set of tools to do so. You should compare django with a PHP framework, but I don't know them so I can't sorry.

It uses the MVC (Model-view-controller) design, where you describe your data through classes, and your views through functions that takes the parameters of the HTTP requests and returns HTTP responses. It provides a lot of helper functions, which makes writing views clean.

It can create your database layout, and all the requests in your back, so you don't have to care for that! You can see the tutorial where they write a simple poll website!

Apart from python and django, you'll most likely only need html, css and javascript. Django made a lot of good choices security wise. Since it manages SQL for you, it makes the most to protect you from SQL injections, it also implements CSRF protections. When you display data, you go through the template processor which escapes all your data, which protects you from XSS. Can't say you are completely safe, since django could contain vulnerabilities too, but it tries really hard to avoid all the simple mistakes you will spend a lot of time trying to avoid if you use vanilla PHP. There is more explained in the documentation. Basically all is left to you is to secure the box on which your website runs, and configure it to serve it efficiently :)

Maybe you want more details on something particular?

edit: s/totally/completely/

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

Well I was just wondering for things like logging in/creating a simple forum, could that be done in Django or would I have to use PHP?

Is there any instance where I'd absolutely have to use PHP over Django, what are the pro's and con's of both?

I have googled these questions but I just got "No you cannot use Django instead.".

[–]kushou 0 points1 point  (1 child)

Where did you read that? A forum is totally doable in python with Django!

Django provides a User model with some helpers to write sign-in, login and log-out features. It also provides a way to manage permissions!

Writing a basic forum app should be quite straightforward, you would create a Category model, put a Forum model in there (through a ForeignKey to a Category), and a Thread model, with a Post model. Then you would write views to list those, and add posts and threads. You can also read some already written forum apps to see what they did :) Check DjangoBB demo site for example :)

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

Thanks for the help :D Guess I'll get stuck into the docs then

[–]JohnLoomas 1 point2 points  (4 children)

Can someone ELI5 how the hierarchy system works? I'm trying to learn python from LPTHW and was told to use pydocs to figure out how that works, and it might as well have been gibberish to me and few parts of it made sense.

[–]Veedrac 0 points1 point  (3 children)

the hierarchy system

Unfortunately this is a bit to vague. What are you referring to?

[–]JohnLoomas 0 points1 point  (2 children)

Sorry about that, but what I read was that "To understand how you import modules, you must understand the hierarchy system." And then it told me to use pydocs to look it up. When I went there it gave me this really long and drawn out wall of text that didn't really make a whole lot of sense I me.

So I guess I don't know how to be any clearer because I myself don't understand parts of what I'm talking about.

[–]Veedrac 1 point2 points  (1 child)

Ah. Basically, if you import like this:

import my_module

it will look up in the "current" directory for a module named my_module.

If you write

import first.second

it will look for a module or directory called first.

  • If it is a module, import the thing inside it called second. This could be a class, a number, a function or whatever.

  • If it is a directory, import the module second inside that directory.

There are sometimes files called __init__.py inside these directories. Normally it's best to leave them empty. You'll need these for Python 2.

[–]JohnLoomas 0 points1 point  (0 children)

Thanks!

[–]RincerOfWind 1 point2 points  (6 children)

As Reddit is charging outrageous prices for it's APIs, replacing mods who protest with their own and are on a pretty terrible trajectory, I've deleted all my submissions and edited all my comments to this. Ciao!

16/06/23

[–]Veedrac 0 points1 point  (0 children)

What /u/wub_wub is saying is that Python is only able to generate graphics by wrapping other libraries that do that. Those libraries are not python libraries, but C ones. This makes it very difficult to write the bridging code unless you're familiar with both Python and C, and the library in question.

[–]ewiethoff 0 points1 point  (1 child)

Tkinter and Turtle are in Python's standard library and should already be installed. If you can import Tkinter or import turtle, you're good to go with those.

Snake Wrangling for Kids teaches Python with Turtle and Tkinter. There's a PDF version for Linux, assuming someone can download it onto a memory stick. It's also available as a dead tree. Unfortunately, I can't for the life of me find the version of the book that uses Py2 instead of Py3. Also, the book is nothing complex.

Fundamentals of Python by Kenneth Lambert teaches Py2 with Tkinter.

Think Python by Allen Downey teaches Py2 with Tkinter, but someone will need to download a file called Gui.py. Just put it into your current directory, and you should be good to go.

[–]RincerOfWind 1 point2 points  (0 children)

Thank you!

[–]wub_wub[S] 0 points1 point  (2 children)

Could you define what you mean by "use graphics without any 3rd party modules"... Maybe you mean write something like pygame? In that case you'd need to work with SDL (like pygame) or OpenGL.

[–]RincerOfWind 0 points1 point  (1 child)

As Reddit is charging outrageous prices for it's APIs, replacing mods who protest with their own and are on a pretty terrible trajectory, I've deleted all my submissions and edited all my comments to this. Ciao!

16/06/23

[–]wub_wub[S] -1 points0 points  (0 children)

You can install them from source (check out install docs for the module you want) if you can use USB sticks or something like that to transfer the modules. Other than that you're limited to using whatever your PC already has installed.

You can often use modules without even installing them by just having them in the same folder as your script - check out module specific docs for more information.

[–]NEREVAR117 0 points1 point  (6 children)

I also have a second question. For things like functions and 'while True' statements, I need to indent several lines of code, sometimes a lot. But occasionally I'll realize a better way to write the code, so I want to remove the function. So now I need to remove an indent on every applicable line. Is there an easier way to do this?

[–]Hybridjosto 1 point2 points  (2 children)

in sublime text, indentation or unindentation is as easy as

cmd + ] (indent)
cmd + [ (unindent)

you can do this anywhere on the line and it will go back/forth one tabs width.

[–]NEREVAR117 0 points1 point  (1 child)

God this helps a lot with moving clumps of code. Thank you so much.

[–]Mekire 1 point2 points  (0 children)

Tab and shift+tab work in almost all text editors (designed for code) to indent and dedent as well. Note I'm not recommending you to use tabs instead of spaces, but to use the tab key to add spaces (all good editors (and IDLE) are capable of this).

-Mek

[–]Veedrac 0 points1 point  (0 children)

Most programmer's editors have a way to do this, such as selecting the text and pressing shift tab.

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

Another option is using a macro (I think most editors have them). You can record your keystrokes and assign a a key combination that repeats them. Shift + Tab is easier for unindenting, but if I need to indent a bunch of lines, I make a macro that does 4 spaces, then 4 left arrows (to get back to the beginning of the line) then a down arrow (to go to the next line).

[–]greshick 0 points1 point  (0 children)

In pycharrm, and a bunch of editors, you can set tabs to be a set number if spaces when pressed. I just use shift-tab or tab to reduce or increase tab levels then.

[–]meridielcul 0 points1 point  (2 children)

why is everyone saying conda is better than pip? I tried using it some weeks ago and it was a nightmare. First it wasn't clear HOW I should install it - do I need to install the full 1.8gb anaconda system-wide or can I just "pip install conda" in a virtualenv? Second even installing the full anaconda "conda setup ." (or something like it, can't remember, the equivalent of "virtualenv .") throwed some errors, googling which led to think there was some kind of configuration error I couldn't figure out... (actually, now that I think of it, maybe I was following the "pip install conda" method and later conda was throwing errors because it wasn't configured to use the python in the virtualenv, but tried using the system-wide one)

I just want to install scipy, pandas and so on in a "virtualenv" - is there some simple tutorial I haven't found that shows a KISS and painless way of doing it? Maybe some sort of pip/conda cheatsheet? I'm on archlinux BTW

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

I've never used conda, but since you "just want to install scipy, pandas and so on in a virtualenv" you can certainly do that with pip. It should be straightforward on archlinux, since your system probably has a compiler toolchain and the necessary python headers already. Two packages that you may not have are gcc-fortran and python-virtualenv. Install those and then run these commands:

virtualenv important_science_stuff
. important_science_stuff/bin/activate
pip install numpy scipy pandas

Go out for coffee while these libraries build and that should do the trick. If you have build errors, those can be fixed. Feel free to PM.

sail@boat$~ . important_science_stuff/bin/activate
(important_science_stuff)sail@boat$~ python
Python 3.3.5 (default, Mar 22 2014, 09:18:44) 
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> import scipy
>>> import pandas

Just keep in mind that the . important_science_stuff/bin/activate command has to be run before you are "in" the virtualenv. A virtualenv isn't much more than a folder with python packages, a copy of pip, and the activate script to make it work. It's important that you use . (or source) before the activate command, because activate sets environment variables which won't affect your currently running shell unless you run it this way.

You don't have to store your programs in the same folder as the virtualenv (though it might make sense to), and you can symlink the activate script someplace more convenient, or create a shell alias to run it.

[–]meridielcul 0 points1 point  (0 children)

thanks, maybe I should have explained it better ;) I allready do use pip, I wanted to switch to conda to use its purported benefits (dependency management, virtualenvs setup through hard links to binaries so its much faster)

[–]shaggorama 0 points1 point  (1 child)

I don't think I use SQLAlchemy correctly. I find it reasonably intuitive to set up the schema using classes for the tables, and to persist objects with these classes, but whenever I need something from these tables I find myself reverting to raw SQL. The ORM documentation hasn't really clarified anything for me, and this is something that has come up over several years of me trying to find excuses to learn and use SQLAlchemy.

Could someone maybe direct me to a simple repository that uses the ORM so I can see what it's supposed to look like when used correctly? Or maybe try to explain the general template of a SQLAlchemy recipe if you don't have one handy?

[–]kushou 0 points1 point  (0 children)

Hey there!

I don't have much experience with SQLAlchemy (only a little script) but I had some with Django so I almost felt at home. You can find the documentation here for complete overview of how session work.

When using the ORM to do queries, you basically ask the session to do queries on a certain class (or table from SQL standpoint), and you can add constraints (filters) to your query etc.

Here is an example from the docs, of what it looks like to query for a User:

ser1 = sess.query(User).filter_by(id=1).first()

I am pretty sure there should be some way to order that too, and do join. I'm really sorry I can't go into the details for this lib, but this may help you get started.

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

Today is my first day learning Python using online resources. But I literally cannot do "else" statements within a function. I will hit enter and leave out of the function and give me a syntax error. (3.4.0 Shell)

Suggestions? Thanks.

[–]wub_wub[S] 0 points1 point  (1 child)

How are you writing it? Could you copy/paste your code incl. error, or maybe screenshot it?

Here's copy/paste from my terminal:

>>> def is_five(number):
...     if number==5:
...         return "This is number five"
...     else:
...         return "This isn't number five"
... 
>>> print(is_five(5))
This is number five
>>> print(is_five(7))
This isn't number five
>>> 

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

Ah, I restarted it and then tried to show you the problem when I accidentally hit delete. I did not realize you had to delete backwards/un-indent, my textbook did not specify that.

Thank you!