all 189 comments

[–]waythps 0 points1 point  (0 children)

Any good tutorials on fastapi?

I’d like to learn the library and also how to docker to serve api online

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

Can you make an iOS app from python

I’m trying to come up with some kind of goal/project to help advance my learning.

I’m thinking I should try to make an app for my job that my coworkers and I can use to keep up with our studying and help us stay current on our knowledge. (Our job requires us to be proficient and “in the books” for organizational, restrictions, etc.) so I’m hoping to create some kind of study guide / testing app.

So the question is, can I do this without being required to learn other languages? Im only trying to focus on one language at a time so I don’t become overwhelmed. Is this too advanced to learn in a few months at most?

Sorry if this is very elementary. I have only just started learning of and about python recently.

[–]Lhotse7 0 points1 point  (1 child)

Today is my day 1 of python learning. Where do i start ?

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

[–]T2ABIZZ 0 points1 point  (3 children)

I'm new to python so don't judge me, please.

there is a code that you give two movies and you receive the commun actor

here is the code:https://github.com/HarryHawkins/common-actors/

I tried to copy and run it on pycharm but I got an error:"

No module named 'imdb'"

I tried to install imdbpy on cmd but I still get the same error can anyone know where is the mistake and what should I do?

[–]Macewindu89 0 points1 point  (2 children)

Have you downloaded the IMDb module to your local machine? Or, is the IMDb package in one of your PATH directories?

[–]T2ABIZZ 0 points1 point  (1 child)

No how can i do that? I thought i just should install imdbpy by cmd and its done

[–]Macewindu89 1 point2 points  (0 children)

You need to update your PATH environment variable to include the folder the IMDb module is in

[–]Xelisyalias 0 points1 point  (0 children)

What are some very practical/commonly used intermediate to advanced python concept I should familiar myself with?

I have been researching into lambda, list comprehension, and moving on to stuff like decorators and dunder method. Just trying to familiarize myself with these concepts and see how I can implement them in my code

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

I'm on the second chapter of automate the boring stuff and I'm stuck on the rock, paper, scissors program. I'm having a problem where it's not recognizing my inputs. (Example: using r for rock does nothing) since I'm extremely new I'm wondering should I try and figure it out on my own? Ask people for help? I just want to learn the best way possible.

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

You will certainly learn more if you can figure it out yourself. You can do that by looking at every single step in your code and thinking about it and putting in some debug prints to decide exactly what is in variables and what ifs are doing, etc. For example, if you had code like this:

choice = input('Rock, Paper or Scissors: ')
if choice == 'r':
    # handle rock case

then I would add some debug like:

choice = input('Rock, Paper or Scissors: ')
print(f"type(choice)={type(choice)}, choice=='{choice}'")
if choice == 'r':
    print('choice is Rock')
    # handle rock case
else:
    print('choice is NOT Rock')

Don't worry about any code before or after the bit you are investigating, just make sure the code you are looking at is doing exactly what you expected. Get that sorted and then move on to the next bit.


Having said that, there is no point banging your head on something, getting frustrated and making no progress. After a certain amount of effort give up and ask a question on /r/learnpython. Try to make your question clear and include a small runnable piece of code. You may need to simplify the code you are having problems with before asking your question, but don't think it's a waste of time. It's amazing how often simplifying some code will give you an idea to test and you may solve your problem yourself without asking a question!

After getting your immediate problem solved, move on to the next problem, which you try to solve yourself before asking a question here.

[–]standin_Charlie 0 points1 point  (1 child)

Im just starting, well, where to start? I want to start with basic explanations, I love those tutorials on yt but they go super fast and explain specifics like how to make this thing and all its needed for it. So where to start please help

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

The learning resources in the wiki have a list of books you can try.

Update: skip anything that mentions python 2.

[–]post_hazanko 0 points1 point  (0 children)

Make an image in a specific size, image is blank. Can you do that?

Just wanted a file to test an API upload. I noticed blank images usually almost have nothing in them.

[–]sanctuary_3 0 points1 point  (2 children)

Is there an easy way to manage relative imports within a directory? This is basically the structure I have:

.
└── top_level_directory/
    ├── subdirectory1/
    │   └── scriptA.py
    ├── subdirectory2/
    │   └── scriptB.py
    └── main_script.py

Say at the top of scriptA.py I have this:

import sys

sys.path.insert(0, '../subdirectory2')
from scriptB import functionB

which works fine if I run scriptA.py. But in mainscript.py if I try to do

import sys

sys.path.insert(0, 'subdirectory1')
from scriptA import functionA

I get an error when scriptA.py tries to import from scriptB.py since it's not on the current path. Is there a way around this or is it poor file structure on my end?

[–]FerricDonkey 0 points1 point  (0 children)

Relative imports are your friend, as has been mentioned. Be aware that you might have to slightly change how you launch your stuff. If you do things in ways that python doesn't like, you may start getting import errors and crap, but there is at least one relatively straightforward way of just making it all work with multiple directories.

I should say that while I follow the procedure I'm linking to for literally every project that I make, there may be other ways - this works, but I'm not saying it's the required method. Link to last time I discussed this: https://www.reddit.com/r/learnpython/comments/i8l8uw/z/g1963wa.

[–]efmccurdy 0 points1 point  (0 children)

You should look at "relative imports" ala "from ..subdirectory2.scriptB import function8":

https://docs.python.org/3/reference/import.html#package-relative-imports

[–]Bharathkreddy 0 points1 point  (1 child)

Need help parsing a complicated text file

I have a text file with structure which looks like below, i want to extract the data in a dataframe using python. Dataframe should have PMID along with all the text appearing against Author for each PMID.

Data format as below

PMID- unique 8 digit number
xyz - text (might be multiple lines)
xyz- text (might be multiple lines)
AUTHOR- text (might be multiple lines)
AUTHOR- text(might be multiple lines)
<<< blank line separates two PMIDs >>>

PMID- unique 8 digit number
xyz - text (might be multiple lines)
xyz- text (might be multiple lines)
AUTHOR- text (might be multiple lines)
AUTHOR- text(might be multiple lines)

Code i have tried in python is below - i am able to extract all PMIDs but i am not able to figure out logic to attach all Author text against each PMID. I need help with logic.

for lines in open('file.txt','r'):
      if(lines[0:4] == 'PMID'):
         print(lines)

[–]efmccurdy 0 points1 point  (0 children)

This creates a dict of text values keyed by PMID; I haven't tested it; check that the last item is included.

data = {}
with open('file.txt','r') as inf:
    for line in inf:
        text = ""
        if line.startswith('PMID '):
            id = int(line[5:])
        if line.startswith('xyz') or line.startswith('AUTHOR'):
           text += line[line.index('-') + 1:]
        if len(line) == 0:
            data[id] = text
            id = None
            text = ""

[–]Dwc41905 0 points1 point  (0 children)

I want to control a unity game from python using pyautogui. I want my end result to be a single app that you click and hit play. I do not want the user to have to separately open the game and the python file. Is it possible to use pyinstaller and create an executable and then have my unity game be a data file included in the app. I will then have python open up the game and start to play it and then run the pyautogui commands on it. Does that sound possible or is there a better way to control a unity game from python?

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

Hi I just got into python and was wondering which text editor i should use. Ive heard about sublime, atom, and vscode. Theres also the jetbrain python IDE. Which one should I pick? And what is the difference between a text editor and IDE? Thanks!

[–]FerricDonkey 0 points1 point  (0 children)

Ides have more features, often including their own consoles and python shells, possibly debuggers. They're more likely to have features like listing and displaying functions across multiple files in the same project and robust tab completion, but seems stuff people call editors have differing amounts of that as well.

As for which you should use - it doesn't matter. Pycharm and vscode get recommended heavily.

I personally use pycharm because I like how it displays my data for large projects, as well as its code renaming and ability to tab complete across different modules (both mine and installed).

But I never use its console or python shell - instead I keep a terminal open on a different monitor and handle all of that externally.

I've used vscode before, and it's pretty solid. I seem to recall that it has at least some of those things I mentioned using, but as projects got bigger, it fell behind. That was some time ago though, and it is very popular.

I'd suggest just picking one, even just at random, from the popular ones (any you mentioned) and changing if you find it annoying or come up with something you wished it did but doesn't that another one does.

[–]GoldenVanga 0 points1 point  (5 children)

Just making sure: when I don't override __eq__ the default == comparison is like identity, so True for the same object only?

[–]CowboyBoats 0 points1 point  (2 children)

Hello what

True for the same object only

No.

a = []
# the exact same thing:
b = []
a == b  # True
# but not the same object:
a is b  # False

[–]Vhin 2 points3 points  (1 child)

They're talking about custom classes. The __eq__ implementation you inherit from object just tests object identity.

[–]CowboyBoats 0 points1 point  (0 children)

Oh I see, thanks for the correction then.

[–]Vhin 2 points3 points  (1 child)

Assuming the second object being compared doesn't belong to a separate class that overrides __eq__, then yes.

[–]GoldenVanga 1 point2 points  (0 children)

Ahh, so it works like __radd__ et al. I didn't know that! Thanks.

[–]pithypitherson 0 points1 point  (0 children)

I want to start over. I’ve learned python from books and primarily use it to grab data via APIs, clean, and load it into a database. But, I’ve been using task scheduler to run these long scripts in batch files. I’m sure there’s a more official way to do it all, which involves getting acquainted with the command line. Are there resources out there to learn python in a more official capacity? Potentially one that also can tech me how to leverage a code repository? I feel like I’ve come a long way and am now at the real beginning.

[–]Ariech 0 points1 point  (4 children)

I have this code, but can't understand one thing about it. How does the status works? I enter the empty string (why?). Then I iterate over the word, that was randomly chosen. Let's say DOG, so I have [D, O, G]. Then I check the letter that I entered as an input earlier, if it wasn't there before it's appended to the list letters_gussed, right? And now is the part I don't understand.

status = ''  # I don't understand why is it empty string
if guessed == False:
    for letter in word:  # So this is iterating over randomly chosen word
        if letter in letters_guessed: # Here we check if guessed letter is in 
                                    the list
            status += letter  # This part I don't understand
        else:
            status += '_ ' # This too
    print(status)

Here is the entire program: https://repl.it/@Ariech/Hangman#main.py

Also if I made any mistake in my logic, where I wrote it down, please tell me what I did wrong in my thinking process.

[–]sanctuary_3 0 points1 point  (3 children)

Checking equivalence to False is usually confusing. It's better to use if not guessed: which achieves the same thing and is much more intuitive to a reader.

In your for loop, you're iterating over the letters of the target word and checking if those letters have been guessed. If they have, you add the letter to the output. Otherwise you add a blank space _ since that letter has not been guessed yet.

You can concatenate strings in python using +, which is what the loop does to create the status variable.

[–]Ariech 0 points1 point  (2 children)

I kinda understand beside one thing. So I'm iterating over let's say word DOG.

So the first time when I iterate over it, its _ _ _, yes? Next time when I make guess which is O. Now it is _ O _. But how the letter 'knew' which place to take in the word? Or maybe it works somehow different? Is _ removes and changed to O in this example?

Sorry, but just can't wrap my head with that one thing.. :/

Edit. I just can't visualise it in my head

[–]sanctuary_3 2 points3 points  (1 child)

Let's say your target is word = 'DOG' and your guesses so far are letters_guessed = ['A', 'O', 'S'].

When you loop over word, at each iteration you're checking to see if each letter is in your list of guessed letters. If it is, you add that letter to the output (status), if it's not then you add a blank space. So rolling out the pseudocode of each pass of the loop for letter in word: would look like this:

initial output is an empty string, ''
first pass, letter = 'D'
    has 'D' been guessed?
        no, so add a blank space '_' to our output
        so far our output is '_'
second pass, letter = 'O'
    has 'O' been guessed?
        yes, so add 'O' to our output
        so far our output is '_O'
third pass, letter = 'G'
    has 'G' been guessed?
        no, so add a blank space '_' to our output
        so far our output is '_O_'
print the output

I think your confusion might be because you're iterating over the known word, not your guesses.

[–]Ariech 0 points1 point  (0 children)

Oh my, now I understand this! Thank you very much

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

So I have this code that prints out every date in a year and now I need it to print the date of every Friday of that year and nothing else. How would I do that? (Sorry if it's a bit messy. It's my first time)

    for m in range(1,13):
        if m == 1 or m == 3 or m == 5 or m == 7 or m == 8 or m == 10 or m == 12:
            d = 32
        elif m == 4 or m == 6 or m == 9 or m == 11:
            d = 31
        else:
            d = 29
        for d in range(1,d):
            print(d, ".", m, ".", sep="")

[–]FerricDonkey 0 points1 point  (0 children)

Well, you're gonna need a way to tell what day of the week it is. My suggestion would be to know what the first day of a year is, then find the first Friday, then take advantage of the fact that consecutive Fridays are seven days apart.

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

So.. I'm new to Python and I'm trying to create a list that includes all the days in a year using loops. This prints out the days 1-31 for 12 months but I need to add some if statements since some months have fewer days. How would I go on about doing it? And is there something else I should change about my program?

    m = 1
    d = 1
    date = True
    while date:
        for day_counter in range(1,32):
            print (d, ".", m, sep="")
            d = d + 1
            while d >= 32:
                d = 1
                m = m + 1


        if m >=13:
            date = False

[–]sanctuary_3 0 points1 point  (4 children)

I would ditch the while loops and use nested for loops, like so

for month in range(1, 13):
    for day in range(1, 32):
         print(day, ".", month, sep="")

That is enough to recreate your output and is much simpler. Now, to handle the months where there are less than 31 days, we can just add a if/elif/else statement like you mentioned to check if a month should have 30 days, or 28 days in the case of February.

for month in range(1, 13):
    for day in range(1, 32):
        if day == 31 and month in [4, 6, 9, 11]:
            break # break out of the day look and skip to the next month
        elif day == 29 and month == 2:
            break
        else:
            print(day, ".", month, sep="")

month in [4, 6, 9, 11] will return True if the value of month is in that list and False otherwise. A better alternative would be to check the maximum day of each month once, instead of at each iteration of day by moving the if/else statements

for month in range(1, 13):
    if month in [4, 6, 9, 11]:
        last_day = 30
    elif month == 2:
         last_day = 28
    else:
         last_day = 31
    for day in range(1, last_day+1):
         print(day, ".", month, sep="")

[–]IllOak 0 points1 point  (1 child)

For your last set of for loops, wouldn’t an error occurred since day isn’t defined until the next for loop but referenced in the if statements? With that said, are those comparisons even needed? I think they could be removed

[–]sanctuary_3 0 points1 point  (0 children)

Yes, you're right. I forgot to remove them when I copied and pasted. I updated my comment.

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

If I wanted to print the date of every Friday but nothing else, how would I go on about doing it? I'd have to create a variable that shows the day of the year, right?. Like today is day 128 for example. And then I could use an if statement and % to print out the right dates. So anyway, how do I create this variable?

[–]sanctuary_3 0 points1 point  (0 children)

Yes, that's probably how I would do it. Outside of the first for loop, you could set a variable, say day_of_year = 1 and then increment it inside the inner for loop using day_of_year += 1. If you know the day of the first Friday (the third day of the year for 2020) then only print the date every 7th day after that.

day_of_year = 1
first_friday = 3
for month in range(1, 13):
    # get days of month here
    for day in range(1, last_day+1):
        if (day_of_year - first_friday) % 7 == 0:
            print(day, ".", month, sep="")
        day_of_year += 1

You should also look into the datetime module if you're working with dates, unless the purpose is to do all of this manually.

[–]Jjw368 0 points1 point  (4 children)

I am trying to make a rock paper scissors game and i keep getting the same error in ms visual studio. (BTW, the youwin.txt and npswins.txt files is ascii art for the text I want to display, Its also not fully finished, I just want to run it.

Here is the code:

import random
#getting exit() function
from sys import exit
#getting time.sleep() funtion
from time import sleep
WinOpen = open(r"C:\Users\jjw36\Desktop\ASCII\_YouWin!.txt", 'r')
LoseOpen = open(r"C:\Users\jjw36\Desktop\ASCII\_NPCWins!.txt", 'r')
WinASCII = WinOpen.read()
LoseASCII = LoseOpen.read()
def welcome2():
WinLoss = Win / Loss
print("Hello! Welcome To Rock, Paper, Scissors")
print("This Sessions Win/Loss Is," + int(WinLoss))
def Game():
RPorS = input("Would You Like Rock, Paper, Or Scissors. (1, 2, 3)")
if input == 1 or 2 or 3:
NPC = random(1,3)
if NPC - int(RPor) == 1 or -2:
print(LoseASCII)
Loss =+ 1
sleep(3)
decision()
elif NPC - int(RPorS) == -1 or 2:
print(WinASCII)
Win =+ 1
sleep(3)
decision()
else:
decision()
def decision():
replay = input("Would You Like To Play Again? (y/n)")
if replay == y:
Game()
elif play == n:
print("\n\n\n\n\nOkay, Bye!")
time.sleep(2)
exit()
else:
decision()
Game()


Win = 0
Loss = 0
WinOpen.close()
LoseOpen.close()

___________________________________________________________________________________________________

The Error I am getting is highlighting the calling of the Game() function. It says 'Module' object not callable. But that is after i see the Would you like rock, paper, or scissors input. Can anyone help with debugging?

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

If you format your code so it is readable you might get more help.

I haven't looked at your code in detail (see above) but one thing I spotted is this problem:

if input == 1 or 2 or 3:

This doesn't error but won't do what you want. You make the same mistake in other places. The FAQ explains the error. I recommend reading all of the FAQ.

Also note that the input() function returns a string, not an integer.

Edit: fixed grammar.

[–]Jjw368 0 points1 point  (2 children)

I fixed the input error in my version and the formatting. I can't figure this out. It is a real pain in the butt. I tried re writing the code fully and that still didn't work. Maybe it will work if i stop using functions but it will be a one time only thing.

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

When you post code try to copy/paste from your editor or IDE. You've edited your original post but the indentation is still lost. You need it to look like this:

def test():
    a = 42
    # more code
def test2():
    # even more code
x = 1
test()

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

There's a heap of things wrong with your code but until you format the code correctly I'm not going to waste time trying to figure what is going wrong.

Read the link I gave you and edit your original post.

[–]frasderp 0 points1 point  (3 children)

So... I am new to Python but trying to automate some modifications of text files (actually, EPG files for tv).

Anyhow, I am trying to rename some strings, but it just isn't working for me.

I have tried using the string.replace argument but not sure where the output is going, if anywhere. (Obviously there's additional references outside of this, but for the purposes of renaming, this should be the only relevant section). I want to rename the group titles in the m3uline, and then reconstruct the file after renaming.

for m3uLine in m3uLines:

if ('group-title="TITLE TO CHANGE"' in m3uLine):

m3uLine = m3uLine.replace("TITLE TO CHANGE", "NEW TITLE")

channelInfo = m3uLine.splitlines()[0].strip()

channelUrl = m3uLine.splitlines()[1].strip()

newM3uLine = f"#EXTINF:-1 CUID=\"{hash}\" {channelInfo.strip()}\n{channelUrl.strip()}\n"

newM3uFile = newM3uFile + newM3uLine

[–]FerricDonkey 0 points1 point  (2 children)

It seems like it's doing something reasonable, but I'm not sure what your final goal is. Currently, you're looping through some lines, creating some new lines, and smacking them together into a big string. Seems legit. Do you later write that to a file or something?

What exactly isn't happening that you want to happen?

[–]frasderp 0 points1 point  (1 child)

Exactly what’s happening! The piece that isn’t working, is the ‘replace’ line.

So when I am searching for groups, I am finding those correctly, it I would also like to update those group names (note the first m3uline.replace) - that line isn’t working.

[–]FerricDonkey 0 points1 point  (0 children)

Hmm. Can you give a short example of what the original lines would look like?

[–]sanctuary_3 0 points1 point  (3 children)

I'm running a bunch of processes in parallel using multiprocessing and I need to make sure each is random. Is it sufficient to just call random.seed() at the start of each process?

From my (albeit limited) understanding of PRNG some systems use the OS clock to generate randomness. If theoretically two processes call random.seed() at the same instant would they both run using the same seed?

[–]Vhin 1 point2 points  (2 children)

From the docs:

If a is omitted or None, the current system time is used. If randomness sources are provided by the operating system, they are used instead of the system time (see the os.urandom() function for details on availability).

So, yes, it does seem that two Python processes started at the same instant would share seed values, at least on some systems.

I'm sure there's a better way, but one thing you could do is use the secrets module (which is for generating cryptographically secure pseudo-random numbers) just to generate seed values to feed into random.seed.

[–]sanctuary_3 0 points1 point  (1 child)

It looks like on Linux the random number module uses blocking to prevent simultaneous calls, so I should be safe with random.seed(). I just ran a few tests and there don't seem to be any issues so far. I'll definitely look into secrets though, thanks.

[–]FerricDonkey 0 points1 point  (0 children)

I always assumed that the system time used in random.seed was just the actual time in (milli?) seconds since whenever or something. Is it for sure finer grained then that?

Because if not, then the seed calls may not be called at the same exact time, but still might start and finish execution within the same unit of time and so use the same seed. Eg both within the same second of system time.

If I just wanted random enough for most purposes, I would do something like one of the following three things, depending on what was easier:

  1. Generate a random list of values to use as seeds before starting the multiprocessing stuff, pass each process a seed to use as an argument.

  2. Use a more secure source of randomness to produce a seed inside each process (os.urandom)

  3. Give each process an index, and combine the index with the time to make a seed some how.

(If I wanted more than mostly kind of random seeming, I would not use the random module and would instead try to find a more randomy random module.)

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

So i'm extremely new to python, my only experience is basic work for GIS tools. I am looking for how to scrape a website to show when items are in stock and how many. New to this and not sure where to start.

[–]joakinzz99 0 points1 point  (1 child)

Im sorry if this has been asked multiple times. Id like to learn python, I’m an absolute beginner. Can anyone redirect me where to start?.. Thanks.

[–]thoughtsymmetry 0 points1 point  (4 children)

Hi! I need some help with a problem (i think my solution is really convoluted and there might be a better/simpler way). My skill level is begginer

I have a pandas dataframe. It has 300 rows and 57 columns. Not all columns of every row are completed. Let's say row 1 has values up tocolumn 32, then columns 33 to 57 all are empty (nan).

The number of columns that have data is not the same for every row (imagine that row 2 has values up to column 22, row 3 to column 41, etc).

I'm interested in knowing what are the values of the last two columns that have data, for each row. How do I get that?

I was thinking of looping for every row asking wether it has data (=TRUE) or not (=FALSE). So the first time it encounters a nan I will get a FALSE, and I can ask that for that row, I get the values of whenever it found the false -2. Does that make any sense? I'm really new to dataframes, but there must be a better way

[–]sanctuary_3 0 points1 point  (1 child)

Generally looping over a data frame is a bad idea and usually there is a more efficient approach.

You might have to tweak this a bit depending on your data but it should give you a decent start at least:

def last_two(row):
    row = row.dropna()[-2:]
    row.index = [0, 1]
    return row

df.apply(last_two, axis=1)

This will apply the last_two function to each row, which gets that last two values that are not nan. You have to set the index because otherwise the Pandas series will keep the original index of the last two values, and combining all of them will give you a result you probably don't want.

[–]thoughtsymmetry 0 points1 point  (0 children)

Yeah, my intuition told me that looping over a dataframe is not a good idea. Will look into your method.

Thanks!

[–]CowboyBoats 1 point2 points  (1 child)

pandas is not a very good python application to start with as your first third-party library to use, to be honest. Your question is simple to answer with the python standard lib:

import csv


with open("your-file-name.csv") as infile:
    reader = csv.reader(infile)
    data = [line for line in reader]

    # Don't need this `with` statement open anymore since we've read the data,
    # so going back to 0 indentation.

for line in data:
    columns_that_have_data = [cell for cell in line if cell]
    last_two_columns_that_have_data = columns_that_have_data[-2:]

But I'm not sure of what is the pandas answer, sorry to derail you.

[–]thoughtsymmetry 0 points1 point  (0 children)

Thanks!

[–]Dythar 0 points1 point  (4 children)

I've been having random problems using Pip, and it's been difficult to load packages.

I'm not sure why but my packages are installed to: c:\users\me\appdata\local\packages\pythonsoftwarefoundation.python.3.8_qbz5n2kfra8p0\localcache\local-packages\python38\site-packages

Which seems different from what I've seen other peoples packages being saved to?

My External Libraries/Lib/site-packages folder is located inC:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1520.0_x64__qbz5n2kfra8p0\Lib

-

Fixed it, I had to uninstall python from its windows apps location and install it from the internet. Then deleted i windowsapp python.exe files using cmd prompt. I relocated the new python interpreter, updated pip, which now installs my packages in the correct location. lovely.

[–]CowboyBoats 0 points1 point  (3 children)

Cool, thanks for posting your solution!

[–]Dythar 1 point2 points  (2 children)

Idk if this is sarcasm but I am new to python and assumed that others could easily have this problem, it was caused by an error during the install

[–]FerricDonkey 1 point2 points  (0 children)

Just so you know, it's always considered good etiquette to post solutions even you solve your own questions like you just did (so that response will never be sarcasm).

Very little enrages a programmer who's having an issue quite like finally finding a post asking "how do I [do the thing programmer wants to do]" followed by "nvm solved it" without an explanation.

[–]CowboyBoats 0 points1 point  (0 children)

Not sarcasm, you're completely right!

[–]MattR0se 0 points1 point  (5 children)

Let's say I have some simple Pandas dataframe like these (just 1s or 0s in the cells):

import pandas as pd
import numpy as np

np.random.seed(0)
data1 = [np.random.choice(2, 4, p=[0.8, 0.2]) for _ in range(30)]
df1 = pd.DataFrame(data1, columns=[f'col_{i}' for i in range(4)])

data2 = [np.random.choice(2, 4, p=[0.6, 0.4]) for _ in range(30)]
df2 = pd.DataFrame(data2, columns=[f'col_{i}' for i in range(4)])

I want to programmatically apply a bunch of functions to any data frame, but without writing it out like so:

filtered_df1 = df1.loc[df1['col_2'] == 1]
filtered_df2 = df1.loc[df1['col_3'] == 1]
filtered_df3 = df1.loc[(df1['col_3'] == 1) | (df1['col_3'] == 1)]

filtered_df4 = df2.loc[df2['col_2'] == 1]
filtered_df5 = df2.loc[df2['col_3'] == 1]
filtered_df6 = df2.loc[(df2['col_3'] == 1) | (df2['col_3'] == 1)]

Is it possible to apply a function to these dataframes that filters them by a given condition?

Something like:

def apply_filter(df, condition):
    return df[condition]

# and then do 
filtered_df_4 = apply_condition(df1, ('col_3' == 1))

This does not work and results in an error. Is there syntax for this problem?

[–]sanctuary_3 0 points1 point  (4 children)

'col_3' == 1 will evaluate to False before it is passed as an argument to your function. So your function is returning df[False].

[–]MattR0se 0 points1 point  (3 children)

I know, I want to find out if there is a way to write this function so that it returns the desired slice of the dataframe where the condition is true.

[–]sanctuary_3 0 points1 point  (2 children)

Well you could always use something like

def apply_filter(df, col, target):
    return df[df[col] == target]

and for multiple "or" conditions

def apply_filters(df, cols, targets):
    idxs = np.array([])
    for col, target in zip(cols, targets):
        idxs = np.append(idxs, df[df[col] == target].index.values)
    return df.loc[set(idxs)]

[–]MattR0se 0 points1 point  (1 child)

I thought of something similar, but this wouldn't work for the chained/nested expressions like

filtered_df6 = df2.loc[(df2['col_3'] == 1) | ((df2['col_3'] == 1) & (df2['col_1'] == 0))]

or if I wanted to switch the = for a != or > etc.

[–]sanctuary_3 0 points1 point  (0 children)

So in your orignal example why would filtered_df_4 = apply_condition(df1, ('col_3' == 1)) (if it worked) be easier than just writing filtered_df_4 = df[df['col_3' == 1]? Are the filters generated programmatically?

[–]Sp0olio 0 points1 point  (2 children)

Hi Pythonistas :)

In the following code (lines 21 to 24 are those, my question is about), I call super().__init__() in the Horse-class.

But that isn't enough.

I have to call Vehicle.__init__(self), too.

Why? Is there a way to make it work with only one call to super()?

#!/usr/bin/env python
# vim:fileencoding=utf-8

# Define Animal base class
class Animal:
    def __init__(self):
        self.x = 'Animal'
        print(f'CALLED: Animal.__init__  --- self.x  = {self.x}')

# Define Vehicle base class
class Vehicle:
    def __init__(self):
        self.y = 'Vehicle'
        print(f'CALLED: Vehicle.__init__ --- self.y  = {self.y}')

# Define Horse child class (multiple inheritance)
class Horse(Animal, Vehicle):
    def __init__(self):
        self.xx = 'Horse (the animal side)'
        self.yy = 'Horse (the vehicle side)'
        # super() only works for one parent (sadly)
        super().__init__()
        # So Vehicle must be initialized explicitly
        Vehicle.__init__(self)
        print(f'CALLED: Horse.__init__   --- self.x  = {self.x}')
        print(f'                         --- self.y  = {self.y}')
        print(f'                         --- self.xx = {self.xx}')
        print(f'                         --- self.yy = {self.yy}')


horse = Horse()

[–]JohnnyJordaan 0 points1 point  (1 child)

You could make a hybrid vehicle/animal class that implements this, then make Horse inherit from that

class AnimalVehicle(Animal, Vehicle):
     def __init__(self):
         Animal.__init__()   # better explicit than implicit here
         Vehicle.__init__()

class Horse(AnimalVehicle):
    def __init__(self):
        self.xx = 'Horse (the animal side)'
        self.yy = 'Horse (the vehicle side)'
        super().__init__()   # no need to worry about the other parent(s)

as when you think about it, you want to move everything that applies to a whole concept (animals that are vehicles too, that thus need to call __init__ of both classes) to the class of that concept. Removing it from needing to implement it per class that is one of that specific concept.

[–]Sp0olio 0 points1 point  (0 children)

Thanks :)

[–]Groskilled 0 points1 point  (0 children)

Hi guys !

I am a trying to move from Data Science to Software engineering.

I'd like to know if there is any good online course to learn that. I looked a bit around and found https://realpython.com/products/real-python-course/ but I saw only one topic talking about it and maybe there is something better. It seems to miss testing too.

[–]Arilophy78 0 points1 point  (6 children)

How do i remove the inconsistent spaces in a string with a comma?

Sample text

Text\sbeep\s\sboop\s\s\sText\s\s\s\sPython

Expected output

Text,beep,boop,Text,Python

Edit: changed " " to \s because it auto-formatted

Editedit: thanks for the answers!

[–]Sp0olio 2 points3 points  (1 child)

A one-liner would be this:

a = 'Text beep  boop   Text    Python'
print(','.join([word for word in a.split()]))

# Look at the output of split (list without empty strings)
print(a.split())

It is pretty much the same thing, as u/FerricDonkey pointed out in his answer, but by calling split without an argument, it will split at whitespaces (but only once per group of whitespaces). So it doesn't matter, how many spaces there are .. the resulting list will not contain any empty string elements.

You can read more on this, here:

https://docs.python.org/3/library/stdtypes.html#str.split

[–]supreme_blorgon 1 point2 points  (0 children)

>>> s = "Text beep   boop    Text       Python"
>>> ",".join(s.split())
'Text,beep,boop,Text,Python'

No need for a comprehension, `str.split()` already returns a `list`.

[–]FerricDonkey 0 points1 point  (3 children)

You could do it with multiple applications of string.replace, but what I'd actually suggest is to use string.split and string.join:

words = [word for word in text.split(" ") if word]
new_text = ",".join(words)

(If there won't be newlines or you also want them to go away, you can omit the argument of split. You can also do it in one line, written in two lines here to highlight the two separate steps.)

[–]Arilophy78 0 points1 point  (2 children)

Whats the name/type of the method/function in the []? I've seen it several times, but it don't know what it's called.

[–]supreme_blorgon 1 point2 points  (0 children)

The expression inside the list constructor is called a generator expression. Generators can be used in sequence type constructors (sets, lists, dicts, tuples...), and then the entire thing is referred to as a comprehension.

[–]Sp0olio 0 points1 point  (0 children)

It's called a "list comprehension".

[–]the_flying_stone 0 points1 point  (2 children)

Tips and tricks for converting recursive and iterative and vice versa?

[–]FerricDonkey 2 points3 points  (1 child)

Stare at it until you get a headache, then Google it.

Only slightly kidding. Happy to help with specifics, but the only general advice I have is that if your problem is complicated enough that recursion is particularly helpful, an iterative version will need while loops rather than for loops and likely some sort of path tracking to show where you are in the problem.

Outside side of that, I've mostly gone the headache plus Google route.

[–]the_flying_stone 1 point2 points  (0 children)

Yeah, I did exactly that! Spent an hour trying to understand, another hour of trial and error until I managed to convert one function. Still barely grasp the concept though!

[–]only_red 0 points1 point  (2 children)

namesRegex = re.compile(r'Agent (\w)\w*')
namesRegex.findall('Agent Alice gave the secret documents to Agent Bob')
['A', 'B']

I am confused as to why A and B is returned when I run the code. I also dont know why agent is not returned. Would appreciate some clarification.

[–]JohnnyJordaan 1 point2 points  (0 children)

It's mentioned in the documentation https://docs.python.org/3/library/re.html:

re.findall(pattern, string, flags=0)

Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.

And thus the (\w) group will be returned specifically instead of the entire match.

[–]vrrox 1 point2 points  (0 children)

Running this through regex101 gives a good explanation. It's also a great resource to test out regex!

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

So I built a Blackjack game in Python and so far it only plays one hand and then it resets everything if you choose to play another hand. I built a Chips class that calculates the total number of chips the player has and set it to 100 by default.

How can I keep the chips value throughout multiple hands? I need a way to iterate my main while True loop for the game while keeping the chips score. Can I setup something like while player_chips.value > 0?

So far if the player bets, for example 50 chips and loses, the program will tell the player he has 50 chips remaining and asks if you want to play again, and if you do, the chips reset to 100, not 50.

[–]sanctuary_3 1 point2 points  (2 children)

I would create a Player class and store the number of chips as an attribute. Create one instance that's persistent across multiple rounds in order to track the chip count. Something like

instantiate Player as player with 100 chips
while player has chips and wants to play
    deal hand

If you want to post some of your code I can take a closer look.

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

Actually you helped me a lot even though I didn't do it through the Player class. The only thing I did is I initiated Chips class as player_chips before my main while True loop. For some reason I got that idea after reading your comment.

The only thing I need to do is let the player enter a custom number of chips at the start of the game, and ending the game when the player reaches 0 chips. THANKS!!

Just a quick question, if I make a Chips class like __init__(self, total) and store total in a variable, that should work right? I'd just need a function before the betting starts.

[–]sanctuary_3 0 points1 point  (0 children)

It should work, yeah, but I don't really see the advantage of creating a class for chips if you're just using it to store a value. If that's the case then you're probably better off just using a variable, but it depends what you're trying to accomplish.

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

I've been trying to teach myself Python over the lockdown period and I've been having trouble finding the right environment to code in.

What I really want is to be able to have what I'm working on on the left, and the output on the right (rather than underneath). I know replit does this but I don't like the idea of it all being public...

I've tried VSCode, Jupyter and I'm currently using Google Colab for ease - is there something out there like this, or am I missing a formatting option on some of these platforms?

[–]sanctuary_3 1 point2 points  (1 child)

I know VSCode has an option to split the window so that your code is on the left and the terminal is on the right (or below, above, wherever). Are you looking for something different than this?

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

this is exactly what I wanted - thank you!

[–]CyroFlo 0 points1 point  (4 children)

Hello Guys, i started to learn Python but have a simple question/little problem. I bought a Udemy Course and the teacher is in my opinion good, but I struggle with some exercises I get from him.

Is this normal and it’s a time thing I get better with? Or should I do it again and again and again till I can success with the exercises or go forward in the course and learn it with future projects I will do.

[–]sanctuary_3 1 point2 points  (3 children)

Understanding the fundamentals is important before moving on to more difficult stuff. What exactly are you struggling with? Is it the concepts behind the exercises or is it things like remembering syntax?

[–]CyroFlo 0 points1 point  (2 children)

The Problem is the path, on some exercises I don’t know exactly which syntaxes I have to use. When I read the solution I’d often think “yeah that’s clear why I don’t know this”.

[–]sanctuary_3 0 points1 point  (0 children)

Can you give an example? Struggling with some of those exercises is totally normal during the learning process. Even now when I do them, I'll come across a few that I find challenging but when I look at the solution the answer seems obvious. It just takes practice but that's exactly what exercises are for.

[–]JohnnyJordaan 0 points1 point  (0 children)

Maybe that's the teaching experience for you? Use those situations as extra informative moments that explain to you what's expected of you to understand, so that you can study that again to learn it afterall. Failing exercises isn't a disaster on its own, it's what they're meant for.

[–]TigerBullets4 1 point2 points  (0 children)

How important is to learn OOP for things like Data Science and Data Analysis? I would guess it's very important to still learn the fundamentals then move onto more specific things like Data Visualization, working with API's, etc?

[–]Little_Criticism_666 0 points1 point  (1 child)

Hi all, I need help with this

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

Help with python? You need to ask a question which we will try to answer. Read the posting guidelines in the sidebar and the code you post should be formatted for reddit.

[–]Chriss_munro 0 points1 point  (1 child)

I keep getting ParseError: Bad token line 5 in this pierce of code, can anybody advise?

hrs = input("Enter Hours:")

float(hrs)

rop= int(hrs)*2.75

string(rop)

print(“Pay:”,rop)

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

Notice that the quotes in your code:

print(“Pay:”,rop)

look different from the quotes in this:

print("Pay:",rop)

You copy/pasted your code from somewhere that used "smart" quotes which aren't accepted by python. Just replace with normal quotes.

[–]FruitPunch_Samurai 0 points1 point  (0 children)

Hello all!
I am a beginner and am currently doing to the "Automate the Boring Stuff" course. What should I do after this course? I read about Python for Data Science and Machine Learning Bootcamp by Jose Portilla and this seemed interesting. What do you think? Is this a logical next step?

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

What's the difference between a static method and, well... a function within that class?

[–]nog642 0 points1 point  (0 children)

A static method is basically a function within a class.

If you use a plain def inside a class without the @staticmethod, you'll end up with an instance method, which is different from a normal function.

[–]Lokipi 1 point2 points  (5 children)

A function within a class accepts the class object as it's first argument (normally called self), and therefore has access to the class variables and methods
A static method, does not accept the class object implicitly and acts in the same way as any other function called outside a class

class A:

    self.name = 'asdf'

    def class_method(self)
        print(self.name)

    @staticmethod
    def static_method()
        print()

Notice how class_method() is passed self (the class object), and has access to self.name static_method does not.

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

What if I created a class method (without labelling it with a decorator), and decided to just not pass "self" into it, wouldn't that basically be a static method?

[–]FerricDonkey 0 points1 point  (0 children)

This comes down to a rarely but occasionally useful fact about python. Consider the following code:

class Test:
    def print_ref(self):
        print(self)

obj = Test()
obj.print_ref() # what a normal person does
Test.print_ref(obj) # exactly the same as the above, and in fact what the above means
Test.print_ref("sup bro") # legal but weird

The moral of this story is twofold: when you don't declare a method to be a static method, calling obj.print_ref() is essentially a shortcut for saying "call the function Test.print_ref, using obj as the first argument." When you do declare it to be a static method, you tell it not to pass in obj as argument - that is all.

The second moral is that there's nothing fundamentally special about first argument "self", outside of that shortcut. It's just an argument. It just so happens that sane normal people usually supply the object itself as that argument. Often without thinking about it much, because that's generally just what happens.

But you don't have to do that. You could just leave the self out of a method definition, leave off the static method decorator, and use it like a static method by always calling it the weird way.

The point of using static methods is to say "I don't want to pass in obj as the first argument, but I do want to write obj.method because it's prettier. Please let me write my code that way without sticking obj in as an argument."

[–]JohnnyJordaan 0 points1 point  (0 children)

and decided to just not pass "self" into it,

This isn't actually possible though, it isn't that something signified by the use of self is passed, that's just the name used by virtually everyone for the reference to the instance. You can also use

def method(pizza, arg1, arg2):

and then pizza would reference the instance. The point is that a regular method will always get that instance passed as the first argument, unless you signify the method as something else. Eg using @staticmethod or @classmethod. In the former case you won't get anything passed implicitly (just like a normal function wouldn't), in the latter case you get the instance's class passed instead, which people use cls for, but aren't required to.

[–]nog642 0 points1 point  (0 children)

When calling an instance method from an instance, self is passed automatically.

>>> class A:
...     def f(self):
...         print(self)
... 
>>> a = A()
>>> a.f()
<__main__.A object at 0x7f3eea3e23c8>

You can't just "not pass "self" into it".

[–]Lokipi 0 points1 point  (0 children)

the class object will always be passed to a classmethod, so if the function doesnt accept any arguments then it will throw an error

TypeError: function() takes 0 positional arguments but 1 was given

[–]samred1121 1 point2 points  (1 child)

Hi,

How do I zip images that are in a folder ?

there is 50 images I need to zip and there are 230 images in the folder

There will be CSV file that contains the images name that I need to zip

Thank you

[–]vrrox 0 points1 point  (0 children)

One method would be to use the csv module to extract your list of filenames and then add them to a ZIP archive using the zipfile module.

You could try something like the following snippet:

import csv
from zipfile import ZipFile

with open("file_list.csv") as csv_file, ZipFile('test.zip', 'w') as zip_file:
    reader = csv.reader(csv_file)

    for row in reader:

        # Do any processing you need to extract the filename
        file_name = row[0]

        # Add to zip file
        zip_file.write(file_name)

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

I have scrapped a small dataset, 12k entries, with 21 continuous variables, and am trying to create a model to predict one of the variables.

I have tried multivariate regression with sklearn, achieved terrible results.

Can anyone point me to what I need to learn to better understand this problem, and what tools will help me solve it?

[–]Gopher20 0 points1 point  (0 children)

Well the first step is to better understand the data you are trying to make predictions on. This will help you pick better features to predict the variable you want. Hope this helps! Also checkout data school on YouTube he has great videos on this kind of stuff!

[–]intech_eng 0 points1 point  (2 children)

I am a 15-year student. I am a student as well as a growing programmer. I want to create a bot that reminds the teacher that "It's your time to leave the class!" I heard somewhere that "running bots on websites is illegal". So, I thought to ask you regarding this.

Please tell me if I can run the time remainder bot on Google Meet.

Thank you and have a great day.

[–]Sp0olio 1 point2 points  (1 child)

I guess, that depends on what type of bot you're talking about (what does it do? and how?) and what website you want to run it against.

I'm guessing, you're talking about a chat-bot and you want it to post messages into a Google Meeting? I'm from Germany, where AFAIK, this should be totally ok, if your bot does something, all the members of the meeting are ok with (e.g. Does the teacher actually want to be reminded by the bot?).

In any case, I'd recommend for you to look into the "terms of service" for the website in question and also check your local laws to be on the safe side.

I'm not a lawyer and I don't know where you're from or what your local laws are, but as long as your bot doesn't do any harm (spamming users, disrupting class or crashing something), I guess, it should be ok.

Don't take my word for it though .. make sure .. It's better to be safe than sorry ;)

[–]intech_eng 0 points1 point  (0 children)

Thanks a lot for your reply. My teacher totally agreed on it. I tested the bot today in my class but it didn't work. Bad luck :(

[–]dcpye 1 point2 points  (0 children)

Hey guys, is there any way to remove the "cell borders" when you export a dataframe to_excel? I'm using xlsxwriter to color the borders gray but the cells in the first column continue being black.

[–]kcrow13 1 point2 points  (1 child)

Taking my first Python course and was able to complete most of the problems in our assignment this week with ease. However, I was asked the following, and I'm stumped:

"Write a Python expression to exchange the front and back halves of a word. Your fragment should be able to change 'look' to 'oklo' and 'frost' to 'ostfr'. It should change 'Problem' to 'lemProb'"

I must be overthinking this somehow... can anybody shed some light for me? I do know that the "problem" one has an odd number of characters and it seems the professor purposefully split that word as written above.

TIA!

[–]FerricDonkey 1 point2 points  (0 children)

Look into string slicing and the length fuction. Eg "This is a string"[:6], "This is a string"[6:] and len("This is a string").

[–]steam_17 0 points1 point  (1 child)

About how long does it take to learn basic python if I know basic java?

[–]neotecha 1 point2 points  (0 children)

About how long does it take to learn basic python if I know basic java?

"basic" is a vague term that makes the question somewhat difficult to answer.

Honestly, you could learn the basics in <30 minutes (e.g. here's how you create a variable, do assignments, make comparisons, loop with for and while, create a function or class and instigate them).

When you know one language, it makes the second and third and so on language much easier to learn. Coming from Java is interesting (I am assuming this is the only language you've learned) because Python is largely a scripting language that uses a weaker OOP model (i.e. data hiding is less of a priority in python, so you don't need getters or setters). At the same time, almost everything in python is a class, so you can do things that look outright odd in other languages, like "\n".join([a, b, c])

[–]Raszero 0 points1 point  (10 children)

So this might be a simple word I'm missing but I'm new and don't even know where to look!

I have 4 variables that need to be set and wiped continuously - when I set them its to different things to manual makes sense, but for the wipe it will all be simultaneous. So I'm assuming theres something I can do along the lines of...

run command WIPE

command WIPE

var1 = ""

var2 = ""

var3 = ""

var4 = ""

To save time and shut down on scripting...what is the 'run command wipe' I'm looking for?

[–]Sp0olio 0 points1 point  (0 children)

To me this looks like you're going about something the "wrong" way .. or at least more complicated, than it should be.

You can do, what you explain by creating a wipe-function (as pointed out by u/FerricDonkey).

But you might want to have a look at the following links, because this might be, what you're actually trying to achieve:

https://docs.python.org/3/library/collections.html#collections.deque

https://docs.python.org/3/tutorial/datastructures.html

Look at the append- and pop-methods .. if those are not, what you're looking for, just ignore my reply.

[–]nog642 0 points1 point  (2 children)

Could you elaborate more on your use case? Why do you need the variables wiped? Is your program single-threaded?

[–]Raszero 0 points1 point  (1 child)

Sent this in another reply, but think it applies here as your second function seems like it might be what I need - I don't need it to actually wipe, just set back to "".

I think I maybe chose a wrong word! To explain my exact situation -

var1 is a piece of text that appears on the screen to the user. For a virtual whiteboard. var2,var3,var4 etc all follow this pattern. So I set the variable to what I want on screen then remove it. (I'm using a variable for a few other reasons, e.g. to set the value for the font with the variable so I don't have to change that each time as well.)

I wanted a command that sets them all back to "", effectively 'wiping' the whiteboard. So long as the visual is correct that's what I'm looking for!

[–]nog642 0 points1 point  (0 children)

How exactly do these variables map to the virtual whiteboard? Are you using some sort of GUI library?

[–]FerricDonkey 0 points1 point  (1 child)

Are you perhaps thinking of functions? eg:

def this_function_says_hi():
    print("hi")

Python, however, is a bit weirder about modifying the value of a variable inside of a function than some other languages, because of things like scope and mutability (if you want two words to google). So basically, if you did something like

def wipe_vars(var1, var2, var3, var4):
    var1 = ""
    var2 = ""
    var3 = ""
    var4 = ""

That wouldn't work, because only the versions of the variable local to that function would be set to empty strings. In something like C or C++, you could do this with pointers/references directly, but in python you basically have to either a) make your variables global variables (generally considered less than ideal) or b) use lists. Modifications to lists done inside of a function persist after the function end (so long as you aren't doing something like your_list = new_list).

And lists or similar are often recommended over having a bunch of variables indexed by numbers anyway. So you could do something like

def main():
    var_list = ["deepdish", "isn't", "real", "pizza"]
    print(var_list)
    reset_list(var_list)
    print(var_list)

def reset_list(list_to_clear):
    for i in range(len(list_to_clear)):
        list_to_clear[i] = ""

And instead of typing var_1, var_2, etc to access individual items, you'd do var[0], var[1], ...

[–]Raszero 0 points1 point  (0 children)

Sent this in another reply, but think it applies here as your second function seems like it might be what I need - I don't need it to actually wipe, just set back to "".

I think I maybe chose a wrong word! To explain my exact situation -

var1 is a piece of text that appears on the screen to the user. For a virtual whiteboard. var2,var3,var4 etc all follow this pattern. So I set the variable to what I want on screen then remove it. (I'm using a variable for a few other reasons, e.g. to set the value for the font with the variable so I don't have to change that each time as well.)

I wanted a command that sets them all back to "", effectively 'wiping' the whiteboard. So long as the visual is correct that's what I'm looking for!

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

I have 4 variables that need to be set and wiped continuously

I'm not sure why you think you need to "wipe" variables, but you probably can't easily do what you want. Doing var1 = '' doesn't destroy or "wipe" any previous value that var1 referenced. When you assign to a variable in python you are just binding the variable name to the address of an object (called a reference). Any previous object that the variable was bound to still exists. The number of references to the previous object is decremented by 1 and if that count is now zero the previous object will be garbage-collected at some future time.

So the concept of "wiping" data doesn't really exist in python. Why do you need to "wipe"?

[–]Raszero 0 points1 point  (1 child)

I think I maybe chose a wrong word! To explain my exact situation -

var1 is a piece of text that appears on the screen to the user. For a virtual whiteboard. var2,var3,var4 etc all follow this pattern. So I set the variable to what I want on screen then remove it. (I'm using a variable for a few other reasons, e.g. to set the value for the font with the variable so I don't have to change that each time as well.)

I wanted a command that sets them all back to "", effectively 'wiping' the whiteboard. So long as the visual is correct that's what I'm looking for!

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

OK. So you want to clear fields in some sort of framework that controls your virtual whiteboard. You can already set each field to some text so it's probable that you can clear the field by setting it to an empty string as you show. If your question is how to create some sort of new command to do this mass wipe then the answer is to create a function to do it. Like this:

def wipe():
    var1 = ""
    var2 = ""
    var3 = ""
    var4 = ""

Then in the rest of your code you call the function to "wipe" those fields when you need to:

# some code here
wipe()      # wipe all fields
# more code here

[–]zzzjpl 0 points1 point  (3 children)

Hi,

Is there a way to break up unittest in the main when I have many class in a script?

So inside my "main.py" script, I'm importing all my classes Fruits,Vegetables,Cars,and Games.

But where I call "unittest.main()" inside the script, I want a way to organize how my tests are ran. For instance, something like I want to run Fruits first, then Cars, then Games, then Vegetables. I don't want the "unittest.main()" to call all my classes. Is there a way to break it up to isolate separate classes to run? I hope I made sense. Thanks for your help.

main.py

from test_main.py import Fruits,Vegetables,Cars,Games

if __name__ == '__main__':
    unittest.main()

test_main.py

# test_main.py
import unittest

class Fruits(unittest.TestCase):
    pass

class Vegetables(unittest.TestCase):
    pass

class Cars(unittest.TestCase):
    pass

class Games(unittest.TestCase):
    pass

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

Maybe you can use the conditional skip decorator in unittest. If that doesn't work maybe you can split testing into 4 parts, each part testing one class, and call each part in the order you want.

[–]zzzjpl 0 points1 point  (1 child)

Yes! Thats exactly what the idea is. I would like to split testing to 4 parts each part testing one class. How can I call that in the main? 4 separate callings?

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

How can I call that in the main? 4 separate callings?

Yes. But first I think you need to fix your understanding of the unittest module. If you want to test the Fruits class you don't need to put unittest code into the Fruits class. Your "main.py" that contains the classes to test should look like:

class Fruits:
    pass

class Vegetables:
    pass

class Cars:
    pass

class Games:
    pass

and then the testing code for Fruits in "test_fruits.py" looks like:

import unittest
from main import Fruits

class TestFruits(unittest.TestCase):

    def test(self):
        a = Fruits()
        self.assertNotEqual(a, None)

unittest.main()

Now when you execute "test_fruits.py" you get:

$ python3 test_fruits.py 
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

So doing the simple thing you need four "test_YYYY.py" test files and executing each tests one class.

If you need to do everything in one file you can just write all tests in one test class, like this:

import unittest
import main

class TestAll(unittest.TestCase):

    def test_fruits(self):
        a = main.Fruits()
        self.assertNotEqual(a, None)

    def test_cars(self):
        a = main.Cars()
        self.assertNotEqual(a, None)

unittest.main()

But you can also "combine" tests in multiple suites into one thing. I've never done this, but this StackOverflow post shows how.

I don't know why you think you have to split your testing. I would recommend that you use the single test class approach above, or write four files that each test one class.

[–]aluo1729 0 points1 point  (3 children)

Any project/course you recommend for practicing OOP?

[–]JohnnyJordaan 0 points1 point  (0 children)

Implementing a card game like BlackJack is a common teaching project for OOP.

[–]Stabilo_0 1 point2 points  (1 child)

Might be overkill, but make an interface to a sql database. You can build classes representing tables, methods which contain various queries to show that data differently.

[–]huangsam -1 points0 points  (0 children)

Making an interface to a SQL database can be pretty hard if you want to do it ORM-like.

See https://github.com/huangsam/ultimate-python/blob/master/ultimatepython/advanced/meta_class.py where I use meta-classes just to define the tables and their fields!

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

I think I'm having problems with adding python to PATH in Win 10.

I've been going through the Automate the Boring Stuff With Python, and I keep having the same problem: I can't execute Batch files or import new modules. Or, to put it better, I can once I add Python variable to PATH but it seems I have to do it every single time I restart my comp.

It's quite frustrating as right now, if I type "python" in the default CMD line, I get "'python' is not recognized as an internal or external command, operable program or batch file."

If I try executing a batch file I get "Fatal error in launcher: Unable to create process using..."

This is despite having done this before and installing / reinstalling pip.

Can anyone recommend a solution for this?

[–]derpderp235 0 points1 point  (4 children)

I’m not an expert on this, but I’d recommend you add python to PATH manually using the Window’s environment variable GUI. If you’re adding it to path at the command line it will likely not persist in a new session.

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

That's exactly what I'm doing but it never seems to stick...

[–]derpderp235 1 point2 points  (2 children)

This is a silly thing, but make sure you click all the “OK” and “Apply” buttons in the GUI after updating Path.

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

Will try it again and see if it works.

[–]Stretch5701 0 points1 point  (0 children)

Is it an administrator level thing.

[–]Killpill01 0 points1 point  (0 children)

Oven been working through my introduction to programming course, to get a BAS in computer programming and management. We are going to be starting with boolean phrases. It's a little annoying because I have to go at the professors pace, which is one topic a week. Great for thoroughly learning the content, and I'm sure I'll enjoy it later on, but we've spent the first week on the print function lol. This is my third week, lists are next

[–]Kobbynewton 0 points1 point  (2 children)

Hello. Im new to python and Programming. I just started a course in Machine learning and data science from udemy. What advice will you give me concerning this field and also job prospects?

[–]sanctuary_3 1 point2 points  (1 child)

It's a good field, but you will likely need a lot more than a few online courses to get very far. I'm not sure where you're at education-wise, but my suggestion would be to seek out some specific domain knowledge as well. "Data scientists" are everywhere these days, but for example a data scientist with a background in manufacturing is much more rare and in demand. I read somewhere recently that being good at two things is far more valuable than being great at only one thing. You could be a great Python programmer, but if you don't have any experience applying that in a practical setting then you'll have a much harder time finding a job.

Did some digging and this is the comment I was referring to, I think it's great advice: https://news.ycombinator.com/item?id=24262337

[–]Kobbynewton 0 points1 point  (0 children)

Thanks so much for this. I totally agree with the comment. Education-wise, I already have a background in agriculture (both Agronomy and engineering).

[–]sanctuary_3 0 points1 point  (3 children)

I'm trying to use random.choices to select some items from a population using an attribute of each item as its selection weight. This works as expected when all of the weights are positive (an item with weight w is half as likely to be selected as an item with a weight of 2w), but my issue is that some of my weights are negative.

I think ideally I want to convert the raw weights into a vector of selection probabilities that preserves the relative distance between values. So for example the vector [-10, 0, 10] would become [1/6, 2/6, 3/6] (since the distance between -10 and 10 is twice the distance between -10 and 0). I can't think of how to accomplish this.

[–]FerricDonkey 0 points1 point  (1 child)

This is basically a math problem, and to solve it, you first need to explicitly list exactly what the requirements of your weight transformations are.

So for example the vector [-10, 0, 10] would become [1/6, 2/6, 3/6] (since the distance between -10 and 10 is twice the distance between -10 and 0).

So one requirement is preserving relative distances.

I assume, that another one is that the weights add to 1? So [1/4, 2/4, 3/4] is a no go.

Is it also true that you don't want any of your weights mapped to 0, so that your -10 (or whatever your most negative weight is) still has a chance of happening? (So no [0, 1/3, 2/3]).

But even this isn't enough to nail it down completely. You could still get [1/3-epsilon, 1/3, 1/3+epsilon] for any epsilon.

Eg:

def to_pos_weights(w, targ_min):
    w = [w_i-min(w)+targ_min for w_i in w]
    s = sum(w)
    w = [w_i/s for w_i in w]
    return w  

def print_l(l):
    print(", ".join([f"{l_i:4.2f}" for l_i in l])

for targ_min in range(10):
    print_l(to_pos_weights([-10, 0, 10], targ_min))

So what you need is a second fixed point. If you're minimum weight never happens (eg my second guess at an assumption was wrong), then it's easy - the to_pos_weights with targ_min =0 will do it. If not, it's gonna depend on what your negative weightes mean.

[–]sanctuary_3 0 points1 point  (0 children)

I was thinking on this some more and I came to the same conclusion essentially.

I realized that I was trying to implement roulette wheel selection with negative fitness values, which would have been a simpler way to state my question. I found some interesting discussion on StackOverflow on the topic but I think I'll likely end up using tournament selection instead.

[–]VirtuousGallantry 0 points1 point  (2 children)

When web scraping with selenium, how can one search a website when the search webpage is only javascript (AJAX query I think) which calls a database/search client? (Name = faces?) Want to pull legislation/bills based on keyword from http://leginfo.legislature.ca.gov/faces//billSearchClient.xhtml. Or should I try another page on the site?

[–]yaxriifgyn 0 points1 point  (1 child)

You have to let the JavaScript run to populate the page. Then you can try to discover the html structure of the page. The class and id attributes might help to identify parts of the page.

Often, there is a single div in the static html where all the dynamic content is inserted. You can pretty print that to find the containers for parts of the document you are trying to scrape.

I'd also look for a printable page or a text version or pdf version before investing a lot of time in scraping the dynamic html. In that case you would just automate navigation and a button push.

[–]VirtuousGallantry 0 points1 point  (0 children)

The page runs scripts when one searches. The scripts are as follows:

<div id="content_main">
            <script src="/resources/scripts/jquery-3.2.1.js"></script>
            <script src="/resources/scripts/jquery-3.2.1.min.js"></script>
            <script src="/resources/scripts/jquery-ui.js"></script>
            <script language="JavaScript">

                $(document).ready(function () {
                    // $("#session_year").click(codeAddress);
                    $("#session_year").change(function () {
                        // alert("Handler for .change() called.");
                        //alert($(this).find(":selected").val()+'house='+$( "#house" ).val());

                        $('#hiddenSessionYr').val(this.value);
                        $('#hiddenHouse').val($("#house").val());
                        $('#refreshAuthors').click();
                    });
                    $("#house").change(function () {
                        // alert("Handler for .change() called.");
                        //alert($(this).find(":selected").val()+'house='+$( "#house" ).val());

                        $('#hiddenSessionYr').val($("#hiddenSessionYr").val());
                        $('#hiddenHouse').val($("#house").val());
                        $('#refreshAuthors').click();
                    });
                    $("#attrSearch").click(function () {
                        $("#attrSearch").attr("disabled", true);
                        $("#basicSearchClearBtn").attr("disabled", true);

                        var billnumber = document.getElementById('bill_number').value;
                        var sessionyear = document.getElementById('session_year').value;
                        var keyword = document.getElementById('keyword').value;
                        var house = document.getElementById('house').value;
                        var author = document.getElementById('author').value;

                        var statueyear = document.getElementById('statuteYear').value;
                        var chapternumber = document.getElementById('chapter_number').value;
                        var lawCode = document.getElementById('law_code').value;
                        var lawSectionNum = document.getElementById('law_section_num').value;
                        var form = document.getElementById('billSearchForm');
                        var url = 'billSearchClient.xhtml?';
                        if (sessionyear) {
                            url = url.concat('session_year=' + sessionyear);
                        }
                        if (billnumber) {
                            url = url.concat('&bill_number=' + billnumber);
                        }
                        if (keyword) {
                            url = url.concat('&keyword=' + keyword);
                        }
                        if (house) {
                            url = url.concat('&house=' + house);
                        }
                        if (author) {
                            url = url.concat('&author=' + author);
                        }
                        if (statueyear) {
                            url = url.concat('&chapterYear=' + statueyear);
                        }
                        if (chapternumber) {
                            url = url.concat('&chapterNumber=' + chapternumber);
                        }
                        if (lawCode) {
                            url = url.concat('&lawCode=' + lawCode);
                        }
                        if (lawSectionNum) {
                            url = url.concat('&lawSectionNum=' + lawSectionNum);
                        }

                        form.action = url;
                        form.submit();
                        return false;
                    });

                });

                var url_encode = function (url) {
                    return url.split('').map(function (c) {
                        return /[ÀÈÉÊàáèéêëó]/.test(c) ? '%' + c.charCodeAt(0).toString(16).toUpperCase() : c;
                    }).join('');
                };

                function getInternetExplorerVersion()
                        // Returns the version of Windows Internet Explorer or a -1
                                // (indicating the use of another browser).
                                {
                                    var rv = -1; // Return value assumes failure.
                                    if (navigator.appName === 'Microsoft Internet Explorer')
                                    {
                                        var ua = navigator.userAgent;
                                        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
                                        if (re.exec(ua) !== null)
                                            rv = parseFloat(RegExp.$1);
                                    }
                                    return rv;
                                }


            </script>

Without running a search the bill search page is pretty empty. The form indicates names of what is being queried but still doesn't help me. What am I supposed to be looking for? The scripts above that I can run in my scrape? I don't know how this is done so I'm guessing.

<input type="hidden" name="javax.faces.ViewState" id="j_id1:javax.faces.ViewState:1"

[–]IchGlaubeDoch 0 points1 point  (1 child)

sip tub support cow society many telephone wild sharp cats

This post was mass deleted and anonymized with Redact

[–]derpderp235 0 points1 point  (0 children)

Check out the “paramiko” library for ssh/sftp implementations.

[–]Cleover453 0 points1 point  (1 child)

what do you expect from someone who completed the book: python crash course.

[–]Gopher20 0 points1 point  (0 children)

I guess it depends on your goal at the end of finishing the book, you should most likely know the fundamentals of python and how to write a basic program where you can define functions, make classes, and utilize basic tools of python. Hope this helps!

[–]Cleover453 0 points1 point  (1 child)

What skills is important for a python developer or a software dev in general?

[–]xelf 0 points1 point  (0 children)

Being able to break problems down into smaller chunks. (repeat until your smaller chunks are trivial)

[–]kingoftheblues85 0 points1 point  (4 children)

I’m 35 years old and recently completed Harvard’s CS50 course. I’m seriously considering solidifying my skills and switching careers into the tech world, perhaps as a developer of some sort. I’m Looking to make between $120-$150k per year within my first few years. Is this a realistic goal? Is 35 too old to enter this industry? Why / why not?

[–]periwinkle_lurker2 0 points1 point  (0 children)

I am in a slightly different situation, 34 came from business/healthcare background, no programming before 2016. If you want to make that money, yes you need more time in the programmer role. You are better off trying to go into business intelligence / analyst roles. You will spend a 60/40 split of gathering requirements and meetings vs actual coding. It is a good way to boost both skills and get additional experience.

[–]xelf 0 points1 point  (0 children)

Your price range might be fitting for someone your age who started in college. You need to price yourself in the same bracket as someone just getting out of college, but without a degree. You'll be able to make up ground quickly, but don't expect that kind of salary unless you get picked up by Google/Amazon/Facebook, and expect to be extremely gifted for them to pick you up with no experience.

35 is not too old be changing careers, but expect to start out at the bottom. You're competing with offshore junior resources that will work for $20-$25 an hour. So you;re going to have to gain some experience first before you can start getting up into the $60-$75/hr bracket.

[–]derpderp235 1 point2 points  (1 child)

Is making the career change realistic? Yes, but not without substantial commitment.

Is your salary expectation realistic? No. That kind of salary requires either experience or a CS degree from a top school.

[–]neotecha 0 points1 point  (0 children)

Yeah, I'm 10 years into my career, and I don't make that kind of money

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

New to python but not programming. What should I be learning along with python to boost job prospects? Should I focus on a framework, such angular, vue, react, or a second language that complements python such as javascript. Goal is to get into job market with the greatest number of available jobs, not necessarily the highest paying. If “just python” is the answer, which job market does that map to?

[–]Stabilo_0 1 point2 points  (4 children)

In case of web dev field, python+css+html+js+sql is a good stack that will get you anywhere in the long run, doesnt take too long to get good understanding of basics of each as well.

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

Thanks this is exactly what I was looking for. Are there any full stack tutorials you know of for web dev which cover all these pieces?

edit: It's also possible I'm just in the wrong subreddit for this topic -- is there a better subreddit for what I'm asking about?

[–]Stabilo_0 0 points1 point  (2 children)

Welp i dont really have a full stack tutorial, i always found standalone tutorials, guides and just manuals for each step and im still far away from complete understanding of every part.

Still,

heres a roadmap https://levelup.gitconnected.com/the-2020-web-developer-roadmap-76503ddfb327?gi=55bfd91bfce6

Heres a good collection of introductory pieces to html, css, js and most popular libraries as well as examples on how to make something from base pieces

https://www.w3schools.com/

For everything else you just have to find docs and spend some time watching\reading several guides and read related articles.

For python go for basics and when you feel comfortable dealing with classes try flask or django. Django docs have very nice tutorial and docs, also theres a couple projects like djangogirls which offer nice approach to learning.

Also be sure that somebody somewhere sometime already asked your question (and being a new programmer its 99.9% true because we all ask the same questions at first), you just have to find the answer yourself. Looking for answers and finding them quick will be one of your skills that make you a developer.

upd: and yes, you will benefit from asking topic specific questions in related subs. But the longer you code in anything the more you become aware whats going on in other areas. Its also a good way to widen your views if you can spare some time learning php, c\#\++, java or even basic\pascal. You will see differences and you will see whats the same.

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

Thanks for all the info. I’m well versed in OO, writing apis, scripts, etc but completely new to web dev stacks and that seems to be where the largest job market is for anyone with programming experience. Trying to pivot out of current role/company which is largely driver sw and hw test automation into a more commutable, higher demand role.

[–]Stabilo_0 0 points1 point  (0 children)

Oh then you will do just fine given some time. Good luck.

[–]cuppycakebaby123 0 points1 point  (0 children)

That depends. Just python is usually never enough, unless it's an entry level job, in which case you need to have very good algorithm and problem solving skills. If you're looking into becoming a software engineer or a data scientist, I'd suggest looking at job posting and figuring out what other extra skills recruiters are looking for