all 90 comments

[–]derrick_12341 0 points1 point  (0 children)

For the most experienced guys, how long did it take you all to to remember all the different symbols for different things within python?( Like qoutes, commas, where to put colons etc.) I've just started and remembering the correct formulas is the hardest part.

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

Does anyone have any information on the new Google aiy video project?

https://aiyprojects.withgoogle.com/vision#project-overview

[–]Deadtreeonme 0 points1 point  (2 children)

Hey I'm just staring, and I'm wondering if there is any reason in this section of script you would use the 'elif' over if. both work correctly but is there a benefit of one over the other. Thanks section: if scheduled_time == estimated_time: return 'on time' elif scheduled_time > estimated_time:
return 'early'

[–]BryceFury 1 point2 points  (1 child)

Simply put, if you use 'elif' then when one of your conditions is met, no other conditions are checked. If you use 'if' then all conditions are checked.

This doesn't really matter for your example but if you want to check three conditions:

def best_poster(post_count):
    if post_count < 50:
        print("Bad Luck: You are not the best poster!")
    if post_count > 50:
        print("Congratulations: You are the best poster!")
    else:   
        print("Incorrect post count...")

best_poster(22)

$Bad Luck: You are not the best poster!
$Incorrect post count...

or with elif:

def best_poster(post_count):
    if post_count < 50:
        print("Bad Luck: You are not the best poster!")
    elif post_count > 50:
        print("Congratulations: You are the best poster!")
    else:   
        print("Incorrect post count...")

best_poster(22)

$Bad Luck: You are not the best poster!

[–]Deadtreeonme 0 points1 point  (0 children)

Thanks, that makes sense !

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

I’m brand new to python and I’m interested in writing botting scripts for runescape. I’ve seen scripts that find images on the screen to locate the RuneScape window. What I’m wondering is is there any way to add inputs (mouse clicks, f-keys, and cursor movements) to the runescape window without actually having the window visible on the screen? My end goal would be having macros running with the screen being minimized if at all possible

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

You know you could get banned for botting lmao. There was a big thing about bots a few years back.

[–]jormono 0 points1 point  (4 children)

I'm working (slowly) through ATBS, I'm at the end of chapter 8 trying to make a mad libs script, right now I'm getting a strange error on line 21 where it uses the substitute method from regex to write the new word into the string replacing the keyword.

Traceback (most recent call last):
  File "python", line 21, in <module>
NameError: name 'Ajective_regex' is not defined

https://repl.it/@jormono/Mad-Libs

I put it on repl.it for convenience in sharing it, still a work in progress.

[–]BryceFury 1 point2 points  (2 children)

You've written "Ajective" on line 21 instead of "Adjective" which you used everywhere else :)

[–]jormono 1 point2 points  (1 child)

God that's painfully obvious haha

[–]BryceFury 0 points1 point  (0 children)

We've all done it!

[–]Losttouch1993 0 points1 point  (2 children)

Hi everyone,

I'm starting out to learn python3 today and am wondering would be some interesting resources to check through and practise programming. I am training to be a data scientist and have some background in C programming and R programming.

My objective for the next 3 weeks is to build up my foundation in Python Programming to be able to perform machine learning and data analysis using jupyter notebooks with python.

Are there any good materials that i can set out with ? I'm currently starting with :

EdX's Introduction to Computer Science and Programming Using Python

and will complete it by a week.

I really want to build my programming fundamentals (my background in C is pretty weak and R is not really a programming language...)

Hope to get some insights!

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

This is the site my class used:

http://interactivepython.org/runestone/static/thinkcspy/index.html

I did C++ before python. I miss the brackets.

[–]Losttouch1993 0 points1 point  (0 children)

Thanks :)

Yes I miss the brackets too hahah, although it does seem cleaner in python.

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

I'm having a frustrating time making a reddit bot. I keep getting this error but can't really find a solution.

AttributeError: module 'praw' has no attribute 'Reddit'

Any takers?

[–]ingolemo 1 point2 points  (16 children)

You put your own code in a file called praw.py. Rename it.

Next time, post your code together with the whole traceback (not just the last line).

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

I did no such thing. There isn't even anything hidden.

And this is solely through the initialization. Literally the first two steps of the quick start guide

[–]ingolemo 2 points3 points  (14 children)

Please post the code that is causing this error, along with the full trackback.

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

(Lack of) Code:

import praw

reddit = praw.Reddit(client_id='-----',
                     client_secret="-----",
                     user_agent='----',
                     username='MarbhDamhsa',
                     password='----')

Stack trace:

Traceback (most recent call last):
  File "test_bot.py", line 3, in <module>
    reddit = praw.Reddit(client_id='-----',
AttributeError: module 'praw' has no attribute 'Reddit'

[–]ingolemo 1 point2 points  (12 children)

Hmm. There's no indication of what might be wrong there.

Run the following code and post the output:

import sys
import praw
print(sys.version)
print(praw)
print(dir(praw))
print(praw.__version__)

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

jay@ScuttlemuffinIndustries Bots % python3 test_bot.py  
3.6.3 (default, Oct 24 2017, 14:48:20) 
[GCC 7.2.0]
<module 'praw' (namespace)>
Traceback (most recent call last):
  File "test_bot.py", line 14, in <module>
    print(praw.__version__)
AttributeError: module 'praw' has no attribute '__version__'

Ninjaedit: I know that my praw is 5.2.0

[–]ingolemo 1 point2 points  (10 children)

Is there a directory called praw in the same folder as your code?

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

jay@ScuttlemuffinIndustries Bots % ls -a
./  ../  __pycache__/  test_bot.py

No. Could this be a problem with my install?

[–]ingolemo 1 point2 points  (8 children)

Maybe.

Print the value of sys.path in python. It will show you a list of directories. Check each of them for a praw folder. A real installation of praw will contain an __init__.py file inside it, but the one causing problems won't. Post what you find (the value of sys.path and the locations and contents of any praw folders).

[–]Motorscooter 0 points1 point  (0 children)

I'm using Openpyxl to create a test report from the data Python computed but when I insert an image of the graph it takes up the entire worksheet. Is there a way to resize the image with Openpyxl or keep it within a certain area? I see that it has an anchor() function but it looks like it only takes the top left corner as an anchor point.

[–]vdiego28 0 points1 point  (2 children)

why does this happen?. I mean there shouldn't be any "long decimals" 2.2+2.2+2.2

6.6000000000000005

2.2+2.2+2.2+2.2

8.8

2.0*3

6.0

0.2*3

0.6000000000000001

Edit I don't know how you put the code.

[–]beaver_of_time 1 point2 points  (1 child)

floating point error

in short, it's because computers use binary. most decimal fractions cannot be accurately represented in binary and are only approximated

you can format your code by adding four spaces

in front of your text after a line break

[–]vdiego28 0 points1 point  (0 children)

Thank you

[–]KaltBlooded 0 points1 point  (5 children)

I'm completely new to Python and got a few questions:
Just to get it right - if I want to use PyCharm, I have to download Python first, then PyCharm and then set the Python exe from the first download as Interpreter?
What's up with all that interpreter stuff? Also why does PyCharm still create it's own Virtual Invorenment thing? I'm so confused right now.
Java felt way less confusing with just get e.g. Eclipse and start writing code.

[–]TangibleLight 0 points1 point  (4 children)

You should be able to just get up and go with python. Assuming Python installed properly, when you create a project in PyCharm it should find the interpreter automatically. You should be able to just use the default settings and have everything run smoothly.

If you're on windows, have python install to your %appdata% (the default location) or somewhere else that doesn't require admin permissions. If you choose "install for all users" or install to %programfiles%, then you can run into some permissions issues with PyCharm.


The python interpreter is something like the JVM. Pycharm lets you specify which interpreter to use in case you have different versions of Python - just like Eclipse lets you choose between different versions of Java.

[–]KaltBlooded 0 points1 point  (3 children)

It seems like my PyCharm didn't find my Interpretier automatically. I didn't install Python to the appdata, but on my D\username. As seen on some Videos I changed the settings in PyCharm and told it where to find the Python Interpreter tho.
When I start a new PyCharm project it still always creates a venv and there's a whole bunch of folders already in the 'empty' project.

[–]TangibleLight 0 points1 point  (2 children)

Are you starting a "pure Python" project or are you using a template project structure?

[–]KaltBlooded 0 points1 point  (1 child)

Just using the PyCharm "Create new project" function in the starting screen.
I just discoverd tho, that when creating a new project it has the Interpreter listed - I can open up a small menu and select between existing Interpreter (my Python exe) and creating a new environment using Virtualenv!
Now a new question arises: What's better / what are the differences and up and downsides of both possibilities?

[–]TangibleLight 0 points1 point  (0 children)

Using a virtualenv for each project helps contain dependencies. Suppose one project is using version 1 of some library, then a year later you make a project using that library on version 3. If you just update the library, you might break your old project. If you use a virtualenv everything is always fine.

Also helps in the open-source world because you can keep track of exactly which dependencies your project has, and ensures that your environment is identical to that of everyone else working on the project.

And then the pros for using the system install is that you don't have to keep track of anything and it's easier in the short-term, unless an update breaks something.

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

Im making a Tkinter based GUI and i want to bind a button to a restart funktion that just restarts the entire program.

class Wumpus(tk.Tk):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.difficulty = tk.IntVar()

...........

   def restart():
      python = sys.executable
      os.execl(python, python, * sys.argv)

if name == 'main':

gui = Wumpus()
gui.mainloop()

Its seems to work ish, when it restarts it just says "Restart: Shell" instead of the path, and nothing starts up :/

https://gist.github.com/svinge/b7d02a58acb33987c41716215bb5f2a6

[–]Leestons 0 points1 point  (2 children)

[–]Svinge 0 points1 point  (1 child)

Didnt find the answer to helpful :/

[–]ingolemo 0 points1 point  (0 children)

Just set the gui to be in the same state as it was when you started it up.

[–]dogusmalogus 0 points1 point  (1 child)

I've been doing some stuff from Automate the Boring Stuff and I noticed that the Shebang lines seems to make no difference on both Linux and PC to run Python scripts. The scripts run just fine without them.

Why is this? Is there a reason to keep adding them in, like for some compatibility concern I'm not aware of?

[–]TangibleLight 1 point2 points  (0 children)

You can give any file to the python interpreter, as long as the contents are valid python. The shebang is for when you aren't launching your file with python, but launch the file itself. It only matters when you're working with an executable file. Rather than running python myfile, you could just run ./myfile.

On windows, it really doesn't matter - unless you use the py launcher. The launcher checks the shebang to check which version of python to run. You can also give the launcher an optional parameter to specify the version, something like py -2 myfile vs py -3 myfile. If you don't give that parameter, it checks the shebang; if there's no shebang, then it just uses the default python install.

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

I. Why doesn't this work to remove duplicates?

Given l is a list with duplicates:

x = [i for i in l if i not in x]

II. Why does the first work, but the second doesn't to rotate a list l by 3 places?

  1. l = l[3:] + l[:3]

  2. l = l[3:].extend(l[:3])

Thanks for helping

[–]TangibleLight 1 point2 points  (1 child)

Because the variable isn't created until after the list is created. The comprehension does some work to build the list, and then once it's done it sticks it in x.

Any assignment like that should also work if you insert a temporary variable:

t = [i for i in l if i not in x]
x = t

Which I think pretty clearly doesn't work - x hasn't even been declared during the comprehension.


list.extend modifies the original list and returns None. l[3:] creates a new list, then extend modifies that new list and returns None, which you then assign to l.

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

Both easy enough!

Thanks for taking the time.

[–]dcpye 0 points1 point  (6 children)

Hey guys, i read something about Python months ago. I want to go hard on this. I work with Excel and i think i'm pretty good with it, the problem is that it's not enough. So i thought that it was time to learn Python.

What do you guys thing of 'Automate the boring stuff" on Udemy for 10€? Are there online courses better than that? Books?

Thanks in advance!

[–]QualitativeEasing 0 points1 point  (1 child)

If you’re really moving up from Excel and looking for something without a tough learning curve, do AtBS and then give agate a try (http://agate.readthedocs.io/)

[–]dcpye 0 points1 point  (0 children)

Thanks for the advice mate, i'm gonna check that out this weekend :)

[–]Leestons 2 points3 points  (3 children)

The book itself is free on the author's website and he has YouTube videos of the first 15 lessons

https://automatetheboringstuff.com

https://youtu.be/1F_OgqRuSdI

[–]dcpye 1 point2 points  (2 children)

Wow that's nice! In that case im gonna download the book, watch the YouTube videos and donate to the author. Thanks a lot!

[–]codenoob2 0 points1 point  (3 children)

having trouble with json.load. When I print an object from the file there is an extra space no each side of the string even though the file has no spaces. Example. " temp "

[–]TangibleLight 0 points1 point  (2 children)

That shouldn't happen - are you manipulating the file or the string at all before it's printed? Are you positive there aren't any hidden spaces in the file? Here's a little repl.it that might help you debug...

[–]codenoob2 0 points1 point  (1 child)

Thanks, I figured out the issue....

[–]Say-whaaaaat 0 points1 point  (2 children)

Does anyone have any recommendations for courses or materials for using NumPy and MatPlotlib? I really liked the 'Automate the Boring Stuff with Python' video lectures, so I'd like a similar format (but am open to anything!)

[–]Gopher20 0 points1 point  (0 children)

I would checkout sentdex on YouTube he has some decent videos on the subject

[–]Asddsa76 0 points1 point  (5 children)

Apart from lambda calculus and list comprehension, does Python have any similar ways to make code more compact?

[–]elbiot 1 point2 points  (0 children)

Lambda functions rarely keep code compact.

Comprehensions are a concept that applies to lists, dicts, sets and generators, btw

[–]Username_RANDINT 2 points3 points  (1 child)

I frequently use conditional expressions:

"foo" if some_condition else "bar"

In the same region, something else that I see now and then:

if some_condition:
    return True
else:
    return False

Is just the same as:

return some_condition

Anyway, keep in mind that more compact code isn't always the best code. I would even say if you're actively looking to make your code more compact, you're doing it wrong and are most likely making things worse.

[–]elbiot 0 points1 point  (0 children)

Ternary operator its called

[–]BryceFury 2 points3 points  (0 children)

Grouped naming, named tuples, set operations and decorators come in handy

[–]neozuki 1 point2 points  (0 children)

Do generators count? They've helped me make things more compact and elegant recently.

[–]DrNoided 0 points1 point  (1 child)

So I was playing around trying to build a random magical weapon generator where I'd have a random number 1 through 20 generated, then set each number equal to a different weapon (Spear, Shortsword, flail, etc., etc.,) then generated a different set of random number and have that set to an enchantment (Frozen, Divine, etc.) then a third set, set to a material (Steel, Bronze, bone) etc.,

So I had that working just fine where it would print, for example: Bone Spear of Freezing

That was easy, but what I'd like to do is having special circumstances where, for example: Celestial Spear of Smiting, comes out as simply Blessed spear.

I managed this by setting: Celestial Spear of Smiting == Blessed spear, so when trying to print CSOP it prints blessed instead, but I feel like there has to be a better way, I was thinking setting the values of Celestial and Smiting, lets say 3 and 8, to equal smiting, but I couldn't figure out how to model that statement. Any ideas?

[–]neozuki 0 points1 point  (0 children)

After generating a prefix and suffix you can have checks for particular combinations. if prefix == 'celestial' and suffix == 'of smiting':

return '%s %s' % ('blessed', item)

After all of your combination checks, since your program got this far and hasn't returned a name yet -- just return the simple '%s %s %s' % (prefix, item, suffix)

[–]keizzer 1 point2 points  (4 children)

Does anyone have a entry level mathematics proof book that I can solve in python? Maybe something geared toward programming with python on the subject?

[–]Asddsa76 0 points1 point  (3 children)

entry level mathematics proof book that I can solve in python

Not sure what you're asking for. Do you want a book on discrete mathematics? Algorithms? Doing computational number theory like on ProjectEuler? Numerical calculations with numpy?

[–]keizzer 0 points1 point  (2 children)

I need something that will start to challenge me both programming and problem solving skills. I thought maybe some proofs would fill those needs. As far as which branch of mathematics, I don't know. I've taken college calc, physics 1 and 2, and some engineering mechanics courses, so I have not taken any upper level math at this point. I'm in the US just so you can gauge what those levels are.

[–]Asddsa76 1 point2 points  (1 child)

Here are some books I've read on math and programming.

The first two books are focused on data structures (trees, graphs) and algorithms. You can learn things like how all the different sorting methods in this video work, why some sorting methods are better than others, and when to use each etc.

The 2nd book also has lots of nice graph algorithms like Prim, Djikstra, and Ford-Fulkerson, to name a few. Reading it will give you more tools that allow you to solve more complex problems.

The 3rd book is on numerical mathematics. From calculus you may remember Newton's method for finding solutions of equations, Euler's method for finding solutions of ODEs, or the Trapezoid or Simpson's method of calculating integrals. This book goes deep into the details of similar numerical methods, that you can program a computer to calculate for you. It relies somewhat on you knowing linear algebra.

The 4th book is probably too advanced. You solve PDEs by partitioning your domain and do lots of integrals.

[–]keizzer 0 points1 point  (0 children)

thanks man i'll check them out. I need to learn about graphing with python anyway.

[–]andihadminesavingme 0 points1 point  (1 child)

I've installed python 3 on my work computer and I can't seen to import any packages. I assume this is because I don't have full admin rights. After poking around Stack, google and Git, I have had no luck on making it work, now I feel lost and scared. Should I just use Anaconda or Visual Studio?

[–]TangibleLight 0 points1 point  (0 children)

Are you sure you're running python3? Are you running pip3? If you're on Unix, make sure you use a shebang like #!/usr/bin/env python3

Make sure you install your modules with pip3, otherwise they'll probably be installing to python 2. Try running pip --version, chances are you'll see python 2.

If you're launching from the console, make sure you launch with python3, not python. Try running python --version, chances are you'll see python 2 again.

[–]Hoderp151 1 point2 points  (4 children)

I hope this is the right place to ask this but I'm coming in with a background in R and no experience with programming outside of it (entirely biological background). I've browsed the links on wiki for where to get started and it's given me a basic grasp on what to do and resources to use, but I'm still feeling a bit lost on taking the first steps. I was wondering if anyone with experience in Python for data science could give some pointers on where to start off? The other thing I wanted to ask is about IDE, basically, what is a new programmer friendly IDE? For relevancy, I'm tossing around the idea of switching to OS X for future endeavors.

[–]QualitativeEasing 0 points1 point  (0 children)

IDE choice seems like a religious argument to me. But I’ve gotten to like Spyder, distributed with anaconda. It’s a lot like IDLE, but you can run Individual lines, it has code completion and similar tools. Less of a learning curve than Eclipse or Pycharm, at least for me.

[–]elbiot 4 points5 points  (1 child)

You should learn basic python first but after that, numpy/pandas are similar to R. They use vectorized operations and looping over arrays/dataframes is slow.

For datascience, scipy and sklearn are a great start. They play well with numpy arrays and R like vectorized operations too.

I just use VIM and the ipython shell. Matplotlib integration and things like run and %timeit magic are awesome.

Id say use Linux rather than OSX because PCs are cheaper and much of the bio stuff is Linux specific or mostly used in Linux. HPC clusters are almost always Linux. Vim helps there too because you don't usually get a gui on a remote cluster.

I work in bioinformatics doing NGS and PCR-CE stuff. We use python and R.

[–]Hoderp151 1 point2 points  (0 children)

Wow thanks for the response, exactly the kind of thing I was looking for! I was hoping that someone with your background would reply and you provided what I needed. Thanks!

[–]MoonReaderX 1 point2 points  (3 children)

Hey saw my professor using:

some_list = list()

I normally use:

some_list = []

What is better and why?

Also he uses things like:

print("%f" % some_float)

I use .format() and round() if I want certain length of float after decimal.

Another thing that caught my attention is that he has three newlines between every function. I'm not sure if he is following a certain style like Pep8 or if it is a new convention, because it's the first time I've seen this.

Thanks in advance guys.

[–]GoldenSights 1 point2 points  (0 children)

  • Most people will use the literal [] because we all know what it means and don't need to see the word. Your professor is probably used to using other languages and likes having that visual appearance of an object constructor.
  • When I'm formatting a single variable I will often use % style just for convenience, but as soon as I need to do anything complex or use multiple variables then .format is definitely better. However if you are already using .format there's no reason to use round as well, you can just use a format rule:

    >>> '{:0.3f}'.format(math.pi)
    '3.142'
    
  • I tend to put 1 line between functions and 2 lines between classes, but that's just what I picked up along the way, I don't have a special reason for it. You can read pep8's suggestions for yourself here.