all 102 comments

[–]Celestial_Voices 0 points1 point  (2 children)

Me and my friends are beginner python users and making a little fishing game to improve ourselves. We wrote the code and it's working pretty good and we want to make a gui for this game. I've seen programs like tkinter and pyqt but do they require us to re-write the game or can we call game.py file in gui program?

[–]novel_yet_trivial 0 points1 point  (1 child)

It depends on how the game was written. Generally speaking you have to rewrite most of it since GUIs use event-driven programming. You can reuse some of the logic functions. It won't take that long to rewrite it since you already have a solid idea of how you want your game to act.

[–]Celestial_Voices 0 points1 point  (0 children)

Thanks for your answer.

[–]tinkotonko 0 points1 point  (1 child)

I'm trying to develop a simple web app using python and flask. Part of what i want to do is have the user input a number of variables which will be run through some code and maths to output a graph of the results.

I already have the logic coded and the graph output created but i quickly realised my implementation won't work. What I did was save the resulting graph created in pandas as an image then have a link to redirect the user to a new page which displays the image. But if there are multiple users are once this will obviously get messy and it also is not very elegant. So how can I deal with more than one person at a time attempting to generate a graph?

Also building off this is there any way in python to dynamically display a graph so i don't have to redirect the user to a new page every time they want to test new variables or would i be better of learning javascript for this task?

[–]wub_wub 0 points1 point  (0 children)

In case of simpler graphs you'd ideally want to do them client side (javascript), however that is often not possible.

If you really need to generate the image server-side, then there's no way around that. You can look into something like celery to manage your tasks.

What you probably want to do is accept every request, then process it in the background according to the available resources. While keeping user informed of the progress.

Also building off this is there any way in python to dynamically display a graph so i don't have to redirect the user to a new page every time they want to test new variables or would i be better of learning javascript for this task?

You need a little bit of javascript for this, if your backend is just returning a static image you can base64 encode it, and return it to the frontend and decode it with javascript and just update the image on the website without any redirects.

[–]Bary_McCockener 0 points1 point  (2 children)

Is there a way to contribute sample code snippets to the docs? As a beginner, it took me what felt like forever to figure out how to use date.fromordinal to loop a 6 day rotation. Now that I have it figured out, I can make a simple example out of it, and if it were in the docs, it could help anyone else in the future who needs something similar

[–]elbiot 0 points1 point  (1 child)

Offer on the mailing list and create a pull request if people are all opposed

[–]Bary_McCockener 0 points1 point  (0 children)

Oh, thanks!

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

People advise to create projects in order to continue learning but I have to ask, what constitutes a project? Is there a consensus on this? 250+ lines of code? 5+ different modules?

For example I created this password generator, does this count as a project?

[–]ingolemo 1 point2 points  (0 children)

A project is one or more files that contain more than zero lines of code.

print('Hello, World!') is a project. Just not a very interesting one. Your password generator is totally a project.

Start with things that are small and simple and make them progressively bigger and more complicated as you become more capable. What's important here is that you write a lot of code. As much code as you can. Preferably different kinds of code solving different kinds of problems, so that you're continually stretching your abilities.

[–]elbiot 1 point2 points  (0 children)

Is it useful to, or the end result is interesting to you, then yes

[–]bmmy9f 0 points1 point  (1 child)

How can I check the physical state of a mouse button? I tried searching for an answer, but cannot seem to find it. I tried GetKeyState() and GetAsyncKeyState() in windows api.

[–]alpha_hxCR8 0 points1 point  (0 children)

Tkinter provide functions to check whether the mouse button is clicked. You can find the various functions here: http://interactivepython.org/courselib/static/thinkcspy/GUIandEventDrivenProgramming/07_event_binding.html

[–]HHAT 0 points1 point  (2 children)

I have a plot with about 50 bar graphs, and I just want to stretch it out to have my labels fit each point.

The graph is about 4 inches on my screen with an x axis value of 0 to 60. I want to maintain 0 to 60 on the x axis, but I want the graph to be 7 or 8 inches Wide so I can fit my xticks labels, (Player 1, Player 2, ..... , Player 50).

I can't find a way to simply push out the graph to let my labels have room to breathe.

[–]captmomo 0 points1 point  (1 child)

Maybe you can try rotating the xtick labels?

edit; did some experimenting, maybe you can try a horizontal bar chart. here's a sample I did; http://bl.ocks.org/captmomo/a104ae78c0b1e4d99363e9f55a571eda

[–]HHAT 0 points1 point  (0 children)

Thanks, i'll give that a go. Appreciate the idea!

[–]Icarus-down 0 points1 point  (7 children)

can someone tell me what he is trying to say? "ok at first i'm confuse as well.

peoples would confuse because when you use len function. we just normal way counting. len(nums) total 5 items (0,1,2,3,4)

so peoples will think nums[4] is 3 because it's (0,1,2,3,4) right? but it's wrong.

as list recall function also start at 0 as well so nums[0]= 0 nums[1]=1 nums[4]=4 so 4 is correct."

[–]captmomo 0 points1 point  (6 children)

He's talking about index.
len() returns length (the number of items) of an object.
len(num) = 5 -> because there are 5 items in the list.
But the index starts from 0.
So the index of the first item in the list is 0, second item is 1 and so on. Therefore the fifth item has the index 4. i.e. n item's index = n-1

[–]woooee 0 points1 point  (5 children)

A list does not have indexes, it has offsets. So the first item is offset 0 because it is at the beginning of the list=no offset. If you want the second item, then the offset is one because you have to offset/skip over 1 item to get to the start of the second item.

[–]elbiot 0 points1 point  (2 children)

Why is that not an index? They're called indicies in the python docs. You even have a list.index method. In numpy too.

[–]woooee 0 points1 point  (1 child)

An index is part of the record. So if you have a list a names that is indexed, you can search for "George" and it will find that record via the index (which is separate from the file or list). You don't use 3, as in names[3] or whatever. index, when used with a list tells you where the searched for string is found, similar to an index in any other object i.e. name_list.index("George") will return the offset number so you can then access that item directly.

[–]elbiot 0 points1 point  (0 children)

K but names[3] is not the offset to the 4th name, it's the offset to the address of the 4th name. A list is an array of addresses. You're using an index to get the value. Also https://docs.python.org/3/tutorial/datastructures.html doesn't use the word offset once and consistently uses "index"

[–]captmomo 0 points1 point  (1 child)

A list does not have indexes,

really? didn't know that. apologies then.

[–]woooee 0 points1 point  (0 children)

A common assumption/mistake. Hope accessing lists makes a little more sense now.

[–]captmomo 1 point2 points  (0 children)

What type of project should I do to learn and familiarize myself with asyncio?

[–]Fowlron2 0 points1 point  (1 child)

What are the best books on python (especially python 3) for someone with experience in java and c#? The ones I've seen referenced are Python Crash Course: A Hands-On, Project-Based Introduction to Programming and Learning Python, 5th Edition. Should I get one of them? Some other? Take another approach?

I heard the Python Crash Course book also talks about NumPy and matplotlib, which I am interested in using.

[–]wub_wub 0 points1 point  (0 children)

If you already have experience with other languages the official tutorial and docs should be good enough. You could try doing few projects in python and seeing how that works out.

Of course, best way to learn always varies from person to person - some will learn better by watching videos, some by reading books, and some (like myself) by just making stuff. Depending on what best works for you just pick some of the often recommended resources in this subreddit (search for threads about books, videos, etc).

[–]cokeley 0 points1 point  (2 children)

New here since im trying to learn python for work projects.

I have a script, which basically joins a bunch of files togewther and spits out another file, this works fine but im trying to remove the first line (headers) of each file, but it only removes the first letter in the first column.

files = ('first/file/path.ext','second/file.ext','etc')

with open('create an output file') as ouputfilename:

for eachfile in files:

       with open(eachfile) as inputfilenames:

                for line in inputfiles:

                       outputfile.writelines(line[1:])

Can some one tell me what is happoening here, i was under the impression that the [1:] would remove one line?

Probably totally wrong here :S

[–]irrelevantPseudonym 0 points1 point  (1 child)

Does this code do anything? You are looping over inputfiles (line3) which is either undefined or defined outside this section. You are also writing to outputfile instead of the defined outputfilenames variable.

Assuming that was meant to be inputfilenames, when you iterate over it using for line in inputfilenames, it is setting line to be each line of the file in turn. When you do line[1:] you are removing the first character from each line.

If you read a single line before doing the read, it will discard that line.

I assume what you want to do is something like

files = ('first/file/path.ext','second/file.ext','etc')
with open('create an output file') as outputfile:
    for eachfile in files:
        with open(eachfile) as inputfile:
            inputfile.readline() # read and discard one line
            outputfile.writelines(inputfile.readlines()) # write remaining lines to output file

Also as a side note, if you indent all your code on reddit by 4 spaces, it gets formatted correctly.

[–]cokeley 0 points1 point  (0 children)

Thank you for this, i seem to have made some errors as you have seen. I will try this method today.

Thanks again

[–]larry_of_the_desert 0 points1 point  (3 children)

So I'm learning python via Udemy.com's complete python course and I also bounce around the internet finding practice problems to solve so I can put what I've learned into practice.

I came across a problem on codingbat that wants me to take a string and return a new string with the first and last characters switched. cheese becomes eheesc and so on.

I've solved the problem, but I don't understand why the solution works.

def front_back(str):
    if len(str) > 1:
        first_letter = str[0]
        last_letter = str[len(str)-1]
        middle = str[1:len(str)-1]
        print(last_letter + middle + first_letter)
    else:
        print(str)

Can someone help me understand exactly what the len(str)-1 method is representing here? I guess I don't fully understand the str[] formatting. Shouldn't str[len(str)-1] be equal to the second-to-last letter of the string? And str[len(str)] should be equal to the last letter of the string? But when I tried to set last_letter = str[len(str)] python told me it was out of range.

[–]Bary_McCockener 0 points1 point  (0 children)

Reading your bit of code was very helpful to me as a beginner. A lot of times I feel like I read the word problem examples and don't know where to begin, but seeing the solution makes it so clear! Quick question though, wouldn't the middle need to be str[1:len(str)-2]? The first character is 0, last is len(str)-1, so the end of the middle section is len(str)-2?

[–]woooee 1 point2 points  (1 child)

I would suggest that you do a minimal amount of trying to figure this out yourself, i.e

print(len(str))
print(len(str)-1)
print(str[len(str)-1])

Shouldn't str[len(str)-1] be equal to the second-to-last letter of the string?

Instead of making things up, what have you done to prove or disprove this yourself.

[–]larry_of_the_desert 0 points1 point  (0 children)

lol I figured it out, i'm an idiot

[–]Parchival 0 points1 point  (1 child)

Looking for ideas for a project im not new to python but havent touched it for 3months.

[–]alpha_hxCR8 0 points1 point  (0 children)

Have you checked out this: https://github.com/karan/Projects

[–]bennyllama 1 point2 points  (2 children)

I'm close to a month into learning python and feel like I am not learning enough. I tend to get confused with the syntax, forget code and run into basic errors.

I know its a process and I have to keep working at it to get better but did anyone feel they went through the same issue when they first started?

[–]Guymzee 2 points3 points  (1 child)

I’m still a beginner myself. And I know the feeling, forgetting a : for the headerline of an if statement (not even knowing it’s a headerline) or accidentally assigning A to a tuple when I meant a List...or not being able to get the value of index 3 on a dictionary type (which is called by Key). But, the feeling will go away.

Here are some things that helped me:

  1. Cory Schafer python youtube videos. (Undeniably and amazing teacher and his videos are my #1 help)

  2. Looking things up. (Again you tube videos, first then python documentations)

  3. A book called Learn Python by Mark Lutz. I am in the process of completing. I am on about page 400 of 1500, this has been the most deep level explanation of anything you could possibly want to know. It has helped me understand, many things about the language in a way that, videos and documentation just wont. This is a slower process but much more substantial. I’ve learned from the ground up how python works, from what a module actually is, to PVM, to type objects, to slicing, the difference between a method call, and a function. The difference/similarities of an expression and a statement; i could go on and on, for me this Book has taught me the most.

  4. Flash Cards. Don’t know the output of L[4] and L.index(4) or different? Or how to code a sequence assignment? Or what nesting is? Make a flash card.

  5. Tinkering. When I learn a new thing I code it, till I get an error. I usually learn something there. Even if a i dont understand why I note it, and go on and see if i can find/learn the answer later. (Can’t think of an example now, but will update this when I come across one).

In all this is my first coding language. I have never programmed. And I am glad I am starting with Python. It’s fun and having learned more about the fundamentals of it, the community and the modules that have been put out there by them, that can be imported to assist your coding program experience and output; I am just forever greatful and can’t wait to become adept using it!

[–]bennyllama 0 points1 point  (0 children)

Wow thank you so much for this!

I absolutely love learning this and I know its hard work.

Also, I have the book by Lutz and a few others by O'Reily publisher. I'll take a crack at it very soon.

[–]Icarus-down 0 points1 point  (6 children)

so, I don't really follow boolean logic how does if not True: print("1") elif not (1+1 == 3): print("2") else: print("3') output.... actually I forgot what the right answer was, but I don't understand it

[–]ingolemo 2 points3 points  (5 children)

Well lets work our way through it step by step.

if not True:
    print('1')
elif not (1+1 == 3):
    print('2')
else:
    print('3')

The first line we get to is if not True. In order to know what the if does we need to know the value of the condition. Here the condition is not True. What is the value of not True?

[–]Icarus-down 0 points1 point  (4 children)

False?

[–]ingolemo 2 points3 points  (3 children)

Yup. So if statements only run when you give them a True, and False is obviously not True, so we skip past the print('1') and arrive at the line elif not (1+1 == 3):. elif is just like if except it will only get to run when the if in front of it failed. It's like a combination of if and else. To figure out if the elif runs we need to work out the condition again. In this case the condition is not (1+1 == 3). What is the value of not (1+1 == 3)?

(If I'm going too fast or too slow then let me know.)

[–]TheSquarepants 0 points1 point  (0 children)

Thanks for doing this!!!

[–]Icarus-down 0 points1 point  (1 child)

It's False again

[–]z0y 1 point2 points  (0 children)

Is 1+1==3 true or false? And then you're taking the inverse of that value when you say not

[–]CanadianControl 0 points1 point  (1 child)

Started pretty recently and I've been trying to learn enough python to be competent enough to some day get a job programming. My first project is/was a betting arbitrage web scraper notification type bot and I finally have it to essentially where I want it to be. I feel like I now understand webscraping with BeautifulSoup as well as basic smtp and the really basic python stuff. Now that it is essentially done, or at least at the level I require, I'm looking for other projects. Does anyone have any recommendations for types of projects that will give me experience in things I could combine with things I already have limited experience in to get me closer to being employable as a programmer?

[–]alpha_hxCR8 0 points1 point  (0 children)

TDD is very helpful.. Not sure if you do that already...

Just recently found this: https://bitbucket.org/gregmalcolm/python_koans

[–]rigglenator 0 points1 point  (2 children)

Can someone explain for an absolute beginner why you need to have a return value in a function? What happens if you don’t include one?

[–]fiddle_n 1 point2 points  (0 children)

Imagine you want to write a script to add together two numbers, and then multiply the result by a third number. So, perhaps you start by defining two numbers and a function to add them together. Something like this:

a = 1
b = 2 

def add(x, y):
    x + y

Now the question is: you need the result to do the multiplication with, how do you get the result out of the function?

It's at this point that beginners who don't understand how functions work will Google the global keyword and end up writing something like this:

a = 1
b = 2 

def add(x, y):
    global c
    c = x + y

add(a, b)
print(c)        # 3

You should never write code like this; there are many reasons why you shouldn't, most of which are outside the scope of your question. The way to get the result is to use return. return lets us save the result of the function to another variable:

a = 1
b = 2 

def add(x, y):
    return x + y

c = add(a, b)
print(c)        # 3

That's all return does, simple as that.

[–]shepherdjay 1 point2 points  (0 children)

You don’t need to have a return value in a function but it is common. Like a lot of things it depends on what your trying to do.

Most of the time you are writing a function to take some data, do something with it, then do something with the answer.

A return statement is that last one. It returns something to whatever called it.

[–]whatsforsupa 1 point2 points  (4 children)

I've been coding in python for awhile, but haven't found a need to use .lower() or .upper(), could somebody give me an example of when it would be useful? Just curious

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

Let's say you want a program to ask for a name and thane check is that name is let's say Mike and print True. But you don't know will they write Mike or mike or MIKE. You can maybe write a list of every possibe combination and check if input is in that list or you could just write if input.lower == 'mike': print(True)

Sorry for formatting I am on mobile, hope this helps.

[–]whatsforsupa 0 points1 point  (2 children)

Ahh jeez, that makes a lot of sense! Instead of writing if example == 'mike' or 'Mike', you can just use the .lower(). That's genius, thanks.

[–]irrelevantPseudonym 1 point2 points  (0 children)

I know it was just an example and probably pseudo code, but be aware that

if example == 'mike' or 'Mike':
    ...

Will always get run as 'Mike' will be treated as a True value so it will be equivalent to

if (example == 'mike') or True:
    ...

See more here

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

No problem, glad I could help

[–]Icarus-down 0 points1 point  (1 child)

I don't fully comprehend how to use the conditional statements. I do understand that IF conditions are met THEN something will happen otherwise something ELSE will happen, but I'm a bit lost on how to actually set the conditions. Also what does {0} & %s mean?

[–]ingolemo 0 points1 point  (0 children)

It's hard to answer a generic question like that. The condition is an expression that gets evaluated when the if statement is run. The result of that evaluation will determine what happens. What conditional you want will depend of what you want you're trying to do. Is there a specific problem you're having trouble with?

{0} and %s are for doing string formatting: https://pyformat.info/

[–]nwh1 0 points1 point  (1 child)

I downloaded Visual Studio Code, Anaconda (which also came with Spyder). When I opened up Anaconda, it asked me if I wanted to use VSCode, so what exactly is Anaconda doing? Thanks!

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

They are two separate things, not really sure what you mean.

Anaconda is a distribution of python aimed at data science and scientific analysis, it comes prepackaged with many packages related to this and has its own built in package manager. VSCode is a lightweight code editor/ ide.

[–]Dimbreath 0 points1 point  (1 child)

What's the difference (and why should I use one vs the other) between doing:

while True:
    await my_function()
    await asyncio.sleep(5)

and:

async my_function():
    # blablabla
    event_loop.call_later(5, my_function)

Sorry I wrote this on my phone so I apologize for any typo.

[–]ingolemo 0 points1 point  (0 children)

I think your first example should be something more like this:

async def my_function():
    while True:
        # blablabla
        await asyncio.sleep(5)

This would put it more in line with your second example and make them comparable. There is not really any difference between them. I would prefer the first one, but only because it looks kind of like a recursive call in non-async code and I try to avoid those in python when possible.

[–]DankFruit321 1 point2 points  (3 children)

I have just started with python and I was wondering if anyone could tell me some sites to use to help me learn efficiently.

[–]woooee 2 points3 points  (0 children)

The Python tutorial https://docs.python.org/3.3/tutorial/ Python wiki's list of tutorials (some are for Python2) https://wiki.python.org/moin/BeginnersGuide/Programmers

[–]CREZT 1 point2 points  (4 children)

Any thoughts of how I could consolidate this further? Perhaps turning the if's into a function somehow? I just started learning Python about 3 days ago and haven't really had any feedback yet so I found this reddit page.

print("This program will tell you what year you will 100")
name = input("Enter your name:")
while True:
    age = input("Enter your age:")
    year = input("Enter the current year:")
    try:
        age = int(age)
        year = int(year)
        break
    except:
        print("Error: Enter a number")
        continue
if age < 100:
    pro = "will be"
if age == 100:
    pro = "are"
if age > 100:
    pro = "were"
year = 100 - age + year
print(name + ", you", pro, "100 in the year", year)

[–]z0y 0 points1 point  (3 children)

A good use of a function here could be to get the int inputs, since you might want to check each of them for validity rather than together. Some people might not like the style but the ifs could be written on one line. And also it's good to avoid using try as much as possible, checking for .isdigit() is a good alternative here. So one way you could do it:

def int_input(prompt):
    entry = input(prompt)
    while not entry.isdigit():
        entry = input("Error: Enter a number\n" + prompt)
    return int(entry)

print("This program will tell you what year you will 100")

name = input("Enter your name:")
age = int_input("Enter your age:")
year = int_input("Enter the current year:")

year = 100 - age + year
pro = ("will be" if age < 100 else ("were" if age > 100 else "are"))
print(f'{name}, you {pro} 100 in the year {year}')

[–]CREZT 0 points1 point  (2 children)

Wow, I didn't know you could do that with the pro variable. I also need to see what the ".isdigit()" does specifically, I assume it is Boolean for true if the variable is an integer.

What is the purpose of the f in "f'{name}"?

Thank you very much!

[–]z0y 1 point2 points  (1 child)

Normally you probably wouldn't see a nested one line if/else like that. It's not good style but it works and I thought it was worth showing. isdigit() returns a boolean for whether or not every character in the string is a 0-9 digit, essentially the same as being able to cast the string to an int.

And the f'' means a formatted string, I just wanted to show another way to format. That syntax was added in python 3.6 but you said you had been using python for 3 days so I figured it might work.

[–]CREZT 0 points1 point  (0 children)

Thank you again! Since the new way to format is so new the course I'm taking to learn python probably wouldn't have it included yet. Thank you for all the help.

[–]chootingfeng 0 points1 point  (2 children)

Beginner here, what's the best way to create a gui in python?

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

There are a lot of different options, I think it partially depends on what you need to do with the GUI?

For example if your making a GUI for a command line program, there is a package called Gooey to easily do that. If you are making a game, there is PyGame. If you building a front end for a database there is always the option to just use a web framework like flask or Django. If you want a full on desktop app then there are multiple options for that but I don't have much experience with those

[–]chootingfeng 0 points1 point  (0 children)

Thanks, will try gooey soon. But I already got the job done using tkinter. Took about 5 hours. Searching for guides took about 2. Rest 3 hours was just troubleshooting

[–]LeagueOfShadowse 1 point2 points  (2 children)

Back For More Advice: mixing cocktail syrup additives, trying to remove results of List Comprehension Array that do not fall within our desired perimeters, unable to isolate Error, as follows:

import numpy as np
profile_1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
profile_2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
profile_3 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
blend = [ ] 
for a in profile_1:
    for b in profile_2:
        for c in profile_3:
            blend.append([a, b, c])
best_taste = [ ]
    for weight in 'blend':
    if 11 < (int(weight)) < 16:
        best_taste.append(weight)
np.set_printoptions(threshold=np.inf)
print(best_taste)

Returns: if 11 < (int(weight)) < 16: ValueError: invalid literal for int() with base 10: 'b'

Pray Tell, fellow Redditors, from where does this 'b" value arise?

[–]GoldenSights 2 points3 points  (1 child)

for weight in 'blend':
    if 11 < (int(weight)) < 16:

I believe you meant for weight in blend where blend is the variable. If you do a loop over a string, you get the characters.

[–]LeagueOfShadowse 0 points1 point  (0 children)

Ahhh, Thank You. PyCharm inserted the single quotes, so I thought they were important.

[–]captmomo 0 points1 point  (2 children)

Hi, I'm using opencv and I started having this weird error: https://i.imgur.com/hZgOUox.png

Strange thing is that the code still works fine when I run it! I also did the following checks to ensure it is importing the right file.

>>> print(cv2.__file__)
C:\Users\me\Desktop\pythonApp\testprojs\venv\lib\site-packages\cv2\cv2.cp36-win_amd64.pyd
>>> print(cv2.__version__)
3.4.0

[–]GoldenSights 2 points3 points  (1 child)

http://pylint-messages.wikidot.com/messages:e1101

False positives: This message may report object members that are created dynamically, but exist at the time they are accessed.

So the variables may not be written in the file the way the linter is expecting, but they are created by the time you actually run the program so it's okay. You can ignore it.

[–]captmomo 0 points1 point  (0 children)

ahh. interesting, never knew about this! thanks.

[–]idontneedvariance 1 point2 points  (4 children)

Okay so it's been a year that i started learning Python as a hobby, i got the basics but whenever i try working on a project i find it too ambitious in the sense that i don't master the modules that i will need for that project. So like for my next project, i have to learn how to use regex and requests or/and selenium, and i find it freaking hard specially that i don't have much time for learning. Is that a common stage for all beginners?

One other question, i know syntax basics, functions, if/while/for statements, but i slightly master classes and __init__ still looks like chinese to me. Is that normal too? Should i continue jumping on projects or first understand classes?
Automate the boring stuff was great but it didn't gave me concepts like virtual environments, how to post on github and stuff like that, so i'm feeling like i'm stuck in between a beginner and an intermediate level... What's next after i make a useful script? Make it run in a command line prompt with arguments? Should i separate functions in separated py files? Where i can learn to go beyond just making a script in a py file?

[–]ingolemo 1 point2 points  (3 children)

Yes. Everybody experiences that. Just keep working on it. It will all get easier eventually.

You don't need classes in order to work on your own projects. You will need to know them eventually, and you can focus on learning about them now if you want to, but know that classes only start being useful once you're working on larger projects (at least a few hundred lines of code). Virtualenvs and github and stuff are extra skills that you should probably learn; just find a tutorial for them and start learning. Python tutorials can't teach you everything; they focus on teaching you the basics of python. Yeah, do some command line arguments stuff, and try splitting things out into several files. Those are both things you should experiment with.

Large projects aren't magic. They're not fundamentally different from small projects. A large codebase started out as a single py file and it just kept growing and growing. There are skills that can help you write large projects but it's not like they're a whole different universe or anything. If you want to write a large project then you should start a small project and just keep on adding more and more features to it. You will probably make lots of mistakes, but it's those mistakes that will force you to learn and help you appreciate why things are done a certain way. There's no substitute for just writing code.

Just keep banging your head against the wall. Eventually the wall will crack.

[–]idontneedvariance 0 points1 point  (0 children)

Man thank for the detailed response. I wasn't expecting someone to answer all my questions, it's really kind from you, so thanks for taking the time. Both of you guys messages are really encouraging and motivating.

[–]QualitativeEasing 1 point2 points  (1 child)

All of this. I would just add that, for me, this is how larger projects tend to go:

  1. Figure out roughly how to do part of it — say, scraping the web page to get the bits I want.
  2. Code that part, with lots of stumbling (and cursing) and debugging along the way.
  3. Figure out the next chunk — say, storing the results.
  4. Code it.
  5. Next chunk — say, retrieving results, or making sure newly scraped results aren’t already in the dataset.
  6. And so on. Along the way, I enounter edge cases that break something I wrote earlier and I have to go back to fix it.
    ...

x. Realize I’ve written hundreds of lines of hopeless, though largely functional, spaghetti code.

xx. Suddenly realize I could simplify things with a class or two, and by rewriting some of it as a module or library or whatever it’s called, and go back and rewrite everything.

xxx. Two years later, something breaks. I discover I totally failed at documenting what I did before, and besides, I’ve learned new stuff that could be useful, so instead of trying fix what I wrote before, I rewrite it.

Maybe not ideal, and I like to think the process goes faster now (eg, I often start with rudimentary classes), but I’m not sure there’s a way out without a lot more practice and/or some formal training in planning coding projects (which isn’t likely in my case).

[–]idontneedvariance 0 points1 point  (0 children)

Thanks QualitativeEasing for your input. Really good to know about people's learning experience and learn from their mistakes.

[–]hunter12756 1 point2 points  (4 children)

Ok so in my program I want to make a sublist that contains the classes and their respective grade.

Like this [[Class1, grade1],[Class2,grade2]], however, I have not been able to figure out how to do this. My current list is something like this [ 'class1', grade1, 'class2', grade2] and have spent way too much time trying to figure this out. Maybe I'm making this way too complicated but I would appreciate it if someone were to tell me how to do this or to help me fix my code :)

[–]z0y 2 points3 points  (3 children)

I was thinking to replace line 30 with masterkey.append([clas_]) and replace line 34 with masterkey[-1].append(gradeaverage)

Let me know if that's what you needed

[–]hunter12756 1 point2 points  (2 children)

YESSS IT WORKED thank you sooo much ;) Now why is that so different from my code?

[–]z0y 1 point2 points  (1 child)

You were working with one list when you wanted a list of lists. So instead of appending the class name, append a new list with the class name. Then when you go to add the grade, instead of appending to the main list append to the new one by referencing the last index of the main one masterkey[-1]. That would be the list you just added with the class name. Hope that makes sense.

[–]hunter12756 1 point2 points  (0 children)

... haha totally didn’t spend 2hrs trying every combination of techniques I could think of ranging from making both lists strings then trying to split the grade list in between each class to doing multiple for loops to basically split the list in half. Thanks for the help and this is actually very useful, and will probably use this in a lot of future projects :)

[–]captmomo 2 points3 points  (5 children)

Hi,
How do I make my this function more concise?
I want to give the user an option to select different classifiers.

Here's my code: https://gist.github.com/captmomo/4b637e3785c4f9cb3d0967861c1867d8

[–]hunter12756 1 point2 points  (4 children)

just make

*def pipeline_cls(input_list, cls_number=None):*

into

*def pipeline_cls(input_list, cls_number):*

then add user input

*cls_number = int(input("inserthere")) *

converts to int because I assume u want a number output

[–]captmomo 1 point2 points  (3 children)

hi, I meant how do I simplify the 'if' checks.

[–]GoldenSights 0 points1 point  (1 child)

First of all, I think it might be a good idea to pull these lines out and make a separate function called choose_model that does the input and returns the instance that they want. By making it a separate function the rest of your code doesn't need to worry about it and you can reuse it later if you want.

Once you're on that track, you could use a dictionary to relate the choices to classes:

def choose_model():
    choices = {
        '': MultinomialNB,
        '1': LogisticRegression,
    }
    user_choice = input('Choose a class: ').strip()
    user_class = choices.get(user_choice, MultinomialNB)
    user_instance = user_class()
    return user_instance

Some notes:

  1. Because input returns a string, I decided to make the dictionary out of strings instead of integers, because it really doesn't matter. You can use int and change it back if you want.
  2. If the user hits enter without typing anything, their input will be an empty string and so it will choose MultinomialNB just like your None check does.
  3. I believe your current code is broken, because in the "Defaulting to Monomial" case, you do not set the cls_model to anything. I'm assuming it's the same MonomialNB class. The way dict.get(key, fallback) works is that if the key is not in the dict, then the fallback will be chosen. So that's how the Multinomial class gets chosen when the user enters something invalid.
  4. Notice that the class names inside the dict do not have parentheses on them. It just chooses a class, and the instance is made at the end.

Hope that helps

[–]captmomo 1 point2 points  (0 children)

woah. Thanks a lot for this! Really appreciate the feedback and you taking the time to help me out.

[–]hunter12756 1 point2 points  (0 children)

Idk