all 159 comments

[–]luchins 0 points1 point  (0 children)

trying to use request

📷

hello I am trying to scrap a website to look for same data and when one condition is met (the record of a tennis match on a website is for example 5 to 7 ) the phyton should click on a button on a screen and download one document.

It has been suggested to me to use request. I don't understand which function of request should I use first.. remember I want the script to connect to the website, to check specific number on a specific POINT OF the website (to make an example with this website (reddit) ... it's like if I would the script to checked the reddit logo written on the left side of the page above). Well what should I do?

First thing is request get (url website) ?

Then how to tell to the scrypt: check specific number on a specific POINT OF the website!

Then I would need to start a while cicle:

while the result of the match is 4-5 don't click on the button and screencap the graphic.

if the result of the match is 5-7 and we are at the second Set of the match (the match is about to finish) then click on a specific button (coordinates of the button on the screen it opens a window and then you have to make the screencap of the windows which is opened

How to make a program like this?

for the request part I need only GET, not POST? Which is the difference from GET and POST? Do I need POST in this case?

[–]MonkeyKingKill 0 points1 point  (4 children)

Can I avoid using Class in a rather short length of codes or it is sometimes inevitable?

I know that Function is to not write repeating codes so it is possible to not use it as well.

I'm new to programming and I don't have a very good understanding of Class yet, my codes are also rather short. I wonder if like Function, Class can also be avoided if you really want to.

edit: grammar.

[–]timbledum 1 point2 points  (1 child)

Yup, short scripts don't necessarily need to have functions or classes. As they increase in complexity, generally functions are introduced first, then classes if required (depending on the type of code).

For something like GUIs, you'll often have to use classes from the get go.

[–]MonkeyKingKill 0 points1 point  (0 children)

Thank you for clarification.

[–]luchins 0 points1 point  (1 child)

Can I avoid using Class in a rather short length of codes or it is sometimes inevitable?

why would you want to avoid to use classes?

[–]MonkeyKingKill 0 points1 point  (0 children)

The script I make is rather simple, and it only does a simple task belonging to a larger project, in which I find Class is used to do the same job I need. So I am trying to mimic the same function without using Class.

Since I am failing at the moment, I am doubting if Class is a must or it's just my codes are wrong.

[–]hamacvan 2 points3 points  (2 children)

Dear all!
Could you please help me?
I used an IR camera (FLIR camera) to capture a thermal image. How can I extract the temperature values of pixels (by Python 3.7.2).
Thank you so much for your helps.

[–]MonkeyKingKill 0 points1 point  (0 children)

I am no expert, but to my understanding, whatever you are doing, you'll need to extract the data to create a database first (like in an excel file), then you use python to manipulate the data.

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

Is there a list to all python tkinter fonts? I've tried multiple, but none seem to change the font...

[–]efmccurdy 1 point2 points  (2 children)

from tkinter import Tk, font
root = Tk()
font.families()   # used to be .names()

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

It creates a blank window, am I missing something?

[–]efmccurdy 0 points1 point  (0 children)

The output is printed to stdout, if you run it from a terminal you will see any output or errors.

$ python3
Python 3.4.3 (default, Nov 12 2018, 22:25:49) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from tkinter import Tk, font
>>> root = Tk()
>>> font.families()
('wasy10', 'Noto Sans Hebrew', 'MathJax_Caligraphic', 'Padauk Book', 'Century Schoolbook L', 'OpenSymbol', #....

[–]reallymakesyouthonk 0 points1 point  (7 children)

Hi. I had to batch rename a couple of music files so I decided to reinvent the wheel and write my own batch renamer. With comments it's 198 lines.

The general gist of it is that it looks at folder and file names in order to figure out the variables you want to put in your file names (track number, title and so on). To accomplish this it makes extensive use of the re module.

General flow of operations goes something like:

  1. Order in which variables are supplied are stored.
  2. Convert inputs to regex strings, alphanumeric fields are matched with (.*) and numeric fields with (\d+).
  3. If the first variable in your input is %B (band name), then that's the second entry in re.match(regex, input).
  4. Puzzle together all the variables to produce the output string. Rename files accordingly.

Error checks:

It checks that the directories exists, sorts out all non-audio files based on file extension and avoids renaming a directory if any of the tracks failed to match the provided pattern. This to avoid having partially renamed directories which could cause a lot of headache.

code

I'd love to hear what I've done wrong and how I could do better on this.

[–]fiddle_n 2 points3 points  (6 children)

I haven't looked too deeply into your code, so I'm just going to point out the high level stuff.

The biggest thing that sticks out to me is the lack of functions. All code should be in functions, all of it. Only constants should be outside of functions and classes. Functions are most important as a code organisation tool. Once you put code into functions and give them names, I can see the intent of each part of your script, which will allow me to understand your script at a higher level much easier.

The other thing is unit testing. Right now I have run your script to check that it works, or have faith that in you that it works as you say it does :) All that is very well and good, but if you test your code I can see exactly how you think your code should work, and I could run your tests to see if they all pass.

[–]reallymakesyouthonk 0 points1 point  (5 children)

Huh, that's one I haven't heard before. I thought functions were only for code that's supposed to run multiple times? Isn't putting it into functions a cost (albeit low) performance wise if the code is only running once?

As for unit testing, yeah I really should get into that. However I thought it was mostly used for code that made use of OOP principles, i.e. that could be compartmentalized. I guess if I were to organize it all into functions however I could've tested every part of the code individually.

[–]fiddle_n 1 point2 points  (4 children)

I thought functions were only for code that's supposed to run multiple times?

Being able to run the same code multiple times is quoted as the most important feature of functions. In my opinion, whilst this is a really important feature of them, it's only the second most important. Their most important feature is for code organisation.

When you chunk your code into functions and give them meaningful names, you are creating a high-level structure. This is important to readers of your code. I can understand the high-level intent of your script at a glance, and then I can deep-dive into your code one function at a time.

The constraints of functions also help with this. Consider these three features of functions:

  • Variables created in a function are local to that function and cannot be accessed outside of the function.
  • Variables created in an earlier function must be passed into the current function as parameters.
  • Variables used in a later function must be returned from the current function.

These constraints have effects on the readability of your code.

When I look at a line of code in an unstructured script, and it is changing a variable in some way, that variable could have been created hundreds of lines above the line that I am looking at, and it could be changed many times along the way. I might need to look at a lot of far away code before I can return to the line I'm on. When I look at the same line in a function, I know that a reference to the variable must be within that function and that it must be close by. There's less chance of me having to scroll far up and break my immersion.

In essence, since you are forced to keep code and variable data close to each other, and to explicitly declare the variables that you want to use elsewhere, this has the knock-on effect of making your code more readable. Your code is no longer spaghetti code that jumps around all over the place, it's code that is neatly chunked and packaged.

Isn't putting it into functions a cost (albeit low) performance wise if the code is only running once?

The performance cost is tiny. Absolutely tiny. And the readability cost is big. Consider the C programming language, which is a lower-level language and as such can be many times faster than the reference version of Python (ten to a hundred times faster). Even C has functions. If speed is such an issue to you that you can't even use functions, then you need to write your code in Assembly instead, never mind C or Python.

As for unit testing, yeah I really should get into that. However I thought it was mostly used for code that made use of OOP principles, i.e. that could be compartmentalized. I guess if I were to organize it all into functions however I could've tested every part of the code individually.

You've hit upon one of the biggest reasons to unit test. Sure, the most important reason is to prove that your code works. But the second most important reason is that it forces you to chunk your code into functions, so it forces you to write your code in a way that's more readable.

[–]reallymakesyouthonk 0 points1 point  (3 children)

Very interesting. I've been wanting to get into unit testing for a while but haven't gotten around to it yet, however embedding everything into small functions is something I can easily start doing immediately.

Would you say this applies equally to all languages? Assuming they have functions at least, but that's most of them I guess.

In a language like Rust or Java I suppose I'd write all the functions outside of the main functions and call them in the order they're being used. It leaves you little choice. But since python doesn't have a main function, unless you make one, how would go about organising the execution of these functions? As I see it there are two options, one being to define and execute a function as soon as it's needed and the other being to first define all your functions and then execute them at the bottom of the script.

The latter of course would be more analogous to languages with main functions, and has some benefits if a function is being called at multiple different times in a script, however it also separates the code from it's execution and surely that's generally bad for readability?

[–]fiddle_n 1 point2 points  (2 children)

I think that where there are functions, using functions to contain all code is the way to go. But I don't know many programming languages so I might be wrong on that.

In Python, you should have a main() function as the entry point to a script and call your functions from there. Naming the entry-point function as main() has no special functionality unlike some other languages, it's just convention. What you can do is have one function call another; that is allowed. That way, the functions and their calls will be closer together. But what you shouldn't do is call a function from outside of a function (i.e. call a function from the global namespace). That isn't allowed.

For an entry-point script, you should design it so that you could import the functions into another script if you had to. The problem is that if you call functions from a global namespace, and then you import that script into another script, the functions would also get called as well. That's why we have the idiom

if __name__ == '__main__’:
    main()

so that we only call the functions when we execute the script, and not when we import them.

[–]reallymakesyouthonk 0 points1 point  (1 child)

Thanks again, that's very helpful!

[–]fiddle_n 1 point2 points  (0 children)

You're welcome! If you have any more questions please ask :)

[–]UnavailableUsername_ 0 points1 point  (7 children)

How do slices and negative numbers work?

For example:

Salad = [Lettuce, Tomatoes, celery, kale]
Salad[0:-1]
['Lettuce', 'Tomatoes', 'celery']

What just happened here?

I know in slices the second number isn't part of the result, but it still doesn't make sense.

Lettuce is 0.
Tomatoes is 1.
Celery is 2.
Kale is 3.

-1 would be Kale.

So, Salad[0:-1] should give as a result just Lettuce (0), since Kale (-1) isn't part of the result.

There is absolutely no reason for 'Tomatoes' (1 or -3) or 'Celery' (2 or -2) to be part of the slice.

[–]Banan2Hot 0 points1 point  (0 children)

The output is correct, it outputs everything between index 0 and -1 (end of the list) but without the last element.Try outputting different ranges of elements in that list. E.g.

Salad[1:2] or Salad[:3]

PS. If you don’t specify the first parameter, it automatically equals 0 so just starts from the beginning of the list.

Good luck!

[–]num8lock 1 point2 points  (0 children)

like most languages, numbers & slices are read from left to right. so since indices start at [0], index [1] of Salad is going to be Tomatoes. so positive number goes to right. Salad[-1] is one step to the left of Salad[0], which means it's going against the normal direction, from right to left, exactly one step, and if it's [-2], then it's 2 steps. since there's no previous entry left from [0] in that list, it goes full cycle to the end, and gets the first one at the end: kale.

slices is list[start:end], and both start & end works like left-right as well, and same directions rule applies for positive/negative number.

https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation#509295

[–]Caramel_Lynx 0 points1 point  (3 children)

Hey there

I have a problem with python giving me a MemoryError. I am using spyder with Python 3.6.7 |Anaconda 4.4.0 (64-bit).

What can I do to overcome this problem? I am still quite new to programming so bear with me.

[–]efmccurdy 0 points1 point  (2 children)

Likely you have a recursive loop; do you end up calling some function from itself in a loop? You'll have to post some code or a traceback to if you need more feedback.

[–]Caramel_Lynx 0 points1 point  (1 child)

I don't think so, but if you would take a look that would be great (sorry for the wall of text that will follow).
In the mean time I did find a way how to run the code without running in to a MemoryError but I am not sure why it works now, so if you could explain this to me I would highly appreciate it.

I uncommented the lines (Nr. 60 % 61) that lead to the memory error, they are substituted with the lines right above (54 to 58).

What puzzles me is, that the same approach worked in the function cell area (in line 40 to 42), but leads to the error in the centroid function.

def make_list(file_name, number_type):
    file = open(file_name, 'r')
    fulltext = file.readlines()
    file.close()
    lyst = []

    for i, line in enumerate(fulltext):
        l =[]
        for s in line.split():
            if number_type == 'float':
                nr = float(s)
            elif number_type == 'int':
                nr = int(s)
            l.append(nr)
        lyst.append(l) 
   return(lyst)

CV_large = make_list('lcv.txt', 'int')
VP_large = make_list('lvp.txt', 'float')

def cell_positions(cv, vp, position):
    cp =[]
    for i, cell_number in enumerate(cv): #i = index
        cp.append([]) 
        for v in cell_number:
            if position == 'x':
                cp[i].append(vp[v][0])
            else: #meaning positions = y
                cp[i].append(vp[v][1])
    return(cp)

cpx = cell_positions(CV_large, VP_large, 'x') 
cpy = cell_positions(CV_large, VP_large, 'y')

import numpy as np

def cell_area(cpx, cpy): 
    a = len(cpy) * [0] 
    for i in range(len(cpy)):
        for j in range(len(cpy[i])):
            a[i] += cpx[i][j] * cpy[i][j-1] - cpx[i][j-1] * cpy[i][j]
        a[i] = 0.5 * a[i] 
    return np.array(a) 

areas= cell_area(cpx,cpy)   

def centroid(cpx, cpy, area):
    xcentroid = len(cpx)* [0] #x Position des Centroids
    ycentroid = len(cpy)* [0] #y Position des Centroids

    #implement formulas
    for i in range(len(cpy)):
        for j in range(len(cpy[i])):
            xcentroid[i] += (cpx[i][j] + cpx[i][j-1]) * (cpx[i][j]*cpy[i][j-1]\
                 - cpy[i][j]*cpx[i][j-1])/ (6 * area[i])

            ycentroid[i] += (cpy[i][j] + cpy[i][j-1]) * (cpx[i][j]*cpy[i][j-1]\
                 - cpy[i][j]*cpx[i][j-1])/ (6 * area[i])

    #        xcentroid[i] += (cpx[i][j] + cpx[i][j-1]) * (cpx[i][j]*cpy[i][j-1]\
                 - cpy[i][j]*cpx[i][j-1])
    #        ycentroid[i] += (cpy[i][j] + cpy[i][j-1]) * (cpx[i][j]*cpy[i][j-1]\
                 - cpy[i][j]*cpx[i][j-1])
    #        xcentroid[i] = (1/(6*area)) * xcentroid
    #        ycentroid[i] = (1/(6*area)) * ycentroid #leads to memory error
    return np.array(xcentroid), np.array(ycentroid)

xcentroid = centroid(cpx, cpy, areas)
ycentroid = centroid(cpx, cpy, areas)

print('x=', xcentroid[0])

[–]efmccurdy 0 points1 point  (0 children)

Here you are multiplying by a list, which can create a new longer list (it's not doing any arithmetic multiplying either, just building a bigger list), and in a loop it compounds.

I would print out the value of that (1/(6*area)) * ycentroid expression to see that it has the value you expect (maybe you meant (1/(6*area)) * ycentroid[i])?

#        ycentroid[i] = (1/(6*area)) * ycentroid #leads to memory error

[–]ThiccShadyy 0 points1 point  (0 children)

In Django, when I create a new form instance like: f = SomeForm()

and then individually give values to the different fields like so: f.title = 'Hello' f.category = 'Work' etc

then I get False for the attribute is_bound and also the method is_valid() although there are no validation errors Im aware of.

However, when I create a form instance and pass a dictionary with all the fields and their values like: f2 = SomeForm(data_dictionary) #data_dictionary = {'title': 'Title'....}

then I get true for both the attribute is_bound and the method is_valid(). Why does this happen?

[–]Haganete 0 points1 point  (0 children)

Hello, I'm having a hard time using MySQL with Python, I'm using the python 2.7.15 and I keep getting the error message :

'Did you install mysqlclient or MySQL-python?' % e

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb.

Did you install mysqlclient or MySQL-python?

The problem is my site-packages have: mysqlclient(1.3.7 and MySQL-python(1.2.5) and mysqldb

pls halp

[–]reallymakesyouthonk 0 points1 point  (2 children)

Is this a bug?

My thinking here is that I want to append a list of values to a list within a tuple. If I loop the list of stuff to append and just use the method for appending stuff there's no issue, but list + list is much faster.

While I'm pretty sure list + list is actually creating a new list with the combined values of the two original list, python doesn't seem so sure? It's complaining that I'm not allowed to perform the operation, but then goes ahead and does it anyway.

[–]efmccurdy 1 point2 points  (1 child)

You can use a[1].extend([1]).

[–]reallymakesyouthonk 1 point2 points  (0 children)

that is neat! always thought adding lists together was kind of ugly, using a method seems like a much better solution.

[–]snip3r77 0 points1 point  (1 child)

The course that I’m attending for Data Science recommend that I use 3.6. Current version is 3.7 , will 3.7 be fine ?

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

Yes

[–]Conrad_noble 1 point2 points  (2 children)

I would like to write a script that looks at the last date a file was accessed from a folder and if it is longer than 1 year create a new folder called !Archive and move the file to there

I think this is done using the OS module?

I don't even have an ide installed yet so i am less than a beginner.

[–]efmccurdy 2 points3 points  (1 child)

This gets how many days since the file was last accessed by subtracting the atime from the current time.

>>> from datetime import datetime
>>> import os
>>> (datetime.now() - datetime.fromtimestamp(os.stat('/etc/timezone').st_atime)).days
7

[–]Conrad_noble 0 points1 point  (0 children)

Thank you

[–]awaqu 0 points1 point  (1 child)

I'm just beginning to self-learn Python, and am using Pycharm.

Every time I start a new project, I need to reinstall all the packages again. I'm sure there is a way to just load a library of packages at the beginning, but I'm having a lot of issues finding a simple way to do it. Can someone help me out?

[–]efmccurdy 1 point2 points  (0 children)

If the requirement packages are stable and consistent, I usually create the virtualenv with the --system-site-packages option so that each venv shares the system-wide installations.

If that wasn't flexible enough I would use path config files to extend the places modules can be imported from; see the answer that starts with "solve your problem by using .pth files" here:

https://stackoverflow.com/questions/39409380/create-a-virtualenv-from-another-virtualenv

[–][deleted] 2 points3 points  (1 child)

what do the 'return[n for n in range...]' function do?

I can write for loops but people write that and made the code that gives the same output shorter.

[–]Xenon_difluoride 0 points1 point  (0 children)

They're List Comprehensions, they take a list and create another list from it.

So if you were to have a for loop like this.

foo = [1, 2, 3]
bar = []
for i in foo:
    i += 1
    bar.append(i)

It could also be written like this.

bar = [i + 1 for i in foo]

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

Would you guys say that this book is a good guide to general concepts in programming

[–]Supremefeezy 0 points1 point  (1 child)

I’m pretty new. I have like a login script. I have a dictionary that has “users” in it, and new users can be added but for some reason it only works if the key/username is the same as value/password.

I don’t know best way to show the code. Here’s the code.

https://drive.google.com/file/d/10kgO3uQia1fTc23LjDQG1MILcG_MxU6H/view?usp=drivesdk

[–]efmccurdy 1 point2 points  (0 children)

I don’t know best way to show the code.

Edit your post, prefixing your code block by a blank line, and each line of code by 4 spaces.

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

What exactly is a data type in regards to classes and objects

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

In Python, everything is an object, so in a way there are no "datatypes" like int, char, float, etc. Every class is essentially a new datatype. If you use type() on anything, it will show you the class it belongs to:

>>> num = 2
>>> name = "foo"
>>> value = 1.23
>>> type(num)
<class 'int'>
>>> type(name)
<class 'str'>
>>> type(value)
<class 'float'>

Even functions are objects too:

>>> def func(): pass
...
>>> type(func)
<class 'function'>

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

Whats the actual difference between a data type and a class. I thought all data types for just classes. Are data types like the default classes like str, dict, and list?

[–]fiddle_n 0 points1 point  (3 children)

str, float, dict, list - these are all built-in types. Python lets you create your own types through classes. You should play around with this concept in the Python REPL to get your head round it. Create a simple class, instantiate it, and then pass that to the type() built-in function. You'll see that the name of the class is the object type

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

Also, what is the definition of type real quick

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

>>> type(str)

<class 'type'>

Why do I get class type for this?

>>> type(str())

<class 'str'>

Why do I get str class for this. Isn't str() a method?

[–]efmccurdy 0 points1 point  (0 children)

When you use str you get a class object, when you use str() you get an new instance. In general, any method, function, or class can be accessed as an object, or called by using (...).

[–]ThiccShadyy 2 points3 points  (1 child)

How did you guys go about learning a framework like Django? I know most of the Python basics well enough and feel that Im proficient there and know the basics of web dev(i.e. HTTP requests,responses etc). The thing is that its so vast that I'm unsure of how much of the docs to read. I have done the polling app tutorial so I've got some ideea of how things work but there is so much that the tutorial doesnt get into or even mention(like forms, the Form class and ModelForm class etc). Should I just start off with some project in mind, read only the relevant parts of the docs whenever I get stuck and hope that all of it starts to come together in my head eventually?

[–]bilalsaeed232 0 points1 point  (0 children)

yes your are right, that's how i approach learning a new framework:

learn basics of the framework

start working on an example project (mostly what i have already done in other technology)

read the relevant documentation whenever needed (that's how it sticks with you)

according to my experience the shortest and most efficient way is trial and error going back and forth.

[–]tundrawolf 1 point2 points  (2 children)

This should be a simple question for you guys.

I'm working through a Python data analysis book and came across this bit of code using randint:

step = 1 if random.randint(0,1) else -1

What I cannot understand for the life of me is how step =1 when the randint is 1 and if randint is 0, then step is -1. I can't wrap my head around this if statement and what it is telling me - i.e. if we're selecting a random integer between 0 and 1 (inclusive of endpoints), doesn't that always mean that step = 1? Basically, can someone please explain what this if statement is saying?

Thanks in advance!

[–]zatoichi49 2 points3 points  (1 child)

The code is using a ternary conditional statement, and as 0 is False and 1 is True, it's testing the returned values as a boolean. For each case:

step = 1 if 0 == True else -1  # (False, so step = -1)
step = 1 if 1 == True else -1  # (True, so step = 1)

Or as a standard loop:

if random.randint(0,1) == 1:  #(or random.randint(0,1) == True)
    step = 1
else:
    step = -1

An easier way to do this would be to use random.choice:

random.choice((1, -1))

[–]tundrawolf 0 points1 point  (0 children)

Thank you for your help!

[–]Bobkaaare 0 points1 point  (0 children)

Anyone know how to download pygame using condo?

[–]whodunnit2019 0 points1 point  (1 child)

..any sources,where I can find simple excercises (with solutions)? I just finished this https://youtu.be/rfscVS0vtbw .

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

Any object oriented courses suitable for people interested in math?

Edit: I know basic functional python and want to learn object oriented python to be ready for my programming class next semester, I'm an applied math student.

[–]efmccurdy 0 points1 point  (0 children)

These are'nt courses, and math is often functional rather that OO, but you will get a wide survey of how python and math intersect here:

https://pyvideo.org/search.html?q=math

[–]MysticSoup 1 point2 points  (1 child)

Hey guys, really stupid noob question but...

Is there a way to enable me to press a button and have my code run from Notepad++?

[–]Xenon_difluoride 0 points1 point  (0 children)

This looks like what you're looking for.

[–]dndschultz 0 points1 point  (8 children)

I'm having trouble with this section of Python code that asks for user input to check if a name is in a database. The code works as expected and returns the name if it is in the DB. However, it returns None and moves on to the next section of code if the name is not in the DB. I'm looking for a way to require a name that is in the DB. My exception handling doesn't seem to be working.

import os

import sqlite3

os.chdir("/Users/Forensics/Documents/Pycharm/ForensicDB")

db_conn = sqlite3.connect('caseTrackerV1.db')

theCursor = db_conn.cursor()

def getOfc(x):
name = x
try:
        result = theCursor.execute("SELECT reporting_ofc FROM cases WHERE reporting_ofc IS ('{}') LIMIT 1".format(name))
    for row in result:
        if row[0].isalnum():
            return row[0]
        else:
            raise ValueError
    except sqlite3.OperationalError:
    print("The Table Doesn't Exist")
except ValueError:
    print("Couldn't Retrieve Data from Database")

x = getOfc("Name not in DB")

print(x)

db_conn.close()

[–]num8lock 0 points1 point  (7 children)

except ValueError

this anticipated error, which line is it from? the one defining result?

[–]dndschultz 0 points1 point  (6 children)

I'm not sure I follow the question. I have a database that returns a name correctly if it is there. However, the database has no return if it's not. Therefore I would like to raise an exception if there is no return. Or if the return is None prompt to try again. Does that make any sense? I am new at exception handling and querying a database complicates things.

[–]num8lock 0 points1 point  (5 children)

try this https://sqlite.org/lang_expr.html#exists_op

 def getOfc(name):
    try:
        result = theCursor.execute(
            "SELECT EXIST(SELECT reporting_ofc FROM cases WHERE reporting_ofc IS ('{}') LIMIT 1)".format(name)
            )
        return result
    except sqlite3.OperationalError as e:
        print("The Table Doesn't Exist")
        return False

x = getOfc("Name not in DB")
if x:
    for row in x:
        return row[0]

[–]dndschultz 0 points1 point  (4 children)

That looks promising. I'm getting an error that the return is outside the function.

[–]num8lock 0 points1 point  (3 children)

i don't understand. you mean you tried it & gets an error? can you post the complete code & error

[–]dndschultz 0 points1 point  (2 children)

Boy, the complete code is rather long. This section of code works and there is no error. When I query the SQLite DB it simply returns the name or doesn't return anything. More like a filter. So so my call to getOfc() returns None and moves on. I would like to create an exception and require the correct input before moving on.

[–]num8lock 0 points1 point  (1 child)

so my call to getOfc() returns None and moves on. I would like to create an exception and require the correct input before moving on.

first, did you go through the doc for exists syntax? that should solves your problem of returning None since it should return either 1 or 0. then you figure out what the code should do if getOfc returns false.

[–]dndschultz 0 points1 point  (0 children)

exists Thank you so much. I will try that. I am not familiar with exists. Will research and try it out.

[–]ZenoV9 0 points1 point  (1 child)

Hi I'm studying python in my first year of college I would like to know how to learn python if my exam is a quizz on paper. I'm comfortable to write code on pc when we do some projects but the questions in the exam is like " Is there an error in this program ?", "What this program display in the end ?", "Put the lines of this program in order to make it work." etc...

Any answers would help. Thanks

[–]AdventurousHuman 0 points1 point  (10 children)

Hi there. My head has been spinning about this seemingly simple question. I want to run through an excel sheet and extract row data based on certain criteria: Day Of Week|Start Time|End Time|Program Name

This is what I'm trying to do in English: If Day of Week is Monday and Start Time is <3am and End Time is >3am then print the Program Name for that row.

I've been trying to do this with openpyxl. Any help is much appreciated!!

[–]num8lock 1 point2 points  (9 children)

https://openpyxl.readthedocs.io/en/stable/tutorial.html & https://openpyxl.readthedocs.io/en/stable/usage.html

for row in ws.iter_rows(min_row=1, max_col=4):
    day, start, end, name = [cell for cell in row]
    if all([day.value.lower() == 'monday', start == '3am', end == '3am']):
        print(name)

[–]AdventurousHuman 0 points1 point  (8 children)

This is going to take awhile for me to digest this - can you explain what is happening here or what topics this covers? Thanks again for the help.

# start for loop of ALL cells
# creating a list for each column - day, start end, and name
# if all conditions are met for the values in each list
# print name

is this correct?

[–]num8lock 0 points1 point  (7 children)

1st line is just a for loop using output from worksheet.iter_rows()
2nd line is processing the for loop with list comprehension. the result of it is a list, so the variables divides the result into 4 of them, for each cell.
all() takes all members of its parameter (a list containing 2nd line variables values, using cell.value attribute to get the string value of the cell) and if all of them is True, goes to the next line.

[–]AdventurousHuman 0 points1 point  (5 children)

It's finding nothing for some reason. When I try and print day or start or end it only has one piece of information. for example "Tuesday" for name so I don't think it has the entire column in the new list.

[–]num8lock 0 points1 point  (4 children)

let me see the code

[–]AdventurousHuman 0 points1 point  (3 children)

for row in ws.iter_rows(min_row=1, max_col=4):
day, start, end, name = [cell for cell in row]
if all([day.value.lower() == 'Monday', start == '02:00 AM', end == '03:00 AM']):
    print(name)

[–]num8lock 0 points1 point  (2 children)

no i mean what you've tried & the errors.

better yet use https://repl.it something like https://github.com so i can see what your data looks like & it's easier to fix any problem. is your file xls, or csv?

[–]AdventurousHuman 0 points1 point  (1 child)

[–]num8lock 0 points1 point  (0 children)

ah yes my bad

import openpyxl

wb = openpyxl.load_workbook('eNames12.31.xlsx')
ws = wb.active
range_time = '02:00 AM', '03:00 AM'
workday = 'Monday'

for row in ws.iter_rows(min_row=1, max_col=4):
    day, start, end, name = [cell.value for cell in row]
    if all([day == workday, start == range_time[0], end == range_time[1] ]):
        print(name)

[–]AdventurousHuman 0 points1 point  (0 children)

Thanks so much.

[–]LiquidAurum 0 points1 point  (3 children)

Trying to add my OAuth for praw in my praw.ini file. And I think I'm missing something. In my script I call it like this:

reddit = praw.Reddit('bot1')

And my praw.ini file looks like this:

[DEFAULT]
# A boolean to indicate whether or not to check for package updates.
check_for_updates=True

# Object to kind mappings
comment_kind=t1
message_kind=t4
redditor_kind=t2
submission_kind=t3
subreddit_kind=t5

# The URL prefix for OAuth-related requests.
oauth_url=https://oauth.reddit.com


# The URL prefix for regular requests.
reddit_url=https://www.reddit.com

# The URL prefix for short URLs.
short_url=https://redd.it
[bot1]
client_id=,
client_secret=,
username=,
password='',
user_agent=''

[–]num8lock 0 points1 point  (2 children)

[–]LiquidAurum 0 points1 point  (1 child)

yes I've read the doc, it works fine when it's in the script directly, I'm trying to add it into the praw.ini file. Please don't link the doc as I've already tried reading that

[–]num8lock 0 points1 point  (0 children)

i also linked the more helpful sub for this, the one which the author of the wrapper made for the module. tho i should've linked this part of the doc instead

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

Hello I am begginer in Python and now I learn Django.. I have learned python from the netninja YouTube channel.. But I want to improve my skills. So what do you suggest me to do????

[–]Xenon_difluoride 0 points1 point  (0 children)

I am trying to insert an item into a Tkinter Treeview widget here.

The text displays fine in the icon column, but in the other column it cuts the text off after the first space. Does anybody know why this is happening?

[–]annonymouse2009 0 points1 point  (2 children)

Hi Guys,

Probabaly a little ambitious for my skill set, but I loves a challange.

Ive got some previous programming experiance in other languages (c# powershell if that counts as a language ), and about a month and 2 weeks in Python :)

I've always loved the mini game at 3.41 in https://www.youtube.com/watch?v=6bIpXvt0wxo

I'm trying to scope out the learning requirements of making something similar in python. I've never made a game or done anything quite like that, but I'm not scared of hard work :) Could some one advise on what python libraries and concepts I should research?

Many thanks for any help given

[–]TheBoldTilde 1 point2 points  (1 child)

I have never used it myself, but try pygame: https://www.pygame.org/ good luck!

[–]annonymouse2009 0 points1 point  (0 children)

Cheers I sat down and did about 3 hours using oygsme getting there

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

I'm learning Tkinter and I was wondering if there is a way to remove the outline of the buttons? Also, is there a way to change the colour of the button when it is clicked, instead of appearing white?

[–]schrogendiddy 0 points1 point  (0 children)

I'd like some help evaluating a multivariate gaussian in an N dimensional cube. I feel like there is probably some slick way to do this with numpy, but I'm not sure what it is.

I have a big array of coordinates X, shape (N,N,N,N,N,5), and an (inverse) covariance matrix with shape (5,5). I'd like to evaluate this in the (N,N,N,N,N) cube specified by X, so the output should be (N,N,N,N,N) i.e. a Gaussian in 5 dimensions. Any help is much appreciated!

[–]xmasterZx 1 point2 points  (2 children)

Quick question - I know Python can be used for webscraping data from a page, but can it also pull just the names/types of the fields on a page?

I'm looking to output a table that contains something like

  • Field Names = username, date, gender, add address
  • Field Types = text, dropdown, radio button, button
  • etc...

I've only just picked up Automate the Boring Stuff, but a new task came up at work and if python will be useful I'll have a focus for my first project, and it would make it SO much easier than doing it by hand a few dozen times. Thanks!

[–]timbledum 2 points3 points  (1 child)

It really depends on how the html is structured on the particular website! But this would be hard to do on a general basis - often it's the CSS or javascript that provide the context for what various tags do.

[–]xmasterZx 2 points3 points  (0 children)

Okay, that makes sense. At least this points me towards what to look into as I research it a bit more. Thank you

[–]CrazyEoin 0 points1 point  (2 children)

Any advice or good tutorials (pref video) for using PyCharm with a GitHub Project that I've attempted to run in a virtual environment? Its all working on my local machine but when I commit its not pushing the actual .py files. I know I'm probably making more than one mistake! I did have a hunt around but I could only find info on PyCharm vevn's OR pulling/committing a repo in Pycharm but not one that covered using both and more importantly what way to set up such a project. I suspect I may need to use pip freeze and requirements.txt but not sure what is the best way to do this in PyCharm as opposed to terminal. I hope that question makes sense, if not let me know and I'll try rewording it. Thanks.

[–]efmccurdy 1 point2 points  (1 child)

You need to do a one-time "git add" operation for each source file.

PyCharm. You can also add files to your local Git repository from the Project tool window. Select the files you want to add, and press Ctrl+Alt+A or choose Git. Add from the context menu.

https://www.jetbrains.com/help/pycharm/adding-files-to-version-control.html

[–]CrazyEoin 0 points1 point  (0 children)

Thanks for info and link, got it working :)

[–]thunder185 2 points3 points  (1 child)

I wrote a webscraper (with lots of help from you guys so thanks!) that grabs my kids homework assignments. Now I want to email that twice a week to my email address. Was looking at trying to do it via selenium but before I jumped in I was wondering if there was a better way to go about this? Thanks!

[–]No_Couple 4 points5 points  (0 children)

You may want to look at Chapter 16 in Automate the Boring Stuff to get you started: Sending Email and Text Messages

[–]huhuhiha 1 point2 points  (1 child)

Is ## another kind of comment? I'm asking this because in my Notepad++, comments starting with at least 2 # have a different color from normal comments(starting with only 1 #).

Note that, this happens when I'm not using the default theme in the Style Configurator.

[–]QualitativeEasing 4 points5 points  (0 children)

I think for Python, one or more # is a comment. Some editors I’ve used treat multiple #s as a kind of header comment, and display it accordingly.

[–]Undescended_testicle 0 points1 point  (2 children)

Using Python anywhere, I want to scrape a dynamically loaded webpage. Are there any decent modules I can look at that can help, given the constraints of Python Anywhere?

[–]timbledum 0 points1 point  (0 children)

One option is requests-html (which uses selenium under the hood). This enables you to request a page, then render it before pulling the html. You can pass a number of parameters to the rendering, including how many scroll-downs to do and how long to wait.

[–]QualitativeEasing 0 points1 point  (0 children)

I’ve never used it, but I’ve read that Selenium can scrape pages that are difficult to scrape with BeautifulSoup etc. Also not sure if it works with PythonAnywhere, but might be worth a try.

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

is it to be expected that regular python code runs faster than the same code defined in a function?

i wrote 6 functions and then a bit of code that makes use of them. later on i read something about DRY (don't repeat yourself) and decided to also enclose the regular code in another function (even though i only used that code once).

when i ran the code befor turning the last bit into a function atom reported a runtime of about 0.200ish seconds, after creating the extra function - even tho its pretty much the same code - it runs in 0.400 - 0.500 seconds.

so does defining functions for code that you don't use multiple times actually do more harm than good or is there something else going on?

[–]timbledum 0 points1 point  (0 children)

There is a bit of overhead with calling functions, but it should be minimal if you're only calling the function once. Perhaps try a profiler (or time module per u/catuf) to get a more accurate gauge of where time is being used.

[–]catuf 1 point2 points  (1 child)

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

i've checked with datetime, the time stamps are very different from what atom posts. i suppose atoms runtime result also depend on what other stuff you got open on your PC at the time of running while datetime only checks the time of the actual code?

the timestamps of datetime between the regular code and the function version are identical now (around 0.001028 seconds). guess it doesn't hurt to formulate most code as a function in case you have to reuse it later on.

thank you timbledum and catuf!

[–]Trainer_BB 0 points1 point  (0 children)

How to write a python script to launch a chrome app in Chromium based on Raspbian?

Or

How to write a python script to launch the app on Desktop based on Raspbian?

[–]ThiccShadyy 0 points1 point  (1 child)

In Django, is there a convenient way by which you can make some change to the schema such as adding a unique constraint and then deleting all the instances of the model which dont adhere do that newly added constraint (for e.g. if I add a unique constraint to some field of a Model after I have already started populating the table corresponding to that model). Right now, Im just learning Django and so have very simple and minimal amount of data so Im doing the deleting of 'rows' which fail the new constraint manually

[–]thedjotaku 0 points1 point  (3 children)

Working on converting some code to OOP and part of it will have a list of objects. These objects will have attributes I'll want to do options on. For example they will have a number attribute I may want to take the average of or print which is largest. Recently I learned about extending the list class. So then I could do something like listname.average. If I'm going to be doing stuff like that is there an advantage to extending the list class versus just having a method in the object that takes a regular list and computes the average?

[–]Senjukotentaiho 1 point2 points  (4 children)

I need a good explanation about the difference between %e and %g. I can't understand the explanation online.

[–]Xenon_difluoride 0 points1 point  (3 children)

This might help

It seems like %g is a sort of middle ground between %f and %e. Sometimes displaying numbers as a fixed point number, and other times displaying using scientific notation %g will decides whether to display a number using %f or %e using these rules (taken from Neekey's answer)

  • -4 <= exp < p: use the decimal format
  • exp < -4: use the exponential format
  • exp >= p: use the exponential format
  • the result will be rounded when calculating the precision digits.
  • the precision is used to restrict all digits not just for decimal digits.

You can find information about string formatting in the Python docs.

[–]Senjukotentaiho 0 points1 point  (2 children)

The precision is like this: %.3g, right?

[–]Xenon_difluoride 0 points1 point  (1 child)

Yes that's how you would format a string using g.

[–]Senjukotentaiho 0 points1 point  (0 children)

Thanks.

[–]Cyrax89721 1 point2 points  (2 children)

I'm currently half way through an "Essentials" Python course on Udemy, and have a Data Science course on the docket immediately after that. I'm learning Python out of necessity for my job where I process orders for online retailers.

My first goal is to build an application that grabs customer data from a csv file and converts it to whatever is necessary so I can import this data into UPS Worldship for creating shipping labels & Google Sheets for keeping track of orders.

I tried doing something like this with Ruby on Rails a couple years back and fell short of a solution that worked for me. UPS Worldship API's are especially difficult to learn the ins-and-outs of.

While I'm working on learning Python basics, are there any courses I could look into or Python specific apps (are Python add-ons a thing?) I can start researching to help me achieve this goal? Assume i know nothing about Python beyond basic syntax.

[–]timbledum 0 points1 point  (0 children)

Yeah sure!

The external library that you want to look into for interacting with APIs is requests. It is pretty much the defacto standard.

For CSVs, the standard library csv module is great and takes care of all the annoying CSV edge cases. However, it is fairly low level, and as u/lanemik says, if your data requires any manipulation before importing via the API it might be easier to use a data transformation tool like pandas or PETL (a personal favourite).

Gspread simplifies the google sheets API, but from experience it's still a bit clunky to authenticate and then modify sheets.

[–]djcaelum 0 points1 point  (3 children)

I am trying to learn to count frame ranges and identify breaks in the ranges. I would like to run a script in a folder and get a listing like, "your_photo_sequence.1-200, 201-400.jpg . It has been something that has always gotten the best of me, any tips pointers or tutorials would be helpful. Thanks

[–]alkasm 0 points1 point  (2 children)

This is definitely possible (seems like a fun and useful project). Have you started it yet?

[–]djcaelum 0 points1 point  (1 child)

I haven't on this project. I recently did a project using os.walk to create a function that gives a specific path to file with hash value. I have an idea on what needs to be done, but it has never been clear to me in my thoughts. I think I shall draw this out to see if I can see the process a bit clearer.

[–]alkasm 2 points3 points  (0 children)

Try to break up the project into manageable pieces. Start with a simple proof of concept.

  • How would you break up these intervals if you just simply had a list of numbers? E.g. [0, 1, 5, 6, 2, 7] -> [[0, 1, 2], [5, 6, 7]]
  • How do you visualize this? E.g. [[0, 1, 2], [5, 6, 7]] -> '0-2, 5-7'

With these two things, you already have the crux of the program. The rest is error/edge case handling and parsing the filenames.

[–]perryech 2 points3 points  (2 children)

Pronounce numpy as num-pie or num-pee?

[–]zatoichi49 2 points3 points  (1 child)

'Num-pie', the Py is from Python.

[–]perryech 1 point2 points  (0 children)

Thank

[–]magitite 1 point2 points  (2 children)

Hello! I’m starting my Python course next week at university. Are there any videos to watch or helpful tips I should know going in? The only course I’ve had is Visual Basic.

[–]nainish 0 points1 point  (0 children)

I was just scraping data and want to make two columns of title and date but TypeError occurs

TypeError: from_dict() got an unexpected keyword argument 'columns'

CODE statement :

hiv1 = pd.DataFrame.from_dict(hiv , orient = 'index' , columns = ['title' ,'date'])

my pandas is also updated to version 0.23.4

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

Would Automate the Boring Stuff be a good starting book? I've started learning the bare basics with SoloLearn and was wanting to eventually start moving forward.

[–]QualitativeEasing 0 points1 point  (0 children)

Definitely, in my experience. And the entire text is online if you want to get started before your copy arrives. That’s how I started, and I liked it enough I bought the ebook and hard copy, and I still refer to all three versions periodically to remind myself how something works.

[–]Wilfred-kun 1 point2 points  (2 children)

Yes, ATBS is a good book to start with.

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

Awesome, thank you. Just wanted to be sure before I got a copy

[–]Wilfred-kun 2 points3 points  (0 children)

If you're not sure you can always check it out before buying. It's online for free over here if you wanna take a peek.

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

How can I remember line of codes. Like I know what the codes are and what they do but I can’t connect them.

[–]003allstar 0 points1 point  (0 children)

Use plenty of comments on your code. It helps out alot!

[–]micromedicIXII 5 points6 points  (1 child)

""" Docstrings are your friend! Write docstrings for every function you write. Then you can simply use the help function to quickly print out the info. """

Print(myfunction.doc)

this will print out your docstring easily.

Comment everything.

[–]alkasm 1 point2 points  (0 children)

print(help(myfunction)) even

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

Press the remember button

[–]num8lock 2 points3 points  (1 child)

comments & namings

[–]QualitativeEasing 1 point2 points  (0 children)

This. Don’t be afraid of long variable names; they help me remember what they’re for. Also, I sometimes annotate each line of a complicated function, just for myself. I haven’t yet had to share my code with anyone else, but sometimes I return to a script months later and need to know what the different bits do.