r/learnpython • • Jul 11 '20

How to earn money using python online?

385 Upvotes

Hi. First of all, I'm sorry I know that this question has been answered already but I wasn't able to get my answer from that. I've been using python for almost 2 years and can say that I'm pretty good at it and improving day by day. I want to make some make money off python even if it's a small amount. I'll learn most of the things if it's not super hard. Also, I'm a teen and due to this lockdown stuff I can't work offline anywhere. It would be a huge help if someone can guide me!


r/learnpython • • Mar 15 '20

I wrote a tutorial explaining and demonstrating `if __name__ == '__main__'`

385 Upvotes

 

The full text is below, but view it at https://voussoir.net/writing/ifnamemain to see syntax highlighting.

 


Python's if __name__ == '__main__'

When you read other people's Python source code, you may find something like this at the very bottom of the file:

if __name__ == '__main__':
    ...

This is a construct that is confusing the first time you encounter it. if __name__ == '__main__' is used to make a Python file that is importable by other Python files, as well as executable on its own.

Understanding if name == main

In order to understand how it works and how to use it, there are a few background pieces of information you need to know.

Part 1

When you are writing a program A.py that imports another module B.py, the code inside B.py is executed just like if you ran B.py by itself.

I know that sounds simple, but it's something people don't usually think about when practicing imports for the first time. Here, watch:

# B.py
print("I'm the B file!")
>python B.py
I'm the B file!
# A.py
print("I'm the A file, and I'm going to import B!")
import B
print("I'm all done importing B!")
>python A.py
I'm the A file, and I'm going to import B!
I'm the B file!
I'm all done importing B!

Suppose you write a file called hextools.py so that you can practice converting between hex and ints.

# hextools.py
'''
This library provides functions for converting to and from hex.
'''
def int_to_hex(x):
    '''
    Python automatically starts it with 0x which we'll strip.
    '''
    return hex(x)[2:]

def hex_to_int(h):
    return int(h, 16)

print(int_to_hex(4000))
>python hextools.py
fa0

It works great.

Then one day, you need to write a second program that also does some hex-int conversion. Well, instead of copying and pasting those functions, it makes sense to just import hextools.

# myprogram.py
import hextools

x = int(input('Please type a number: '))
print(x, 'in hex is', hextools.int_to_hex(x))

Now let's run that program.

>python myprogram.py
fa0
Please type a number:

That's annoying -- the print statement inside hextools is executed, and shows fa0 before myprogram even asks for input. Well, that's because all the code inside hextools is executed simply by importing it. When I say "all the code", I'm referring to anything that's written on the global scope -- anything which touches the left edge of the page. That means the def statements which create the functions and, in this case, the print statement that we left there.

Now you know that importing a file causes that code to run. Hold that thought, it's time for the second piece of background information.

Part 2

Python modules have some special variables in the global scope that are created automatically.

Try starting a python interpreter and calling dir.

>python
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__']
>>> __name__
'__main__'

Ok so there's an automatic variable called __name__ which is a string that says '__main__' but let's keep going to figure out what it means.

Let's start an interpreter with the -i flag which runs everything in the file and then gives you the repl afterward.

>python -i hextools.py
fa0
>>> dir()
['__annotations__', '__builtins__', '__cached__', '__doc__', '__loader__',
'__name__', '__package__', '__spec__', 'hex_to_int', 'int_to_hex']
>>> __doc__
'\nThis library provides functions for converting to and from hex.\n'
>>> __name__
'__main__'

Well, there's that fa0 again. As you can see, there is a magical variable called __doc__ which automatically took the docstring that I wrote at the top of the file. I'm showing that to prove that this is exactly what the variables look like while Python is executing this file. And we see the variable __name__ which again says '__main__'.

One more demonstration. Let's check that name variable again, but with an imported module:

>python
>>> import hextools
fa0
>>> __name__
'__main__'
>>> hextools.__doc__
'\nThis library provides functions for converting to and from hex.\n'
>>> hextools.__name__
'hextools'

Aha. So the __name__ of my Python repl is '__main__', but the __name__ of an imported module is its name.

>>> import os
>>> os.__name__
'os'
>>> import sys
>>> sys.__name__
'sys'
>>> import requests
>>> requests.__name__
'requests'
>>>
>>> __name__
'__main__'

There is only one module that can be '__main__', and that's whatever file we run directly. Anything you import will just have its own name.

Part 3

Let's combine these two lessons together. Any code that you write on the global scope will be executed when you import that file into another. But, the magic variable __name__ will only say '__main__' when you are running that file directly, otherwise it will just say the name of the module.

# B.py
print("I'm the B file, and my name is", __name__)
# A.py
print("I'm the A file, and I'm going to import B!")
import B
print("I'm all done importing B!")
>python B.py
I'm the B file, and my name is __main__
>python A.py
I'm the A file, and I'm going to import B!
I'm the B file, and my name is B
I'm all done importing B!

This should drive the point home:

# B.py
print("I'm the B file, and my name is", __name__)

if __name__ == '__main__':
    print("The B file is being run directly!")
>python B.py
I'm the B file, and my name is __main__
The B file is being run directly!

>python A.py
I'm the A file, and I'm going to import B!
I'm the B file, and my name is B
I'm all done importing B!

Therefore, by putting code inside an if __name__ == '__main__', it will only run when you are running that file directly, and it will be skipped if the module is being imported by something else. There's nothing surprising about how this works. It's just an if statement!

Let's apply that change:

# hextools.py
'''
This library provides functions for converting to and from hex.
'''
import sys

def int_to_hex(x):
    '''
    Python automatically starts it with 0x which we'll strip.
    '''
    return hex(x)[2:]

def hex_to_int(h):
    return int(h, 16)

if __name__ == '__main__':
    x = int(sys.argv[1])
    print(int_to_hex(x))
# myprogram.py
import hextools

x = int(input('Please type a number: '))
print(x, 'in hex is', hextools.int_to_hex(x))
>myprogram.py
Please type a number: 42
42 in hex is 2a

>hextools.py 42
2a

Now, hextools.py can be run on its own with an argument on the commandline, and myprogram.py can import hextools and use its functions without interruption.

Great job!

Why doesn't Python use a main function

In some languages, like C or Java, all you have to do is define a function called main and it will be run when you execute the file. Why does Python use this somewhat awkward magic string variable instead?

In my opinion it's for a few reasons. Firstly, Python spans a broad range of "program formality" levels. If you just write all your code on the global scope:

# someprogram.py
import os
for filename in os.listdir():
    if os.path.isfile(filename) and filename.endswith('.temp'):
        os.remove(filename)

Then you're basically treating Python like bash/batch (except a million times better). In order to allow for this kind of programming, Python is already predisposed to treat files as a list of instructions to execute in order. Compare that with Java where files are more like baskets full of methods and the order doesn't matter because main is where things actually start running.

Consider also that in Python you can do this:

def f():
    print('hello')

f()

def f():
    print('world')

f()
hello
world

Which you can't do in a language like C or Java.

int f()
{
    return 1;
}
int f()
{
    return 2;
}
main.c:7:5: error: redefinition of 'f'
int f()
    ^
main.c:3:5: note: previous definition is here
int f()
    ^
class Main {
    public static int f()
    {
        return 1;
    }
    public static int f()
    {
        return 2;
    }
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}
Main.java:6: error: method f() is already defined in class Main
    public static int f()

And then there's Javascript, which I guess must do a parsing pass before running but doesn't complain about redefines.

function f()
{
    console.log("hello");
}

f();

function f()
{
    console.log("world");
}

f();
world
world

But anyway. On the opposite end of the formality spectrum, you can write Python files where everything is tucked away into classes and functions and the file is designed as an import with no regard for command-line usage of that particular file. Well, if Python already has the predisposition to just run all the code on the global scope, why should there be a separate parsing mode, and how would it know which one to use?

That's not to say I love if __name__ == '__main__'. I would prefer to have a separate __main__ magic variable that is True or False, then you can just if __main__:. The __name__ string is still fine for other purposes, like printing the module to the screen.

As a matter of fact, whenever I upgrade a Python script from quick prototype to reusable code, I always move the main code into a C-like function called main via this template:

def main(argv):
    # At this point I usually do my argparse
    return 0

if __name__ == '__main__':
    raise SystemExit(main(sys.argv[1:]))

That's because if you make any variables inside if __name__ == '__main__', they will be part of the global scope which may have accidental side effects. For example:

# bad.py
import sys

def int_to_hex():
    return hex(x)[2:]

if __name__ == '__main__':
    x = int(sys.argv[1])
    print(int_to_hex())

# Great, everything's ready to ship!

Spot the error.

Whereas by creating a main function, any variables in main are local variables and are not accessible outside of it.

Real-life examples.

I understand that the examples shown here are very simplistic. Here are some links to my other programs which use ifmain in a purposeful way.

  • bytestring is imported by many of my other programs, but also is very useful on its own.

  • epubfile can be imported into any program that wants to modify epubs, but has a number of builtin utilities that run from ifmain.

In a very large project with many files, it's more likely that you'll have a main launcher file, and none of the internals are very useful to run on their own. ifmain essentially bridges the gap to make single Python files useful as imports and standalone utilities.


r/learnpython • • Aug 07 '24

Creating an Instagram bot that will block everyone over 10,000 followers

383 Upvotes

My friend and I are going to create an instagram bot that will block every account over 10,000 followers as well as accounts that have certain words in their bio/name such as "daily" or "Jesus". My friend is a computer science major and has experience with python. Reason: I am TIRED of influencers.

I believe this is going to take the bot an extremely long period of time to complete and I read that making a bot operate quickly can risk you getting banned.

How likely is this to work? Will I get banned? Is blocking people on Instagram with a bot something that is deemed "illegal" in the Instagram bot realm? Have you ever done this?


r/learnpython • • Oct 29 '21

Why is this so common in python tutorials?

383 Upvotes

They will walk you through the most basic and simple application of something and then the practice activity by comparison is not only insanely difficult, you just wouldn’t know how to do it given what has been taught so far. Why can’t they just give activities that are at or around the same level of difficulty of what they teach? I want to learn how to walk before learning how to run.


r/learnpython • • Oct 22 '20

How and where can I start contributing to an open source project?

383 Upvotes

Does anyone know where you can find open source projects to contribute to quickly and easily. I have never contributed to any open source projects before, so this will be my first time. I also probably only have a years worth of python experience, so it can't be too advanced/complex.

Any help would be greatly appreciated. Thanks


r/learnpython • • May 09 '20

TIL that Spyder allows you to create "Cells" just like Jupyter Notebook so you can separate out blocks of code that you can run by itself in ipython

383 Upvotes

https://docs.spyder-ide.org/editor.html#defining-code-cells

Yeah anyways after more than a literal decade of using Spyder found this out. Nice. For all the new IDE's out there I always keep coming back to this one.


r/learnpython • • Jun 30 '19

What are some 'speed hacks' that I, as a beginner, should be aware of when I code in python?

383 Upvotes

For example, a few helpful people in this subreddit advised me to use f-strings instead of %-formatting or str.format() and to utilise numpy arrays when working with large/complex lists.


r/learnpython • • Jul 15 '20

Python Subreddit for "Intermediate" Questions?

381 Upvotes

Is there a good subreddit to ask "intermediate" python questions? /r/learnpython has been very helpful (and continues to be! thanks!), but usually I don't get responses when I ask questions about, say, PyQt5 or async stuff. And then the people over at /r/python are too important and busy with their 10 hot girlfriends each to discuss mere questions, and usually point me back here.

Of course there is Stack Overflow, but I do feel that reddit is better for discussion vs. posting a question and getting sample code as an answer on SO.


r/learnpython • • Mar 01 '21

I am struggling in my first python class. Does this mean the computer science track isn’t for me?

379 Upvotes

I have a good grade in the class thanks to the help of a tutor, but I feel like the information just isn’t clicking like it should be. I struggle doing any of the assignments on my own. There is only one week left in the class. Has anyone else had this struggle and went on to have it really click or am I hopeless? Loops really confuse me and those seem to be the basis of everything.


r/learnpython • • May 09 '22

where to start to learn python

378 Upvotes

Hey guys, This has probably been asked a lot but I want and have to learn python and I would love to hear recommendations from people where to start ( websites, etc.) I know I could Google this but I like to communicate and interact with people :P Thanks in advance!


r/learnpython • • Mar 05 '21

Jupyter Notebooks - Great tool for beginners

378 Upvotes

Just wanted to share with anyone who is struggling to learn AND implement code. I'm in my 4th week of Intro To Python and I have to say, I got a little overwhelmed. My teacher recommended using Jupyter Notebook (Google it, it's Free!) and it's helped out a shitload. Basically it's an open-source web app that allows you to share documents that contain live code. The BEST part is you can easily toggle between text for note-taking and code AND RUN THE CODE right in the document. This really changed the game for me and if you're out there struggling to bounce between your notes and your interpreter/compiler, check it out. Good luck


r/learnpython • • Nov 12 '20

Help for my 13 year old son is creating a python game

378 Upvotes

Hello, my 13 year old son is creating a python game. Is anyone interested in seeing it and giving positive and negative feedback? As well, is there anything I should do to support him? I am paying for python coding courses.

Edit I have read these comments. Thank you very much for your help and support. I will ask him to upload his code as suggested. I do not know how to do that but I will ask my husband to help me. Thank you all kind people!


r/learnpython • • Jan 14 '20

I've made a python program that let's you mass download images from a given subreddit!

377 Upvotes

The program/script can be found here.

Any advice would be appreciated, thanks in advance!

This is my first code over 100 lines, so it may be messy, sorry for that.

------------------------------

How to use?

Go to the link given above, and download the program. (The first page given, there's no releases or anything)

Once you got it downloaded unzip it somewhere, and open usersettings.py file with any text editor, then fill out the information.

Once that is out of the way open cmd, and download PRAW library. (pip install PRAW), then head over to the directory where sid.py is located, and type in sid.py subreddit_name sorting (Sorting can be top/hot/new/rising).

------------------------------


r/learnpython • • May 02 '20

Would you like to learn python with a group? Cohort style groups for people at similar levels or using similar material could help a lot of people.

376 Upvotes

I've been thinking of organizing a group of people similar to my own level who would like to learn together. I'd be interested in potentially hoping on a zoom periodically and helping each other through problems and just generally navigate the world of python and programming at large.

No real solid ideas so please share any that you have as well if you'd be interested!

I've personally just finished Python Crash Course and have built a few small programs such a game of 21 that you play against a computer dealer. However if there are enough people who are interested we could have a few different levels.


r/learnpython • • Jan 01 '21

Are there any YouTube channels like The Coding Train, but they code in python?

375 Upvotes

Or any YouTuber that records themselves programming some project in Python without it being a tutorial?


r/learnpython • • Jul 16 '20

Where to learn about Python program structure/design?

375 Upvotes

I'm self-taught in Python and am able to write programs that work, but I still don't feel like I know what I'm doing. Where can I learn about program structure/design?

I usually just start coding and one thing leads to another and pretty soon, I'm done. But I can't shake the feeling that a professional programmer would look at my code and laugh at how haphazard and inefficient it is. Any pointers or suggestions? Or are we just supposed to figure it out for ourselves?


r/learnpython • • Jul 16 '20

Just finished "Automate The Boring Stuff With Python''. What next?

375 Upvotes

Should I start building projects? What are some good beginner projects to start on? What books will help me build projects?


r/learnpython • • Dec 08 '17

Here's a website with 100+ short exercises for beginners to Python

374 Upvotes

Useful for any beginners over at www.pythonsandladders.com. A good number of questions to go through, some perhaps a little challenging even for seasoned problem solvers.

The whole thing runs in the browser through Skulpt, using JavaScript to emulate Python 2.6.

Happy coding!


r/learnpython • • Nov 15 '20

My first competition, and why they are more important than you realize.

373 Upvotes

Hi all,

Today I joined my first coding competition, using Python (I know Python isn't recommended, but it's my dominant language). 3 months after finishing the full course of Python and doing projects, school started. I recently started my freshmen year in high school and that was when my problems started.

Because I didn't have a lot of time to code or complete projects, my unused knowledge in Python died. I recently started doing Hackerrank due to the positive reviews everyone gives, but I was immediately overwhelmed. Though the questions started out easy, it immediately curved to a point where I didn't understand. Because I didn't want to give up on Hackerrank, I took some time off it to learn Algorithms and Data Structures from geeksforgeeks.org which had massive amounts of courses. Once again, I was left with no direction and a sense of being lost in a desert.

Recently, I joined a computer science club in school. I didn't think too much about the club and just went in. I soon signed up for a coding competition that took place today. We win or do anything notable, but it was all I needed. The questions in this competition started from easy (printing out "Hello World", concatenation, etc.), to more advanced things. For the first time in around 3 months, I was able to solve problems that were not too hard, but not too easy, and pushed me outside my comfort zone. I finally have the same feeling of direction and joy of coding as when I printed "Hello World". I was finally able to apply things that I learned into coding.

I'm no expert, and I don't want to act like one, but for someone who was struggling to progress in their journey in coding, I highly suggest you join a competition or club if you had the same problem as me. I have learned more from 4 hours of straight coding than 1 month of "learning" algorithms.


r/learnpython • • May 28 '20

Just finished my first official project!

373 Upvotes

Hi :)

I have been learning python programming for the last two months +- but i was always scared to start a project and fail in the middle.

i have done a couple of scripts that to little stuff but this is the first time that i tried to build an official project that is not following a tutorial and with git, github, python structure and all of those stuff.

i call it..... Flasher!!

it is a simple Flask web with a button where every time the user presses it it links him to a random flash game from the past.

it is not really complex, I will link here to the github page but i will also write here that my objective was to take a bunch of little topics I have learned in the last month-month and half, configure them to work together and make them do something lol.

obviously there is a *91025915 better way to build what I built but I am still extremely proud of it because in the end I was able to think of something and build it from scratch from start to end, something I would not imagine I would be able to do around a month ago :)

i want to also thank the people of the python and learnpython subreddit that have helped and inspired me to program :)

now i will shut up and link to my project!

https://github.com/Micbenh/Flasher


r/learnpython • • Apr 13 '20

THANKS A MILLION

373 Upvotes

I'VE been a part of this comunity for a couple weeks now, give or take a month. and so fare this place has actualy helped me grow so quickly and i just wanted to say thanks

it's nice to be a part of something positive like this and i look forward to the day where my knowlidge aand experience can help some1 on their journey

don't give up on yourselves guys... you can do it


r/learnpython • • Dec 21 '20

What does "have an understanding of basic python" mean?

372 Upvotes

Sometimes when you wanna take online course on specific python topic like "Web development with Django!" or "Data science with Python", it is recommended that you need a "basic understanding of python". Like what does that mean?

I understand functions, arrays, conditional statements, variables, loops and mathematical operations. But I don't know jack about class, lambda, decorators, etc (I actually don't know how much I don't know). The most complex stuff I did with python was making an animated scatter chart using plotly while heavily relying on tutorials and stuff. Am I considered to have a basic understanding of python?

I wanna learn web development and data science from online courses and I am willing to pay for it if I need to. But I don't know if I'll be able to understand enough to follow the courses


r/learnpython • • Dec 03 '20

Python Projects for Beginners

372 Upvotes

Any sites or books for doing projects for python beginners?


r/learnpython • • Aug 10 '20

Feeling dumb after seeing the best solutions on codewars

372 Upvotes

I've already got the basics and I can easily solve the beginners problems on codewars, but when reading the best solution I feel very dumb for not knowing a lot of operators, having difficulties with list comprehension, or even not knowing why it is working at all.

Should I just solve it in my own way or should I stop and try to write like the best practices?

In my own way I could solve in 5- minutes and find it waay more readable, when trying to write like the best solution I spend like 30+ mins.

Edit: Thanks everyone for your answers, like some people mentioned, this is entirely the point, learning is challenging. I won't care too much about the one line solutions, but I should learn how they work. Got a lot of ideas on where should I head next.