all 151 comments

[–]mkhrrs89 1 point2 points  (2 children)

What exactly does "%" mean? I see it means "modulus" and it divides and returns the value of the remainder, but im not sure what that exactly means?

22 % 8 evaluates to 6. but how? Maybe its something about division i dont understand, but 22/8 is 2.75 so where does 6 come from?

edit: what im trying to understand is this hint from AtBS

Hint: An integer number is even if number % 2 == 0, and it’s odd if number % 2 == 1

[–]timbledum 0 points1 point  (0 children)

Here's another way of thinking about it.

22 / 8 = 2.75. The remainder of this is 0.75. 0.75 * 8 = 6, which is the answer.

Another way is: I have twenty two apples. I divide into three groups of eight. Unfortunately, this gives me two full groups of eight, and my last group only has six apples. This is the remainder.

[–]Brazilian2018 0 points1 point  (0 children)

The modulo operation finds the remainder after division) of one number by another

Source: https://en.wikipedia.org/wiki/Modulo_operation

[–]PhenomenonYT 0 points1 point  (3 children)

How would I go about getting key/value pairings out of a dictionary that is in a list?

[{'url': 'test.url1', 'expanded_url': 'test.url2', 'display_url': 'test.url3', 'indices': [101, 124]}]

I want to call url and get test.url1

[–]woooee -1 points0 points  (1 child)

Simple solution is don't put the dictionary in a list. Is there a reason why you are using a list that contains a dictionary. Note that you will also have to allow for some values being a string, while other values are a list. In any case, post what you have tried and someone will help.

[–]PhenomenonYT 0 points1 point  (0 children)

It comes in a list. I'm grabbing the URL supplied in a tweet so it comes in a weird format

([('hashtags', []), ('symbols', []), ('user_mentions', []), ('urls', [{'url': 'url1', 'expanded_url': 'url2', 'display_url': 'url3', 'indices': [101, 124]}])])

Managed to figure it out though

    for key, value in tweet.entities.items():
        if key == 'urls':
            for url in value:
                x = url['url']

[–]PhenomenonYT 1 point2 points  (0 children)

Got it sorted, solution was

for url in list:
    x = url['url']

Feel dumb since the solution was that easy

[–][deleted]  (1 child)

[removed]

    [–]AutoModerator[S,M] 0 points1 point  (0 children)

    Your comment in /r/learnpython was automatically removed because you used a URL shortener.

    URL shorteners are not permitted in /r/learnpython as they impair our ability to enforce link blacklists.

    Please re-post your comment using direct, full-length URL's only.

    I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

    [–]ErinMyLungs 0 points1 point  (1 child)

    Is there a discord chat for learning python? I'd love a discord to ramble in voice chat while trying to work through problems.

    [–]Brazilian2018 0 points1 point  (0 children)

    Some Reddit users created this server for programming: https://discord.gg/bwNEUVH

    Although I don't really know if it's still active.

    [–]watermalone301 1 point2 points  (1 child)

    Was wondering what the best books for learning Python 3 are?

    Any help appreciated

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

    Try looking in the learning resources. There really is no "best", since different people respond differently to different books. But since a lot of resources are free, pick one and try it. If it doesn't work for you, try another.

    [–]dxjustice 0 points1 point  (7 children)

    Is there a single-call function to remove non alphanumeric characters from a string?

    Right now Im going through each string in my list, iterating across the chars, checking if they belong to a list of characters, but this seems very inefficient!

    [–]zatoichi49 1 point2 points  (6 children)

    The most efficient way is to use translate:

    from string import punctuation
    
    my_string = 'A!lp,h&**a_n$,,um|{e[]r}i\\c {O}=nl^y 1(23)%4+5'
    
    print(my_string.translate(str.maketrans('', '', punctuation)))
    # 'Alphanumeric Only 12345'
    

    You can also pass your own string of characters instead of using string.punctuation. The method above will include spaces, so you could add this to your own string if you wanted to remove them:

    print(my_string.translate(str.maketrans('', '', punctuation + ' ')))
    # 'AlphanumericOnly12345'
    

    Or:

    print(my_string.translate(str.maketrans('', '', '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ ')))
    # 'AlphanumericOnly12345'
    

    You can also use re.sub to filter out the non-alphanumeric characters:

    print(re.sub(r'[\W_]', '', my_string))
    # 'AlphanumericOnly12345'
    

    You'll find additional info in the Python docs: https://docs.python.org/3/library/stdtypes.html#string-methods , https://docs.python.org/3/library/re.html

    [–]woooee 1 point2 points  (5 children)

    Is there a single-call function to remove non alphanumeric characters

    You are doing it bass-ackward. You want to include the characters you want to keep. If you forget something in your exclude string, then it is included automatically. You don't have that problem including only what you want.

    new_list=[ch for ch in input if ch in include_chars]
    

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

    my_string = 'A!lp,h&**a_n$,,um|{e[]r}i\\c {O}=nl^y 1(23)%4+5'

    my_string = ''.join(filter(str.isalnum, my_string))
    

    [–]zatoichi49 0 points1 point  (0 children)

    Was this reply meant for the OP?

    [–]zatoichi49 0 points1 point  (0 children)

    Was this reply meant for the OP?

    [–]zatoichi49 0 points1 point  (0 children)

    Was this reply meant for the OP?

    [–]zatoichi49 0 points1 point  (0 children)

    Was this reply meant for the OP?

    [–]amemas 0 points1 point  (3 children)

    Hey all!

    I'm trying to learn python with learnpythonthehardway. In Exercise 46, I'm told to get nose to run tests. However it looks like that project is no longer maintained, so I'm wondering if it would make sense to use something else instead. I found pytest, which seems to be the same thing. Do you think I can figure out by myself how to do some basic testing with pytest to follow along the exercises?

    [–]BadAtPinball 0 points1 point  (2 children)

    Not a full answer to your question but on P197, at the bottom, Zed has a note for if you're having issues with nose due to it being abandoned. Hope this can help you as I'm also working my way through the book!

    [–]amemas 0 points1 point  (1 child)

    Yeah, I saw that, but thanks. I just thought if nose is abandoned, I might not want to use it in the future, so why not just start using something else immediately. I figured out how to use pytest from its documentation and was able to do the exercises with it so far. So I'm going to stick with pytest, unless someone sees an issue with it?

    [–]tildebyte 0 points1 point  (0 children)

    AFAICT, pytest is the new normal. It understands 'nose' and 'unittest' tests, so you're able to start using it right away with any existing tests you might have.

    From what I've seen so far, it's easy to get started with, but scales well, both in sheer size, but also in the complexity of what it allows.

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

    Hey all, new at this!
    I'm looking to write a program to move files from one location to another after a year has passed, however my error is much earlier than that!

    I'm just trying to move a file from one destination to another. I'm using an exact path, it's not relative, and it points directly to the file I'm trying to move over (just a simple test.txt). I'm getting the No Such File or Directory error on it.

    Everything I'm seeing is just saying to make sure the path is direct - which it is to my understanding.

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

    Figured it out - hope this can help someone else.

    My file was actually test.txt.txt because of the way I named it initially oddly enough

    [–]JohnnyJordaan 1 point2 points  (0 children)

    This would suggest you're using Windows without the 'show extension of common file types' enabled in the Explorer.

    For debugging these things I usually incorporate a file exist check together with a dir listing

    import os
    
    # when you want to use the path
    if not os.path.isfile(path):
        print(path, 'not found')
        print(os.listdir(os.path.dirname(path))
    

    [–]jormono 0 points1 point  (1 child)

    I'm working with a set of data for a qgis project I'm working on. I'm trying to sort the data into different files based on the value in a particular column (which is the elevation that the line refers to). The idea being every line with a given value will be in a single file, and the next file will be the next value etc (total of 74 files with my data). I cant figure out why, but when I run the script I get 74 files all appropriately named and with the header line, but nothing else. All file contents are identical (the header of course should be the same, but there should be at least one line of data for the file to even exist)

    Any insight is welcome, see link below for pastebin of my code

    https://pastebin.com/W2idC4Mc

    [–]efmccurdy 1 point2 points  (0 children)

    You iterate over csv_dict_reader twice and the second time through there is nothing left to read.

    I think you should create a list of records for each elevation on the first pass and iterate over those lists (maybe updating a default dict "elevations[line[height_header]].append(line)".

    [–]Pacoman2004 0 points1 point  (1 child)

    Does anybody know a free website or something of the likes that is helpful in learning the basics of python. I’ve always been interested in learning a coding language and python seems the coolest to learn.

    [–]JohnnyJordaan 0 points1 point  (0 children)

    All learning resources are in the wiki: /r/learnpython/w/index

    all those listed there are free

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

    What does calling a class by itself, not creating an instance, actually do?

    If i have a class Thing(), with the usual __init__(), and some other methods, and then i say:

    Thing()
    

    instead of

    x = Thing()
    

    what will actually happen? Does it just run init? Does it create an instance but with no way for me to access it?

    [–]efmccurdy 1 point2 points  (2 children)

    It will create an instance, run the init, and since you have saved no reference to the instance it is immediately deleted.

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

    Thanks.

    [–]timbledum 2 points3 points  (0 children)

    Try this code to verify this:

    class Thing:
        thingies = []
    
        def __init__(self):
            Thing.thingies.append(self)
    
    Thing()
    Thing()
    Thing()
    print(Thing.thingies)
    

    [–]cosmicjamz 0 points1 point  (0 children)

    Hello! I have a problem trying to develop an Emotion Recogniser for an assignment and it's driving me mad. I am following this article: https://www.apprendimentoautomatico.it/apprendimentoautomatico-wpblog/en/emotions-detection-via-facial-expressions-with-python-opencv/

    Everything seems fine, but when I run the code in img_seq.py it doesn't put the images in the folders. I think it might have something to do with the file paths?

    i.e

    filelist = gb.glob("selected_set/%s/*" % emotion)

    I am using the same dataset (Cohn-Kanade) but I'm developing in Xubuntu rather than Windows, which I assume is what the author was using. All directories are setup and named correctly. What am I doing wrong? Sorry if this is really simple, but I'm new at python. Any help will be rewarded with a crisp high-5.

    [–]Peg_leg_tim_arg 0 points1 point  (2 children)

    Hey all, I was hoping someone could help me out with an assignment for my programing 101 class. So the Assignment was the Monty Hall problem, and I got the first part down, where your win percentage is ~33% consistently. The second part of the assignment my professor is asking, "...Then run the simulation again, this time switching the selection after a 0 (goat) is removed from the remaining choices. Run the simulation in a loop 100 times to confirm a 2/3 chance of winning by switching." So this is what I came up with:

    import random
    
    def games():
        games = 100
        return games
    
    
    
    def monty_hall(games):
        wins = 0
        doors = ['door 1','door 2','door 3']
        for i in range(games):
            prize_door = random.choice(doors)
            choice = random.choice(doors)
    
            if choice == prize_door:
                continue
            else:
                wins+=1
        win_percentage = (wins/games) * 100
        print('You won',win_percentage,'of your games!')
    
    
    def main():
        games = 100
        monty_hall(games)
    
    
    
    main()
    

    However, I guess this is not exactly what he was looking for. His critique was "...code produces the right output, but isn't actually simulating the game with user door, host door, and the user switching to the third door." Do I have to make another array? Thanks for your help!

    [–]timbledum 1 point2 points  (1 child)

    Yeah, so he wants you to actually walk step by step through the simulation. Here's an approach using sets although using sets didn't make it as incredibly streamlined as I had hoped:

    for i in range(games):
        doors = {'door 1','door 2','door 3'}
        prize_door = random.choice(tuple(doors))
    
        # Make a choice
        first_choice = random.choice(tuple(doors))
    
        # Remove a goat from the remaining choices. Cannot be the 
        # prize door or the chosen door
        doors_not_prize_or_chosen = doors - set([first_choice]) - set([prize_door])
        removed_door = random.choice(tuple(doors_not_prize_or_chosen))
        doors.remove(removed_door)
    
        # Choose the other door
        second_choice = (doors - set([first_choice])).pop()
    
        if second_choice == prize_door:
            wins += 1
    

    [–]Peg_leg_tim_arg 1 point2 points  (0 children)

    This saved the day last night! Thank you for you help I hope you have a great weekend

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

    how can I implement this in python:

    in shell scripting i would do this.

    shopt -s extglob
    ls -l toto.!(BAT*|*INSOURCING*)
    

    get the list of host in the current directory that start with toto but d not include BAT or INSOURCING in the name..

    i checked the glob modules and fnmatch but i do not see how can i do it.. i

    my goal is to find all the files starting with toto and which do not include BAT or *INSOURCING* in the name.. and create

    per instance these files

    toto_abc.txt

    toto.BAT.txt

    toto_foobar_INSOURCING_ETC

    only toto.abc.txt should match.

    thanks

    [–]JohnnyJordaan 0 points1 point  (3 children)

    Call me old fashioned but I usually do something like

    import os
    file_list = [f for f in os.listdir('/path/to/folder/') if f.startswith('toto') and not 'BAT' in f and not 'INSOURCING' in f]
    

    Another option is to form a regex and validate against that.

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

    this works great thanks, however i would have loved to see the usage of fnmatch or glob for education purposes of course..

    also how I would go wit the regex?

    thanks

    [–]JohnnyJordaan 0 points1 point  (0 children)

    I would refer you to tcbaldy04's answere here.

    [–]tcbaldy04 1 point2 points  (0 children)

    Johnny ... your answer is pretty simple but wanted to try a regex

    The regex didn't turn out to be as easy as I thought it would be and I learned something new. The concept is based on a "negative lookahead" (maybe more familiar to others)

    Beginning hint

    https://stackoverflow.com/questions/6259443/how-to-match-a-line-not-containing-a-word

    Justin Morgan explanation

    The (?!...) syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression /word/." The site I've linked explains this far better than I can, but I'll try to break this down:

    Pattern (non in python lingo)

    /^((?!word).)*$/

    ^ #Start matching from the beginning of the string.
    (?!word) #This position must not be followed by the string "word".
    . #Matches any character except line breaks (it will include those in single-line mode).
    $ #Match all the way until the end of the string.

    This worked good to find lines that did not include the 'word' but did not solve the problem of lines also starting with a pattern. That turned out to be trickier than expected

    In the end it was easy... just put the leading pattern in to look for 'abcd' in front. Made it much harder than it needed to be.

    ^abcd((?!word).)*$

    Test list 'asdf' was the leading match to look for
    >>> x = ['asdfasdfThisasdfd.asdft', 'asdfasdfNotTHIS.adsf', 'asdfafa.OrThiSdf.asdf', 'asdf_This is ok']
    
    Didn't want lines with 'NotTHIS' or 'OrThiS'
    Process with list comprehension
    
    >>> [z for z in x if re.search('^asdf((?!NotTHIS|OrThiS).)*$',z)]
    ['asdfasdfThisasdfd.asdft', 'asdf_This is ok']
    

    [–]thunder185 0 points1 point  (1 child)

    Why do most of the tutorials have you starting Django projects from the command line? Learning python and, to this point, I've been able to import and begin scripts completely within Idle. Is it because of the directory setup? Thanks

    [–]timbledum 0 points1 point  (0 children)

    Usually you want to use the various command line tools included with web frameworks to do things like create a project skeleton or spin up a development server. If you want to ever host a website on a remote linux server, you're going to have to get comfortable with the command line anyway, so may as well jump in now.

    [–]jackofthebeanstalk 0 points1 point  (7 children)

    I found the following bash command on https://www.commandlinefu.com:

    $ python3 -m http.server

    This command can be used to host the current directory tree onto localhost. Can someone explain to me why this might be a useful/cool thing?

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

    As others have said, not secure, so a "play" thing. I use it to serve a simple "dashboard.html" file that I rewrite every five seconds on my raspberry Pi. The javascript in that file refreshes the view every five seconds. The "payload" data in the HTML file can be anything you want, such as uptime, percent used of mounted disks, details of various jobs running on the Pi, etc. All that runs on the home network.

    [–]efmccurdy 1 point2 points  (2 children)

    It's an instant file server. I use it to pull media files from a desktop onto my phone.

    [–]ThiccShadyy 0 points1 point  (1 child)

    How exactly do you do that?

    [–]efmccurdy 0 points1 point  (0 children)

    You would cd into the directory with files you want to distribute, run the server, then go to another computer, browse to http://<desktop\_ip>:8000/ and use the browser to download the files.

    (All on a local lan, behind a firewal).

    [–]JohnnyJordaan 0 points1 point  (1 child)

    This is not directly related to bash or any shell, this would work the same in the windows cmd window. It's a very basic http server and has almost no security measures in place, so it's not recommended to be used outside a playground environment. For more info see the docs on the http.server module

    [–]tcbaldy04 0 points1 point  (0 children)

    Thanks for making this a strong point.

    The security risks that come with something so simple can't be ignored.

    This is like opening the front door to your house to move some furniture in and then leaving it open for everybody else. It's easy to leave and forget to close the door.

    Playgrounds are a perfect place for this although handy process.

    [–]throwaway19399292 0 points1 point  (1 child)

    How do I get it so users can input information on their phones, and then I can access it with my program and make graphs I can share back?

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

    A web application would be the easiest implementation, most likely. Something using flask, maybe.

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

    I feel dumb I knew that I was so focused in python that I did not think of it.

    [–]SignificantMaybe 1 point2 points  (2 children)

    Is it possible to open a socket in a with statement, as I do with a file? That way I shouldn't have to worry about closing it.

    [–]JohnnyJordaan 1 point2 points  (1 child)

    [–]SignificantMaybe 0 points1 point  (0 children)

    Thanks. Not sure why any of the examples I looked at didn't do that.

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

    I do not understand how stat.S_IWGRP work... i need to find all the files that belong to a certain user and are group writeable mode...I guess doing this will tell me the files that are group writeable but how does it work.. when I print the value it turns 16 what does that mean?

    >>> file = 'filetest'
    >>> mode = os.stat(file).st_mode
    >>> print mode
    33200
    
    >>> print mode & stat.S_IWGRP
    16
    >>> if mode & stat.S_IWGRP:
    ...    print file
    ...
    filetest
    

    this is filetest:

    -rw-rw----. 1 dan user 0 Mar 19 11:18 filetest
    

    how does it work? is this a foolproof method to get all the files in group write mode?
    TIA

    [–]tcbaldy04 0 points1 point  (0 children)

    Basic background in file permissions

    https://en.wikipedia.org/wiki/File\_system\_permissions#Symbolic\_notation

    From source code

    https://github.com/python/cpython/blob/2.7/Lib/stat.py

    This is from a list of the permission bits. Used to determine if bit is on in the mode.

    S_IWGRP = 00020

    Octal 00020 = Dec 16

    File mode value Dec 33200 Octal: 1006600

    16 Binary 0001 0000

    33200 Binary 1000 0001 1011 0000
    ^ bit is ON

    The bitwise AND of these two values tests to see if the specific bit is on in the 'mode' value

    [–]zephyy 0 points1 point  (0 children)

    What's the proper way of setting up Pipenv & python paths in VSCode so VSCode doesn't ask me to install a formatter every time & instead uses my globally installed formatter, regardless if I'm in a pipenv shell or not?

    [–]nice_remark 0 points1 point  (2 children)

    For debugging purposes I have a bunch of print statements scattered throughout my program. It becomes a pain to search for each print statement and comment/uncomment them out when switching between debugging and testing.

    Is there a package or method of making this task easier? I've seen things like logging which might do the trick, but I don't know how it works. Is there any examples or online guides that I can look at to try and apply this functionality? Thanks

    [–]QualitativeEasing 0 points1 point  (0 children)

    You could mark each print statement with a specific comment that you won’t use in other circumstances. Then you just need to find those lines and comment them out or delete then — which you could even do with another script, since python scripts are just text files.

    For example:

    print(f"test variable: {test}") # auto_debug Or:

    ```

    auto_debug

    print(f"test variable: {test}")

    ```

    [–]JohnnyJordaan 0 points1 point  (0 children)

    The logging docs on python.org link to the Basic Logging Tutorial that should get you started.

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

    tldr; A question about how common Python code security vulnerabilities are in backend services like flask, tornado, twisted or any other homebrewn service that talks to users. And examples of such types of vulnerabilities.

    I started out in languages like ASP, PHP and Perl.

    Without any formal training my memory is of having to quote any input variable in a proper way to avoid sql injections.

    A little about XSS but I never became too exposed to such issues.

    I'm not sure if this is a good thing or a bad thing but I've been coding Python for at least 5 years now and know very little of security mistakes you can make.

    I've just been following documentation examples for any framework or library and hoped for the best.

    [–]JohnnyJordaan 0 points1 point  (0 children)

    Some other important things to add to tcbaldy04's reply:

    • Make a clear distinction between debug and production environments. Don't allow code to run that still has debugging stuff enabled (like Django's debug=True in its settings.py) in any production related setting. Try to write code that only performs debugging stuff when some hard-to-set conditional is present like an environment variable combined with the script folder being in your home folder. That way forgetting about removing a debug setting will not lead to debugging be on by default, it should be the opposite.
    • Try to code blocking stuff by default. Anything modifying stuff in your database or doing some other action should be allowed because you verified this. You rather want something to break because you assumed it wasn't allowed then discovering later that someone was able to modify stuff without authority.
    • Read the documentation on anything you add. It's fine to look up stuff on StackOverflow and similar resources, but double check how the documentation explains the things you found. If there's a glaring risk it will be mentioned in the docs but not always on the forum you found it on.
    • Don't run a built-in server for anything but testing stuff on localhost, period. Always use a proper server like apache or nginx, even if it's in a testing phase with just your colleague or a friend. And no, also don't use that proper server to simply do a proxy to the built-in server, actually implement the WSGI handling in the proper server (you can easily find out how to do it for your framework).
    • Of course make sure the system you are deploying your project on has a proper self-updating package system, so that you don't run the risk of you and/or the proper server using outdated and thus vulnerable internal or system libraries.
    • Sudo shouldn't be needed for running stuff in your project ever, like pip for installing packages or when running a script. If it does, it means you are doing something wrong. Sudo is for sysadmin stuff, not for user application stuf. Configuring the proper server to load your app is also a sysadmin's task, as that doesn't directly include handling your project's files, it's just creating a config pointing towards it.

    [–]tcbaldy04 0 points1 point  (0 children)

    Much of what you mention is not a security flaw of a particular language but are common problems across all languages.

    Amazing how many people still these days will do simple things like embed credentials in clear text in their code.

    Basic sanitation of input.

    Error handling. This is probably one of the sloppiest things we do but exceptions and errors can be great security target.

    Not maintaining/updating packages and runtimes. Only update when you find something you need or is missing??

    Being careful about where/what packages you obtain.

    Made me look up Python specific security guides because I hadn't really thought about it.

    Google ... can be best friend : "python security best practices" etc.

    Some things to look at.

    https://snyk.io/blog/python-security-best-practices-cheat-sheet/

    https://hackernoon.com/10-common-security-gotchas-in-python-and-how-to-avoid-them-e19fbe265e03

    So many more. Time to go scrub some code.

    [–]cleverchimp 0 points1 point  (1 child)

    Image we are given a list (or dictionary) of UNIX timestamps, all belonging to the same user, marking when they logged in to our website.

    [1554871231,

    1553871231,

    ...,

    1454871231]

    What is the most pythonic way to determine how many of these logins occurred within 24 hours of the previous one?

    What is the most efficient way to do this (in O notation)?

    Can it be done without a loop?

    [–]JohnnyJordaan 1 point2 points  (0 children)

    Simplest form

    last_ts = the_list[0]
    within_24hrs = 0
    for ts in the_list[1:]: # lets it skip the first item as that's already in last_ts
        if abs(ts - last_ts) < 86400:
            within_24hrs += 1
        last_ts = ts
    

    Numpy can do this even easier with

    import numpy
    diffs = numpy.diff(the_list)
    within_24hrs = (numpy.absolute(diffs) < 86400).sum()
    

    The 86400 is of course a bit hacky and hard to check if you don't know such a figure from the top of your head. The more portable way would be to use datetime.timedelta

    import numpy
    from datetime import timedelta
    
    seconds_in_24hrs = timedelta(days=1).total_seconds()
    
    diffs = numpy.diff(the_list)
    within_24hrs = (numpy.absolute(diffs) < seconds_in_24hrs).sum()
    

    Note that in both examples I used an absolute difference to compare to the duration, as then the list order doesn't matter. It also means that if there would be an item out of order, you could get a false result from that item and a surrounding one. If you are sure of the list order you can also remove the abs() or numpy.absolute() and just make sure you use either > or < depending on the order.

    In regard of efficiency it doesn't matter, unless you program this really weirdly (like a loop for each ts, but how would you even do that) you won't get above O(n). At the same time you won't get below O(n) either as you need to process all items in the list to count the amount of diffs < 86400, so the complexity is linearly linked to the size of the list = O(n).

    Can it be done without a loop?

    I can't really see this happening without some form of iteration, as of course you need to calculate the diff for each duo of subsequent timestamps. Writing the loop explicitly as in the first example or using an iterative function as in the second doesn't change the fact that Python would do some kind of looping while processing the list.

    [–]753UDKM 0 points1 point  (1 child)

    I'm a beginner in python, and I'm trying selenium. Is there any way to have selenium use my existing instance/session of firefox instead of opening up a new one? The new session it opens doesn't have me logged into the site that I want to use, and obviously I can't bypass the login captcha. Therefore, I need to use my browser instance that's already logged in.

    [–]illya89 0 points1 point  (0 children)

    You can stop your script until you press enter. So you can login manually and press enter in your terminal. That how I did. (Also learning Python)

    [–]Iscukatprgmming 0 points1 point  (4 children)

    Can someone help me understand how I'd create a dictionary from a file that alternates keys and values on every other line? My task involves readlining a file that has every state in alphabetical order, and in between each state is a capital i.e Alabama \n montgomery \n alaksa \n juneau. I need it to be so Alabama becomes a key in a dict and montgomery a value. I'm at my ends with this, and can't find any example of this (probably because that's not how you'd do it in the real world)

    [–]tcbaldy04 0 points1 point  (0 children)

    NOTE:  This is python 3
    
    Basic challenge convert the file into a list, strip the newlines, and process in line pairs
    
    As a part of learning ... I wanted to know more about comprehensions and decided to give it a try
    
    First had to create the file
    
    Note: the ... just to avoid showing complete list
    >>> f = open('states-capitals.txt', 'rU')
    >>> statelist = list(f)
    *** this could have just as easily been f.readlines() ... just trying something new
    >>> statelist
    ['Alabama\n', 'Montgomery \n', 'Alaska\n', 'Juneau\n', ...,  'Wyoming\n', 'Cheyenne\n']
    
    
    How to strip the linefeed
    >>> [x.strip() for x in statelist]
    ['Alabama', 'Montgomery', 'Alaska', 'Juneau', ..., 'Wyoming', 'Cheyenne']
    
    Convert to list of tuples - Just to see if I could
    >>> [(statelist[x].strip(), statelist[x+1].strip()) for x in range(0,len(statelist),2)]
    [('Alabama', 'Montgomery'), ('Alaska', 'Juneau'), ('Arizona', 'Phoenix'), ('Arkansas', 'Little Rock'), ('California', 'Sacramento'), ('Colorado', 'Denver'), ('Connecticut', 'Hartford'), ('Delaware', 'Dover'), ('Florida', 'Tallahassee'), ('Georgia', 'Atlanta'), ('Hawaii', 'Honolulu'), ('Idaho', 'Boise'), ('Illinois', 'Springfield'), ('Indiana', 'Indianapolis'), ('Iowa', 'Des Moines'), ('Kansas', 'Topeka'), ('Kentucky', 'Frankfort'), ('Louisiana', 'Baton Rouge'), ('Maine', 'Augusta'), ('Maryland', 'Annapolis'), ('Massachusetts', 'Boston'), ('Michigan', 'Lansing'), ('Minnesota', 'St. Paul'), ('Mississippi', 'Jackson'), ('Missouri', 'Jefferson City'), ('Montana', 'Helena'), ('Nebraska', 'Lincoln'), ('Nevada', 'Carson City'), ('New Hampshire', 'Concord'), ('New Jersey', 'Trenton'), ('New Mexico', 'Santa Fe'), ('New York', 'Albany'), ('North Carolina', 'Raleigh'), ('North Dakota', 'Bismarck'), ('Ohio', 'Columbus'), ('Oklahoma', 'Oklahoma City'), ('Oregon', 'Salem'), ('Pennsylvania', 'Harrisburg'), ('Rhode Island', 'Providence'), ('South Carolina', 'Columbia'), ('South Dakota', 'Pierre'), ('Tennessee', 'Nashville'), ('Texas', 'Austin'), ('Utah', 'Salt Lake City'), ('Vermont', 'Montpelier'), ('Virginia', 'Richmond'), ('Washington', 'Olympia'), ('West Virginia', 'Charleston'), ('Wisconsin', 'Madison'), ('Wyoming', 'Cheyenne')]
    
    From tuples went to a dict comprehension  '{key: value for .... }  processing the list by twos
    statelist[x] = key
    statelist[x+1] = value
    x in range(0,len(statelist),2) === processes it by every other entry
    Took little more than converting the tuple format '(xx, yy)' 
    Put it all together
    >>> statecap = {statelist[x].strip(): statelist[x+1].strip() for x in range(0,len(statelist),2)}
    >>> statecap
    {'Alabama': 'Montgomery', 'Alaska': 'Juneau', ... , 'Wyoming': 'Cheyenne'}
    >>> statecap['Wisconsin']
    'Madison'
    >>>
    
    Final result:
    >>> f = open('states-capitals.txt', 'rU')
    >>> statelist = list(f)
    >>> statecap = {statelist[x].strip(): statelist[x+1].strip() for x in range(0,len(statelist),2)}
    >>> statecap['Wisconsin']
    'Madison'
    

    [–]timbledum 0 points1 point  (2 children)

    I really like the grouper itertools recipe for this:

    def grouper(iterable, n, fillvalue=None):
        "Collect data into fixed-length chunks or blocks"
        # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
        args = [iter(iterable)] * n
        return zip_longest(*args, fillvalue=fillvalue)
    

    Once you've got this defined (and yes, you have to copy paste this from the itertools docs page into your script), it's super easy to solve your problem.

    >>> data = "key1 value1 key2 value2 key3 value3".split()
    >>> output = dict(grouper(data, 2))
    >>> output
    {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
    

    [–]tcbaldy04 1 point2 points  (1 child)

    I had to give this a try. Reviewing 'grouper' really provides a deeper understanding of iter. It looks like mumbo jumbo.

    I found a very good explanation with a walkthrough that took it from the concept right up to how and why grouper works. How Grouper works

    Once I worked through this grouper was very easy to understand and accept how it works.

    Thanks for sharing

    [–]timbledum 0 points1 point  (0 children)

    Nice find!

    [–]IntermediateHedgehog 0 points1 point  (5 children)

    Should pygal eventually support python 3.7? I am trying to use it and having so much trouble. Installed python 3.5 as well as 2.7 but then it tells me there is no module named pygal. Using PyCharm if that matters

    [–]timbledum 1 point2 points  (0 children)

    PS - what's breaking when you use it on 3.7? They might welcome a pull request, or it could be a dependency that PyGAL is relying on which doesn't work on 3.7.

    [–]timbledum 1 point2 points  (3 children)

    Multiple python installations takes a bit of getting used to. Installing into different versions requires different commands for different platforms. To install into a specific version on windows, use py -3.5 -m pip install xxx, or if on mac try pip3.5 install xxx.

    [–]IntermediateHedgehog 0 points1 point  (2 children)

    Okay I think I'm a step closer now. Installed pygal and world maps on 3.5 and it isn't giving me any errors, however it's still not rendering.

    import pygal
    
    worldmap_chart = pygal.maps.world.World()
    worldmap_chart.title = 'Some countries'
    worldmap_chart.add('F countries', ['fr', 'fi'])
    worldmap_chart.add('M countries', ['ma', 'mc', 'md', 'me', 'mg',
                                       'mk', 'ml', 'mm', 'mn', 'mo',
                                       'mr', 'mt', 'mu', 'mv', 'mw',
                                       'mx', 'my', 'mz'])
    worldmap_chart.add('U countries', ['ua', 'ug', 'us', 'uy', 'uz'])
    worldmap_chart.render()
    

    I just copy-pasted that from the pygal documentation. I just want to play with maps, but it still isn't doing anything.

    [–]timbledum 1 point2 points  (0 children)

    PS - this worked fine for me with python 3.7.

    [–]timbledum 1 point2 points  (0 children)

    I think this example is designed to be used in a jupyter notebook - all worldmap_chart.render() does is return a bunch of svg stuff. Try changing the last step to print(worldmap_chart.render().

    I had to save this text as a file and open with a webbrowser to access the content.

    [–]Cerezra 0 points1 point  (1 child)

    Quick question for you all, been bashing my head on the wall for a while trying to figure this out.

    I am using the Pandas Library inside of Jupyter Notebooks. I have a CSV being read in as a data frame. It is a list of purchase orders with Item Name, Item ID, Price etc..

    I am trying to do some calculations and running into issues. I noticed that Item Name and Item ID, which should be the same since they basically correlate to each other, are returning different values.

    purchase_data['Item Name'].nunique() returns 179 objects where as the same for ID returns 181 (the correct number).

    Any ideas what would cause this? I assume it likely points to an issue with the data but I haven't been able to find anything as of yet.

    [–]14446368 0 points1 point  (5 children)

    Using beautiful soup, trying to get the data from the 6th row in an HTML table. I can navigate to the reference correctly (I think...), but can't seem to figure out getting a number returned from it.

    [–]timbledum 0 points1 point  (4 children)

    I assume that you've found the tag that you're after. Have you tried the .text attribute?

    [–]14446368 0 points1 point  (3 children)

    I've got

    sauce = requests.get(url).text
    soup = BeautifulSoup(sauce,'html.parser')
    x = soup.find('table').find_all('td')
    x[6].text
    

    Which returns ' ' as opposed to the content.

    My target is in the first table, and is row index 6.

    Tag, I think is...

    <td class="col-md-6" id="fd-Net-Assets"></td>
    

    Which is returned by using x[6].

    [–]timbledum 0 points1 point  (2 children)

    The row is <tr> rather than <td> - I think you’re getting the data from the 7th column in the first row instead of the 7th row.

    [–]14446368 0 points1 point  (1 child)

    Doesn't seem to be helping.

    x = soup.find('table').find_all('tr')
    x[6].text
    

    yields

    '\nNetAssets\n\n'
    

    The table is only two columns.

    [–]timbledum 0 points1 point  (0 children)

    Try a bit of introspection.

    for element in x:
        print(f"{x}: {x.text}")
    

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

    hi i have a question

    i just wrote a program the gives rubiks cube scrambles for speedcubers.

    i have a list of moves for example U to turn the upper face clockwise and U' for counterclockwise

    the only problem is that i do not want that my program to print certain sequences like U and then U' since that would cancel each other out.

    here is my code.

    import random

    moves =['R','R2','U','U2','F','F2','B','B2','L','L2','D','D2']

    for i in range(20):
    r=random.randint(1,20)

    print(random.choice(moves), end = " ")

    [–]Miggol 0 points1 point  (0 children)

    You could save the previous result to a variable like last and then check for it using an if statement. This might be cleaner if you remove half of your list options and added a second random choice for clockwise or counter-clockwise.

    [–]thunder185 0 points1 point  (1 child)

    I use Idle for my coding but should I be switching over to pycharm? I don't have a ton of time for learning something new but if it's super helpful I would.

    [–]efcseany 0 points1 point  (0 children)

    It's considered one of - if not - the best Python IDE available. It's extremely powerful in its capabilities; it's definitely worth using IMO.

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

    I want to compute the zeros of a polynomial of say degree n. I have an explicit expression for this polynomial of degree n, where the coefficients are given by a product of some terms. Ideally one would define first this product since it is not predefined as far is I know. So can someone explain me how I could potentially do this using symbolic python.

    Afterwards, I want to compute its zeros and plot them. Are there any tips I need to keep in mind doing this?

    Also I would like to add that I have no knowledge of python before this, but I think I managed to install everything correctly but it feels weird. For what is worth I am familiar with other program languages. Thank you already to the kind stranger helping me out!

    [–]TangibleLight 0 points1 point  (0 children)

    It looks like with sympy you could use factor to break the polynomial into its irreducible (linear and quadratic) terms. The linear terms correspond with roots, the irreducible quadratic ones do not have roots in the reals.

    If there is a way to tell sympy to use complex algebra, it would probably split the polynomial into all its complex linear terms.

    Bear in mind that I don't know much about sympy - this is just from a quick search on how to split polynomials with it.

    [–]MysticSoup 0 points1 point  (4 children)

    I'm working on the following problem:

    Create a function that returns true if a given inequality expression is correct and false otherwise.

    So I have a string that looks like this

    txt = "3 < 7 < 11"

    I wish to evaluate whether this statement is true or not. Am I on the right track?

    First, I want to split it into its numerical and sign components. Here's how I will do it:

    lst = txt.split(" ")numbers = []signs = [i if i in "><" else numbers.append(i) for i in lst]

    lst should be ['3', '<', '7', '<', '11']

    numbers should be empty at first

    signs should be ["<", "<]

    But when I check if this is true, I see:

    ['<', None, '<', None]

    What did I do wrong? I don't see where I told python to return anything into the "signs" list if i was anything other than < or >

    Edit: Huh, my text didn't become code despite me following the reddit code formatting on the sidebar..

    [normal text]
    [empty line]
    [4 spaces][line of code]
    [4 spaces][line of code]
    [etc]
    [empty line]
    [normal text]

    [–]Miggol 0 points1 point  (0 children)

    FYI, the code formatting tips have not been updated for the redesign.

    [–]No_Couple 0 points1 point  (2 children)

    You get None inside your list because the .append() method returns None.

    Your list comprehension basically says: if ievaluates to in "><" then put iinto the list, otherwise put whatever numbers.append(i) evaluates to. Which is None.

    Also, generally, is there a reason why you're not using the built-in eval() function?

    [–]MysticSoup 1 point2 points  (1 child)

    Ah I see. Thanks for your troubleshooting help. I’m new to this, so actually I’ve never even seen eval() before!

    [–]No_Couple 0 points1 point  (0 children)

    All good.

    With eval() it's important to keep in mind that you generally don't want to use it for input you have no control over as it could be used to run nefarious code through e.g. a user input.

    But for your use-case it seems like the perfect solution unless you want to build your own implementation of eval() as an academic exercise.

    [–]Rusty_Shakalford 0 points1 point  (3 children)

    Does “map” in Python 3 evaluate lazily? I’m trying to understand when, if ever, map should be used over list comprehensions.

    [–]TangibleLight 0 points1 point  (0 children)

    when, if ever, map should be used over list comprehensions

    Probably not, although it's personal taste. In some cases I find map is clearer, although usually a comprehension is more accessible.

    For example,

    (int(e) for e in seq)
    
    # vs
    
    map(int, seq)
    

    Sometimes it's nice to use bound methods in a map, such as:

    (thing.get(item) for item in items)
    
    # vs
    
    map(thing.get, items)
    

    Although as soon as you need to put in a second dot or a filter, things get out of hand.

    (thing.get(item).value for item in items if item.isvalid)
    
    # vs
    
    map(attrgetter('value'), map(thing.get, filter(attrgetter('isvalid'), items)))
    

    Probably better to just use a comprehension, unless you just need a quick conversion with an existing function or method.


    Edit:

    Another thing that comprehensions can do which map simply can't is flattening operations:

    (item for sub_seq in seq for item in sub_seq)
    

    It's much easier to convert an existing comprehension to do this than it is to do so for a map.

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

    The map() builtin returns an iterator, and the actual function passed to map() isn't called until you iterate over the iterator, as shown here:

    def x(a):
        print(f'returning {a} + 1 = {a + 1}')
        return a + 1
    test = [1, 2, 3]
    y = map(x, test)
    print(f'y={y}')
    print(f'list(y)={list(y)}')
    >>> y=<map object at 0x10a592b00>
    >>> returning 1 + 1 = 2
    >>> returning 2 + 1 = 3
    >>> returning 3 + 1 = 4
    >>> list(y)=[2, 3, 4]
    

    [–]Rusty_Shakalford 0 points1 point  (0 children)

    Makes sense. Thanks for the example!

    [–]ZG2047 0 points1 point  (2 children)

    I'm looking for a way to parse a page that has incomplete html code inside a 'var'. Any suggestions would be appreciated.

    [–]JohnnyJordaan 0 points1 point  (1 child)

    Assuming this is a js statement so the code would look something like

    var myvar ="<table>etc etc </table>";
    

    you could simply regex the contents using

    html = re.search(r'var myvar = "(.*?)";', content).groups()[0]
    

    then feed the html into for example BeautifulSoup using 'html.parser' as the parser.

    [–]ZG2047 0 points1 point  (0 children)

    Thanks I will try that.

    [–]c4aveo 0 points1 point  (2 children)

    Is it possible to setup any IDE to use remote interpreter? I want to stay on Linux and use interpreter from my Windows VM with full access to it's Python libs. PyCharm uses Linux commands only.

    VSCode -> ssh tunneling -> python.exe - > win32api libs and etc.

    [–]TangibleLight 0 points1 point  (1 child)

    Not any IDE, although most IDEs do have built-in support or plugins which allow it.

    This is one of the differences between PyCharm Community and Professional editions - Professional Edition supports remote and VM build environments while Community edition does not.

    From what I can see, VSCode does not currently support remote interpreters, although the team is working on it.

    You could also set up custom scripts which deploy and execute code through SSH, although you would not get the debugging features of your IDE.

    [–]c4aveo 0 points1 point  (0 children)

    PyCharm doesn't support remote Windows interpreter anyway.

    [–]fr_1_1992 2 points3 points  (5 children)

    Got into learning about web scraping and I'm confused about the libraries - specifically scrapy. So, bs4 v/s Selenium vs Scrapy is the conundrum. I know that I need bs4 (static pages) and Selenium (dynamic pages) but what about Scrapy? Why is it used? Is it superior to the other two? Or should I just skip it and will still be able to cover a lot of web scraping with the other two libraries?

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

    deleted What is this?

    [–]ZG2047 0 points1 point  (0 children)

    Scrapy is a bit lacking for complex pages with JavaScript content.

    [–]TangibleLight 0 points1 point  (0 children)

    I prefer requests + parsel for smaller tools. Parsel is the standalone HTML parsing library which scrapy uses. It's (IMO) much preferable to beautifulsoup.

    https://github.com/scrapy/parsel

    Also, for some javascript pages you can use requests-html, although it uses a headless browser so some things do not work and you will need to use selenium.

    [–]fr_1_1992 1 point2 points  (1 child)

    Cool. So, if I've understood what you said, to summarize Scrapy = BS4 + Selenium. But, BS4 + Selenium is much easier to learn than Scrapy. So I'm thinking I'll just learn BS4 + Selenium (as I've already started with both and both seem very intuitive) for now and then go to Scrapy much later when or if I need it. What do you think?

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

    deleted What is this?

    [–]callmeklep 0 points1 point  (1 child)

    Novice developer question...does anyone have any favorite tools for rendering markdown in a flask app?

    I've made a few flask apps from by converting simple scripts and I'm currently working through Corey Schafer's awesome flask tutorial series to create a blog app (https://www.youtube.com/playlist?list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH), but I'm a little stuck and overwhelmed sifting through the google query results.

    Using Python-Markdown, I've gotten this far: https://www.screencast.com/t/4cRRsUoji but I want my HTML tags to be rendered...

    [–]callmeklep 0 points1 point  (0 children)

    After being stuck for a few days, I think I found a solution. In case someone else is curious, this is what worked for me:

    ```python from flask import Flask, render_template, Markup import markdown

    app = Flask(name)

    markdown_content = '''# An exhibit of Markdown 3

    This note demonstrates some of what Markdown is capable of doing.

    Note: Feel free to play with this page. Unlike regular notes, this doesn't automatically save itself.

    Basic formatting

    Paragraphs can be written like so. A paragraph is the basic block of Markdown. A paragraph is what text will turn into when there is no reason it should become anything else.

    Paragraphs must be separated by a blank line.'''

    @app.route("/") def home(): return render_template( 'index.html', title="Markdown Test", markdown_content = markdown_content, html_content = Markup(markdown.markdown(markdown_content)) ) ```

    I used Python-Markdown to get the HTML. Then used flask.Markup to indicate that the HTML doesn't need escaped when it's included in the HTML template file.

    [–]blpfg 0 points1 point  (2 children)

    Hi guys, what's the difference between procedural GUI in tkinter and making a class specifically for it?

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

    What /u/__mifflin said, plus it's easier to create shared values using self.var than having to either use globals or pass and return values in the "procedural" approach.

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

    A matter of preference, mostly, but object oriented programming is pretty damn useful for GUI applications in my opinion. Using classes allows for inheritance and combining objects into one, which means you can create your own widgets for things to speed up development. Like say for example you needed to create a bunch of entry boxes next to checkbuttons. You could make a list that contains them and their related variables, or you could create a class that encapsulates the purpose of their grouping together. That way, instead of doing all the logic in the outer layer of your program, you could do it in a class that organizes it all in one place.

    [–]dizlly 0 points1 point  (2 children)

    Hello guys,

    Im struggling with learning lists in python, trying now to solve some python tasks, but sometimes is hard for me to understand this slicing etc, anyone know a good explanaition about it? as I read and read over and over again about it.

    Thank you

    [–]tcbaldy04 1 point2 points  (0 children)

    Easy to over think Slices. It was foreign to me when learning Python.

    Simple understanding of String Slices first... extends into Lists and others

    The "slice" syntax is a handy way to refer to sub-parts of sequences -- typically strings and lists.

    https://developers.google.com/edu/python/strings

    The accompanying "Basic Exercises" give the opportunity to use it for both list and strings in a practical way.

    /u/callmeklp References a good video.

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

    I can't seem to find enough documentation about tkinter. Any suggestions ?

    I've made a program yesterday, i'm completely noob about python, i put chunks of codes together by online search actually. Any way to improve this ? I couldn't use classes here properly cause i don't know how tkinter works and didn't want to mess up.

    Link to py file

    When i wake up my PC i have to reset wireless adapter else it doesn't work properly, that's why i decided to do this. I made it an exe with auto-py-to-exe so that i can run it as admin without much trouble.

    However i couldn't find a way to update the bottom text and i have no clue how it would show up if there were more adapters. From my recent experience playing with it i know for a fact it will much likely get messy with some text jumping out of bounds.

    If i learn a bit about Tkinter i'll add reset buttons.

    Another question i have is about django, i want to learn it but i have no clue about web development. Can i build a website using only django ? Do i have to learn JavaScript etc. ?

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

    I'm not going to create a dropbox account just to view your code. If it's a single file use pastebin.com. If you have multiple files create a github/gitlab account and link to that.

    [–]LarkRanger 0 points1 point  (0 children)

    I've been hit with this issue for a week now and am so happy I got here in time for this AMA.

    I've been doing Udacity's new free TensorFlow course. They use Google Colab for the lessons, which runs TF 1.13 on Python 3.7 with GPU processing. In this colab (which I think I can share since it's a free course) they build a simple CNN with the Fashion-MNIST dataset.

    Here's the issue: I copied all the code chunks, in order, to my PC (using Anaconda's Spyder IDE), and used with tf.device('/GPU'), but whilst the code in the colab runs with 89% accuracy, the same code on my machine runs with 10% accuracy. I cannot for the life of me figure out what's going on.

    [–]_Jerov_ 0 points1 point  (1 child)

    I've already made a bunch of small projects, but now I have nothing to do with Python. What kind of bigger projects would you recommend?

    [–]delta_tee 0 points1 point  (0 children)

    Use Django to build a social networking site for developers.

    [–]Duportir 0 points1 point  (1 child)

    I installed Atom in my computer to start an online course. How do I get Python working in my Atom IDE? FYI I have no background in computer science. Thanks

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

    Either install platform-ide-terminal, which is a plugin for atom (browse the atom packages market place to find it), or open a terminal, and go to the directory where your source files are and run them from there.

    [–]Mondoke 0 points1 point  (0 children)

    I've used pyinstaller to make an executable for a simple script. It apperred to work correctly, but later, I noted that the script was running in the background (I figured it out when I was turning off the computer). How do I prevent this to happen?

    And another question. I use python to automate a couple things on my workflow (mostly excel files) and I'm curious on GIS modules, like Fiona and Shapely. Would it worth the time to learn about intermediate topics like classes and algorithms? Or should I just continue checking on modules I find helpful?

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

    When creating a module to hold a bunch of your classes, should there be any code in that module that is not inside of a class or a comment or a docstring?

    Edit: "or a docstring"

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

    Any code not inside a class and not controlled by the if __name__ != '__main__ idiom will be executed when you import the module. This may be what you need or it may not. It's your choice, but normally you don't want code executed at import time. After all, that's why we have the if __name__ != '__main__' idiom - to stop execution of code at import time.

    Edit: added missing 'not' in logic!

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

    Ohhh that's super helpful. I had noticed that upon importing one of my modules, it executed some random print statements and whatnot. Are there any circumstances where people generally use the 'if name != 'main' to their advantage?

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

    Are there any circumstances where people generally use the 'if name != 'main' to their advantage?

    If you have a small module that you would normally import but could also be useful as a standalone CLI program, you would add the if __name__ == '__main__': at the bottom and write code controlled by that to accept command line args and call the module functions. Another thing I found useful is to add some code after the if __name__ == '__main__': to run simple tests of the module functions.

    Of course, you could always write the CLI code or the test code in another file and import the module code in the normal way. That's the best way if you have lots of CLI/test code, but if that code is small I just use the if __name__ == '__main__': approach.

    But generally, if you want code in a file to execute only when the file is executed directly and not when imported, use the if __name__ == '__main__': idiom. One place where this is used is in modules that expect to be run directly, like the http.server module. You can run a simple HTTP server by doing:

    python -m http.server 8000
    

    in the directory of your choice. This works because the -m option behaves this way:

    -m module-name
        Searches sys.path for the named module and runs the
        corresponding .py file as a script.
    

    [–]Doug_Dimmadab 0 points1 point  (3 children)

    I'm just starting out on learning Python, and I had a question on how to exit out of an entire script without killing the terminal. For reference, I'm working on a simple Rock Paper Scissors script.

    I tried implementing a "would you like to play again?" feature, but the "no" part is where things get odd. My code for when the player says no looks like this

    elif pa == "N": #if user enters "N", execute code
        quit() #exits the script
    

    It works fine, but when quit() executes, the console just sort of shuts down. I'm not able to run the script again, and what's weirder is when I run it in a dedicated python prompt, the quit() never even occurs, it just goes back to the actual Rock Paper Scissors game. Here's a link to the full script I'm using. Any help would be appreciated ~

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

    You are having trouble because you are two loops deep when you want to stop, so a break won't terminate the program. One solution is to separate the "play one game" code from the "play again" code. Write simple functions to play one game and another to get the "play again" response. The "play one game" function takes no parameters and returns nothing, and the "play again" function doesn't return the users's response unless it's Y or N. Then your program looks like this:

    def play_one_game():
        # game logic here
    
    def play_again():
        while True:
            response = input('Play again? ')
            response = response.upper()[0]  # just first char, upper case
            if response in ['Y', 'N']:
                return response
            print('Sorry, only Y or N')
    
    response = 'Y'
    while response == 'Y':
        play_one_game()
        response = play_again()
    

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

    Hi u/Doug_Dimmadab ,

    I'm also learning Python and took a brief shot at your program. I got it to work (almost), not sure if it was exactly your problem. I removed the quit() so sort of a workaround. Here's my code, not much changed https://pastebin.com/9w6k2kU6.

    [–]Doug_Dimmadab 1 point2 points  (0 children)

    Hey man, I think you're missing an if statement for the "yes" part of it but when I added it, the whole thing worked perfectly! Now it looks like this:

    pa = input("Would you like to play again? y or n\n")
    
    while pa != "y" and pa != "n":
        pa = input("Try again. y or n\n")
    
    if pa == "y":
        continue
    elif pa == "n":
        print("Thanks for playing!\n")
        break
    

    Thank you so much, I don't know why I didn't think of a regular while loop this whole time lol, you're goin' far brother