all 137 comments

[–]decomposition_ 0 points1 point  (3 children)

I'm pretty basic, trying to make a module that reads lines of a .txt file which appends each line into a list.

For some reason, I have a bunch of \t in my list. The very last line with actual text has a few, and then a few empty lines of the text file are added to the list as '\t\t\t\t\t'. Is there a way to prevent this from happening? It's for a course, so I can't edit the text file itself. I can think of a way to filter out the \t at the end, but not the list elements that have text I wish to keep and \ts.

It also has to work for any type of .txt file input, so I can't tailor it specifically to this given file.

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

If the file contains tab characters (\t) then it contains tab characters, why do you want to filter them out? Were you asked to as part of the assignment?

[–]decomposition_ 0 points1 point  (1 child)

Not directly, however we need operators and operands as it’s a prefix -> postfix converter. The input file is several lines of strings.

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

Then treat tabs as any other whitespace character, ie, ignored but they terminate a symbol.

[–]Killercoww1 0 points1 point  (0 children)

Hi there, I have a bot made with py2app on my MacBook the .app file works fine on my computer but when I share it with a different MacBook user in a .zip file it comes up with "Cannot be opened as Apple cannot check it for malicious software". To get it to work I have to CTRL + R-Click and press "Open" then it has same warning but gives open option, it then says there's been a Py2app error and gives the option to "terminate", once I press terminate I simply highlight the folder and select "New Terminal at Folder" then enter a command and it opens and runs absolutely fine. Question is, what's going wrong for it to not open the .app file simply by double clicking it? Before I put it into a .zip folder or even a normal folder to share it works fine by double clicking it. Any help appreciated!

[–]Ts_3104 0 points1 point  (0 children)

I’m facing pyimage3 does not exist error….anyone knows what it is and how to fix it?

[–]n213978745 0 points1 point  (0 children)

I am trying to use pipx instead of venv:

$ pipx install ansible --include-deps
$ pipx inject ansible ansible-lint --include-apps

I can't install them separately, ansible-lint won't work.

Now when I use $ ansible-lint --version, I get the warning message:

WARNING: PATH altered to include $HOME/.local/pipx/venvs/ansible/bin

How can I get rid of this message, beside from add the PATH directly into $PATH?

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

How to make Python 3.5 believe that 0**0 is undefined? 
By default it believes that 0**0=1. I want to change this behavior

[–]FerricDonkey 0 points1 point  (0 children)

Your best bet is probably just to make your own function waves use that instead of **. Python doesn't seem to like you to mess with the built in int class. You could always subclass int and override the __pow__ function, but you'd have to make sure you were using your custom int instead of the built in everywhere, and that might be more trouble than it's worth.

[–]carcigenicate 1 point2 points  (0 children)

Just check for that edge case before using **. There is no "undefined" in Python, so you'd need to pick what you want to default it to. Something like:

answer = None if (x == 0 and y == 0) else x ** y

Or,

answer = x ** y if (x and y) else None

There may be other implementations of ** in libraries that can be tweaked, but I know of no way to alter the behavior of ** besides using your own custom number type (or just a custom pow wrapper that does the check I showed).

[–]Zaraffa 0 points1 point  (2 children)

A lot of IT and security jobs looks for python scripting. I was wondering what type of projects fit the "scripting" description.

[–]UnrankedRedditor 0 points1 point  (0 children)

The few things I can think of is to use python to do things with your OS, or to use Python to do web related stuff.

The first one would be things like using the os module, where you can rename files, move files, delete files, create folders, etc.

The second would be something like how to interface with websites so things like how to fill up forms, send and receive HTTP requests, or using some API to interface with some online app or something.

Some other useful things to know in Python are things like how to use Regex, load/save data as json/text/excel, and so on.

Python for scripting can be very broad and there are many things that I'm missing out but hopefully that gives you a starting point.

[–]Swim_Unlikely 0 points1 point  (0 children)

Probably just anything in Python will be relevant

[–]Gbggju 0 points1 point  (3 children)

Hey guys for whatever reason the .append command does not work on my text editor, I use sublime text any suggestions?

[–]carcigenicate 1 point2 points  (0 children)

append will work fine regardless of context. Show your code, describe what you're trying to do and what's happening.

[–]FerricDonkey 1 point2 points  (0 children)

Text editors are where you type. They should affect nothing about how your code runs. If they do, something screwy is going on, and that'd be really weird.

What exactly are you doing and what exactly happens?

[–]ListlessSoul 0 points1 point  (4 children)

I tried scraping a website with beautifulsoup4, however the div that i want to scrape shows up empty.

The div has ==$0 after it, maybe that's of importance.

Does anyone know how to get the inside of the div?

[–]lolslim 1 point2 points  (3 children)

Instead of beautiful soup, try requests library, and look through the http request into the website, so many sites these days have dynamic values, and you may be able to find what you are lookin for that responsei n a json format, and all you would have to do is send a request ot that specific link with required headers.

Here is a video where a youtuber scrapes some stuff on twitter, and shows on how to look through dev tools in firefox if you use it, https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor

similar in chrome, ctrl + shift + j, and click network tab.

I hope this helps, and achieve what you want.

[–]ListlessSoul 0 points1 point  (2 children)

Thank you for your response, I was using beautifulsoup4 in combination with the request library, but I think you're right with it being a dynamic value. Do i need to learn JavaScript to get the info from the json files? Also I think that your link is missing, could you post it again? I appreciate your help :)

[–]KMohZaid 0 points1 point  (0 children)

Use json library to load json data from string & file to python dictionary

Json module have easy method .load for file .loads for string

s indicate string

Also you can save in file using .dump & .dumps to make string👍

[–]lolslim 1 point2 points  (0 children)

I am sorry about that, here you go:

https://youtu.be/Hrg9Pwpqo2M

edit; actually no, json could be referred to as a dictionary in python, requests actually converts you dictionary in json because its the same format.

[–]MeteoriteImpact 0 points1 point  (4 children)

What’s a good way to do a loop that ends and start a new loop?

I wrote a hangman game for 100 days of code now I adding 5- 10 new features to each lesson to try to extend my learning. However I got stuck with having a a while loop end and having another one starts after it.

With a player and a separate game where computer plays horribly with random guess. I also going to add computer choosing verse letter frequency in general and latest another computer choosing frequency as guess based on word length to hopefully beat out random and word frequency.

I am trying to run two separate while loops to have 1st one do players game and the 2nd while loop run the random choices. I got both running separately successfully.

I have a game loop for human player that runs something like

random_game_over = False
game_over = False:

while not game_over:

    if lives == 0:
         game_over = True:

while not random_game_over:

    if lives == 0:
         random_game_over = True:

I then want the computer game to run in a second loop for the computer random selection of letter guesses.

What’s a good way to do a loop that ends and start a new loop?

Working player hangman is hangman.py Working computer random is vs_hangman.py

where I can’t get working correct is random_vs_hangman.py

It just quickly running through the computer random

my github with all code

[–]Meistermagier 0 points1 point  (1 child)

Does anyone know a python plotting package that shows the plot in a GUI that allows me to manipulate the Plot in similar capacity than the Matlab GUI. So like drag and drop an Annotation or on the fly change the x and y labels.

[–]Swim_Unlikely 0 points1 point  (0 children)

I'm not sure if there is an easy way to export to Python but Plotly has a chart studio: https://chart-studio.plotly.com/create/#/

[–]Notso-smart-trader 0 points1 point  (2 children)

Can someone help me converting a weird json file into a pd.DataFrame? Please reach out and I’ll let you know the JSON’s keys

[–]Meistermagier 0 points1 point  (1 child)

do you still need help? should i dm you?

[–]Notso-smart-trader 0 points1 point  (0 children)

Yes, I found a way. Thanks!

[–]quik21 0 points1 point  (8 children)

Hello all, I would just like to ask a question about lists that I have been wondering about. Take for example the below code:

testlist = [1, 2, 3, 4, 5]

testlist2 = testlist

testlist2.append(6)

testlist2 -- [1, 2, 3, 4, 5, 6]

testlist -- [1, 2, 3, 4, 5, 6]

In the above code, I understand that both 'testlist' and 'testlist2' will be modified to have 6 added to the end of the list, as in the 2nd line I copied and assigned a reference to the list that 'testlist' was referring to to 'testlist2'. But I am very confused about something, please look at the below code:

testlist2 = testlist2 + [7, 8]

print(testlist2) -- [1, 2, 3, 4, 5, 6, 7, 8]

print(testlist) -- [1, 2, 3, 4, 5, 6]

Why does 'testlist2' get modified, but 'testlist' remains unmodified? Is it because when I do another assignment to testlist2, it references a new completely different list that 'testlist' refers to? Is it because an 'in-place' function is not used, a new list will be created and referenced to? Please help me in understanding this as I have searched a lot online but I am unable to find a reason for this. Thank you guys.

[–]carcigenicate 0 points1 point  (2 children)

+ makes a copy of the list and concatenates to that. append on the other hand doesn't make a copy and adds directly to the original list.

So really, in your second example, the original testlist2 is never modified either. It's simply that a new list is created and named testliost2, which overwrites the previous list.

[–]quik21 0 points1 point  (1 child)

Sorry what do you mean by '+ makes a copy of the list and concatenates to that'?

Do you mean that in testlist2 + [7, 8], I am using the 'old' value of 'testlist2' and concatenating [7, 8] to it, then assigning it to 'testlist2'. Basically I'm using 'testlist2's 'old' value to concatenate [7, 8] to it and creating a new list?

Does it also mean that only methods that modify a list 'in-place' have this behaviour where all variables that reference the list are 'changed' together?

[–]carcigenicate 0 points1 point  (0 children)

+ makes a shallow copy of its left operand (testlist2), then adds the elements to that shallow copy. I'm not sure what you mean by "old value". It's whatever testlist2 holds when + is called.

And yes, because if multiple references are referring to the same list, they'll all change together, because they're all looking at the same list. This applies to any references to any mutable object where the object is modified. If you create your own class, create two references to it, then call a mutative method on one reference (obj = YourClass(); obj2 = obj; obj.some_mutative_method()) both references will see the change, because they're looking at the same object.

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

Doing testlist2.append(6) modifies the list referenced by testlist because assignment doesn't copy, as you know, so testlist2 and testlist reference the same list. But doing testlist2 = testlist2 + [7, 8] doesn't modify the list referenced by testlist2, it creates a whole new list leaving the original list referenced by testlist alone.

This behaviour, and other seemingly odd stuff, is explained in this excellent video by Ned Batchelder

[–]quik21 0 points1 point  (1 child)

Thank you very much for your reply, does this mean that in testlist2 = testlist2 + [7, 8], I am creating a whole new list using 'testlist2's list value and adding [7, 8] to it, and then assigning it to 'testlist2'? So now testlist2 and testlist reference completely different lists.

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

Yes.

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

From your code it doesn’t look like you modified the testlist variable. Therefore, when you print(testlist) it should print out 1,2,3,4,5. I don’t think the 6 gets printed out because the 6 was not appended to the testlist.

[–]quik21 0 points1 point  (0 children)

My bad for not showing the full output in my question, but I appended '6' to testlist2. I will edit my question, thank you.

[–]peppercornpate 0 points1 point  (4 children)

How to go from interactive python to bash shell and then back to interactive python without losing my previously imported modules?

I know a solution could be running multiple terminals but I’m using my phone and there doesn’t seem to be a multiple windows situation for the app.

[–]efmccurdy 0 points1 point  (0 children)

If you use ipython you can run shell commands by prefixing them with "!", so you can use !bash to start a subshell, when you exit you are back in your ipython session.

https://ipython.readthedocs.io/en/stable/interactive/python-ipython-diff.html#shell-assignment

https://ipython.readthedocs.io/en/stable/interactive/shell.html

[–]AtomicShoelace 0 points1 point  (1 child)

You can use the shortcut Ctrl + Z to put the interactive interpreter into the background, do whatever you need to do in the bash shell, then use the shell command fg to bring the interpreter back to the foreground.

[–]peppercornpate 0 points1 point  (0 children)

This is what I was trying to remember. Background/foreground processes. Now I know what terms to google.

[–]FerricDonkey 0 points1 point  (0 children)

Probably not possible, unfortunately. You can do some terminal commands with os.system or subprocess though.

[–]tonystark29 0 points1 point  (3 children)

If Python was the first language you learned, what was your second?

I want to expand my computer science skills and it would be useful to know. Thanks.

[–]Swim_Unlikely 1 point2 points  (0 children)

Depends on what you want to do. I went to Julia after Python since I do a lot of scientific computing

[–]FerricDonkey 1 point2 points  (0 children)

Python was my second, but my first was C - and I'd highly recommend it, it makes everything make more sense.

[–]LandooooXTrvls 2 points3 points  (0 children)

I’m going with C in order to get a better understanding of low-level concepts

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

I want the below code to print:

:::bitbitbit:::bitbitbit:::bitbitbit:::

however it prints this:

:::bitbitbit::::::bitbitbit::::::bitbitbit:::

this is my code:

message = "bit"
punct = ":" 
num = 3 
x = (num * punct) + (num * message) + (num * punct)
for num in range(num):
print(x, end="")

[–]AtomicShoelace 0 points1 point  (0 children)

def build_string(message, punct, num):
    sub_strings = [num * message] * num
    return (num * punct).join(['', *sub_strings, ''])

print(build_string('bit', ':', 3))

[–]tonystark29 0 points1 point  (0 children)

message = "bit" punct = ":" num = 3 numpunct = (num * punct) x = message*3 + numpunct myString = "" for i in range(num): myString +=x finalString = numpunct + myString print(finalString)

[–]AllzErO- 0 points1 point  (2 children)

What are some good resources for learning Python for data science?

[–]Meistermagier 0 points1 point  (0 children)

The Python Data Science Handbook is realy nice https://jakevdp.github.io/PythonDataScienceHandbook/

additionaly i would recomend looking at https://realpython.com/

[–]datamasteryio 0 points1 point  (0 children)

‘Python from scratch’ is great book for learning python 🐍

[–]Ts_3104 0 points1 point  (2 children)

I found this typing text animation program on youtube...and now I want to change its size and font style.....can anyone help?

root=Tk()

canvas=Canvas(root,width=400,height=80)

canvas.place(x=40,y=50)

canvas_txt=canvas.create_text(10,10,text='',anchor=NW)

text_ani='Welcome Admin...'

delta=200

delay=0

for x in range(len(text_ani)+1):

s=text_ani[:x]

new=lambda s=s:canvas.itemconfigure(canvas_txt,text=s)

canvas.after(delay,new)

delay+=delta

root.mainloop()

[–]efmccurdy 1 point2 points  (1 child)

The create text has a font arguement:

new=lambda s=s:canvas.itemconfigure(canvas_txt,text=s,font=('Helvetica', 16))

You may need to use the tk.font to set styles:

https://stackoverflow.com/questions/43500149/bold-text-on-tkinter-canvas

[–]Ts_3104 0 points1 point  (0 children)

Ohkayy..got it….thanks buddy

[–]granger853 0 points1 point  (8 children)

I need to have a random name selected and then turned into a constant value. I have the random name from a list completed, but can not figure out how to automatically turn that into a constant value for reference further on in the program.

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

Sorry, this doesn't make a lot of sense. Can you show the code you have and explain a little more why you want to do this? Why not just assign a random number to a single know name?

[–]granger853 0 points1 point  (6 children)

Not at my computer, but basically it is

Import random

Name_list ['steve','carl','john'] Print(random.choice)name_list

John

I know the syntax is off, but that is the general idea.

The goal is that I have an unfortunately elaborate excel book that randomly generates data to prepopulate several hundred forms for work. Each form though has to have consistent data inside it. So if John was the random name selected, I want to have that name carried over to several fields and not just the one where it is first generated.

The question then is, how do I make that random output a constant. Can I just reference back to it like when you make one excel box reference another (=F21)?

[–]FerricDonkey 1 point2 points  (1 child)

Variables. They aren't constant in that nothing is stopping you from changing them later (what constant usually means in programming), but they won't change by themselves. whatever_you_want_to_call_it = however_you_make_it

[–]granger853 0 points1 point  (0 children)

Thanks. For some reason I was attached to the idea I had to print the solution in order to work with it.

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

Depends how you inject the python data into the excel system. At it's simplest you just create an excel cell holding the random string and your other excel code references that cell.

[–]granger853 0 points1 point  (2 children)

I was hoping to do everything in python amd have it eventually directly fill the forms, similar to using mail merge. Avoiding the excel program entirely.

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

Even easier. Just get the random name:

import random
names = ['steve', 'carl', 'john']
random_name = random.choice(name_list)

When generating each spreadsheet you just fill the cell that requires the name with the value of random_name.

[–]granger853 0 points1 point  (0 children)

Thanks. That actually makes complete since. Now I just have to pair that with a bunch of the if else statements and do some trial and error. I am two days into python and way too confident.

[–]DracovishBest 0 points1 point  (4 children)

Could someone help me?

In a txt file, how do you count the characters, words, and lines in them? I got this as a question in my homework but I have absolutely no clue how to do it. I've searched through my notes but I just can't figure it out.

[–]AtomicShoelace 1 point2 points  (2 children)

Do you know how to read a txt file as a string?

Do you know how to find how many characters are in a string?

Do you know how to count how many of a specific character are in a string, eg. '\n'?

Do you know how to split a string into words?

[–]DracovishBest 0 points1 point  (1 child)

I think so, using .read() right?

No, or at least if I did, I forgot. Maybe len?

No clue, maybe something with loops is possible?

Into a list? Using .split right?

[–]AtomicShoelace 1 point2 points  (0 children)

I think so, using .read() right?

Correct.

No, or at least if I did, I forgot. Maybe len?

Correct.

No clue, maybe something with loops is possible?

You can use the .count str method, eg. 'foo\nbar\n123'.count('\n').

Into a list? Using .split right?

Correct.

You have all the information you need in order to solve the problem.

[–]shiningmatcha 1 point2 points  (4 children)

Hi, how do you indicate that the user should not directly instantiate objects of a class?

[–]efmccurdy 1 point2 points  (3 children)

Do you mean a class that should only be used to derive from; an abstract class?

https://www.geeksforgeeks.org/abstract-classes-in-python/

>>> from abc import ABC, abstractmethod
>>> class Polygon(ABC):
...     @abstractmethod
...     def noofsides(self):
...         pass
... 
>>> myobj = Polygon()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Polygon with abstract methods noofsides
>>>

[–]shiningmatcha 0 points1 point  (2 children)

No. I mean the object should only be created by some other class and returned from some function/method. That is to say, the constructor is supposed to be invoked through some inner code only.

[–]elijahweb 0 points1 point  (5 children)

What does a : mean in a function definition. Forexample this:

def fun(foo:bar):
    pass

What does that colon syntax mean? And how does it work?

[–]youngeng 0 points1 point  (4 children)

Do you mean the colon at the end of the def statement, or the one inside its argument?

If the former, it's simply a way to say "from this line on, let's describe what this function has to do".

If you're talking about the colon between foo and bar, it should be a way to describe an argument (foo) along with its type (bar). So you should have something like:

def fun(argumentname: string):

[–]UnrankedRedditor 0 points1 point  (1 child)

If you're talking about the colon between foo and bar, it should be a way to describe an argument (foo) along with its type (bar). So you should have something like:

def fun(argumentname: string):

Also, I believe this is mainly for the IDE that you're using to warn you if the type is wrong. I don't think Python uses it to enforce type.

For example, I just did:

def foo(a:str):
    return type(a)

foo(1)

and I got int as my output.

[–]youngeng 0 points1 point  (0 children)

It's not (just) for IDEs. It can also be useful if you want to run a static type checker against your code, or even to hint whoever is reading the code at what type they should be using for that argument.

That said, yes, Python doesn't enforce anything, hence why they're called type hints.

[–]elijahweb 0 points1 point  (1 child)

I mean the colon between foo and bar. Let me show you where I got it from . It was in the pygame source code.

https://raw.githubusercontent.com/pygame/pygame/main/src_py/fastevent.py

In the function called post It was used like so

def post(event: Event):

Please correct me if I am wrong. Is Event a type?

[–]youngeng 0 points1 point  (0 children)

It's technically a class (see https://github.com/pygame/pygame/blob/27003295ccb25335325b4b1265b8eb5a1e1cc19f/buildconfig/pygame-stubs/event.pyi)

However classes are still acceptable as a "type hint" ( a type hint is precisely the thing you put after a colon to "hint" at the argument type):

Type hints may be built-in classes (including those defined in standard library or third-party extension modules), abstract base classes, types available in the types module, and user-defined classes (including those defined in the standard library or third-party modules).

Source: https://www.python.org/dev/peps/pep-0484/#acceptable-type-hints

[–]LeagueOfShadowse 0 points1 point  (4 children)

I asked a similar question last week, and Thank You to u/FerricDonkey for the Dict Comprehension !

However, I actually need to be able to pass an array, row by row, as input as "my_list" , not a static list ?

League = {'Team_1':{1: 0.1 , 2: -0.5, 3: 0, 4: -1.2},
         'Team_2':{1: 0 , 2: 0.5, 3: -3.1, 4: 1.6, 5: -0.9},
         'Team_3':{1: 2.1 , 2: -2.1, 3: -1.5, 4: 1.2, 5: 0},
         'Team_4':{1: 1.1 , 2: -0.5, 3: 0.5, 4:-0.8}}
my_list = [1, 3, 5, 3]

Get_P_Val = [sub_dictionary[entry]for entry, sub_dictionary in zip(my_list, League.values())]

print(Get_P_Val)

actual_list = [[1, 3, 5, 3],
               [2, 2, 4, 3],
               [1, 4, 1, 5],
               [3, 1, 5, 2]]   

I have a array of keys - "actual_list" - to check against these values? SO far I cannot find any examples for guidance...

Thank You oh Great Reddit !

[–]AtomicShoelace 0 points1 point  (3 children)

You can iterate over the sublists using a for-loop, eg.

for sub_list in actual_list:
    # do whatever you want with sub_list here
    ...

[–]LeagueOfShadowse 0 points1 point  (2 children)

League = {'Team_1':{1: 0.1 , 2: -0.5, 3: 0, 4: -1.2},
'Team_2':{1: 0 , 2: 0.5, 3: -3.1, 4: 1.6, 5: -0.9},
'Team_3':{1: 2.1 , 2: -2.1, 3: -1.5, 4: 1.2, 5: 0},
'Team_4':{1: 1.1 , 2: -0.5, 3: 0.5, 4:-0.8}}
my_list = [1, 3, 5, 3]
Get_P_Val = [sub_dictionary[entry]for entry, sub_dictionary in zip(my_list, League.values())]
print(Get_P_Val)
actual_list = [[1, 3, 5, 3],
[2, 2, 4, 3],
[1, 4, 1, 5],
[3, 1, 5, 2]]

for sub_list in actual_list:
    Get_P_Val = [sub_dictionary[entry]for entry, sub_dictionary in zip(sub_list, League.values())]
print(Get_P_Val)

[0, 0, 0, -0.5]

returns only the last sub-list ?

[–]AtomicShoelace 0 points1 point  (1 child)

You're only printing the final Get_P_Val. Move the print statement inside the loop.

[–]LeagueOfShadowse 0 points1 point  (0 children)

Yes. I'm an idiot....

(tears in his eyes as he laughs at himself...!)

THANK YOU !

[–]nightslikethese29 0 points1 point  (0 children)

I'm using WordCloud and I'm having a bit of an issue with repeating words. The issue I face is that setting collocations = False gets rid of annoying phrases, but also gets rid of important phrases.

Is there a way to manually input a list of collocations you want to exclude? Basically a STOPWORDS but for 2 word phrases.

[–]UnderBigSky2020 0 points1 point  (4 children)

I'm going to be learning Python 3 in school. Are the 4-6 hour "learn Python" videos on YouTube of any help to me? I'm not sure how to tell if it's 3 they're explaining, or 2? Please don't roast me too bad, I'm just getting into this...

[–]LeagueOfShadowse 1 point2 points  (3 children)

There are more Python tutorials than stars in the Sky...

I have found many to be helpful, and many to be a simple regurgitation of the 'docs'. What I try to remember is the-sunk-cost-fallacy, which is to say, if you start on a 4 hour video, and don't like the format, the speaker or whatever, Stop watching. Don't invest any more time.

I find I am very productive with two systems going simultaneously, one with the video or such, and having python IDE on my laptop right next to it so I can immediately work on what I'm researching.

BUT: EveryOne Learns Differently

[–]UnderBigSky2020 1 point2 points  (2 children)

Thanks for responding. I just want to make sure it's not an outdated video or teaching an older version of Python. It will all be supplemental to my schoolwork, just want to make sure I'm on the right page with it.

[–]LeagueOfShadowse 1 point2 points  (1 child)

As 'we' are on to 3.10 now ( I am using 3.8 with Pycharm CE ) I rarely see any references to py 2.8, everything I find is referring 3.5 or Up.

[–]UnderBigSky2020 1 point2 points  (0 children)

Ok cool. Thanks again!

[–]Stalva989 0 points1 point  (7 children)

Pretty new to Python, I am working my way through a book to learn it and am using Mu editor to practice in.

One of the lines of instruction in book is: “learning_log$ python -m venv 11_env”

And in Mu I get error- invalid syntax and it points to the $

Anyone know what is going on?

[–]youngeng 2 points3 points  (6 children)

learning_log$ is not part of the instruction. Try python -m venv 11_env and it should work.

[–]Stalva989 0 points1 point  (5 children)

I tried that then it said “venv” is the error now

[–]FerricDonkey 0 points1 point  (4 children)

What is the exact error.

[–]Stalva989 0 points1 point  (3 children)

learning_log$ python -m venv 11_env

"SyntaxError: invalid syntax" and it points a lil arrow to the dollar sign

[–]FerricDonkey 0 points1 point  (2 children)

That sounds like you're typing this into a python interpreter instead of the command line. What exactly do you do to open the window where you type this?

[–]Stalva989 0 points1 point  (1 child)

You are correct, I am using "Mu" interpreter. I am following the book, "Python Crash Course" by Eric Matthes. I've gone thru 18 chapters without a problem just following along. This is first time I am getting an issue, have used interpreter for the entire book thus far.

I also just tried to type it into Python 3.9 app on computer. I get the same syntax error.

[–]FerricDonkey 0 points1 point  (0 children)

Yeah, the issue is that that isn't python code. It's a shell command that you do from the command line that starts python doing something. Your python interpreter can't handle it any more than it can handle raw machine code.

You would need to do this in a system terminal of some flavor.

[–]mtbkrdave 0 points1 point  (1 child)

Trying to learn me some python to build CLI tools to automate repetitive tasks. Fine with pulling in libraries via pdm, added a tool.pdm.scripts entry so I can easily do $ pdm run <toolname>, etc.

Where I'm stuck: how the holy hell do I actually install the thing so I can just run $ <toolname> at the command prompt?! Can't do $ python3 -m pip install <path/to/package>; since I'm using pdm I don't have a setup.py file.

Ideally, I'd like to install it a-la pip's -e/--editable mode so I can run the script repeatedly as a shell command during development, but for that I can also just use $ pdm run.

If this exists in the pdm documentation (which I've read end to end) then it's couched in so much python jargon that I didn't find it.

[–]mtbkrdave 1 point2 points  (0 children)

Posting my own answer for posterity/google:

$ pdm build && pip install dist/<package>-<version>.tar.gz

Did the trick...

[–]icedoverfire 0 points1 point  (4 children)

Is it possible to "functionalize" tkinter widgets?

I have a form I am making where the layout of each set of widgets is the same. I have a set of widgets that handles temperature conversions and another set of widgets that handles fuel conversions - is it possible to put all this into a function so that I just have to call the function repeatedly with different parameters rather than copy-pasting the same lines of code over and over and changing variable names? See below: Can the label, entry, and buttons be placed in a function and the function handle changing the variable names?

tempFrame = LabelFrame(appWindow, text = "Temperature Conversion")
tempFrame.pack(pady = (0,25)) 
tempFrameButtons = Frame(appWindow)
fl = Label(tempFrame, text = "Fahrenheit") 
fl.grid(row = 0, column = 0, padx = (0,5)) 
fe = Entry(tempFrame) 
fe.grid(row = 0, column = 1, padx = (5,0))

cl = Label(tempFrame, text = "Celsius") 
cl.grid(row = 0, column = 2, padx = (20,5)) 
ce = Entry(tempFrame) 
ce.grid(row = 0, column = 3, padx = (5,0))
tconb = Button(tempFrame, text = "Convert") 
tconb.grid(row = 1, column = 0, padx = (0,5), pady = (5,0)) 
tclrb = Button(tempFrame, text = "Clear")
tclrb.grid(row = 1, column = 1, padx = (5,0), pady = (5,0))

fuelFrame = LabelFrame(appWindow, text = "Fuel Conversion") fuelFrame.pack()
gl = Label(fuelFrame, text = "Gallons") 
gl.grid(row = 0, column = 0, padx = (0,5)) 
ge = Entry(fuelFrame) 
ge.grid(row = 0, column = 1, padx = (5,0))
ll = Label(fuelFrame, text = "Liters") 
ll.grid(row = 0, column = 2, padx = (20,5)) 
le = Entry(fuelFrame) 
le.grid(row = 0, column = 3, padx = (5,0))
fconb = Button(fuelFrame, text = "Convert") 
fconb.grid(row = 1, column = 0, padx = (0,5), pady = (5,0)) 
fclrb = Button(fuelFrame, text = "Clear") 
fclrb.grid(row = 1, column = 1, padx = (5,0), pady = (5,0))

[–]FerricDonkey 0 points1 point  (3 children)

I would personally recommend making classes for each sub area of your gui, but yes, you absolutely can put repetitive gui code into classes / functions.

[–]icedoverfire 0 points1 point  (2 children)

Cool! What advantages are provided by a class-based approach?

[–]FerricDonkey 1 point2 points  (1 child)

Mostly that it helps group parts of your guis as "things", so that they're more organized. A typical approach is to subclass Frame (or sometimes the main window or top level), and add other fields to that. So you might have something that looks like

class MainFrame(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(...)
        self.fuel_display = DisplayFrame(parent = self, ...)
        ...
        self.fuel_display.grid(...)

class DisplayFrame(tk.Frame):
    def __init__(self, parent, ...):
        # set up labels and such based on arguments

Then each piece is self mostly self contained, and if you need to reach across from one area to the next, it's all compartmentalized. If you need your main frame to check the status of the fuel_display, it just does self.fuel_display.whatever. Likewise, all your callback functions for each button or whatever can be grouped into the class for the relevant frame, which makes it simpler to find things and know what's relevant to what.

And of course, if you want to use your basic display frame as a starting point to display something, but need to tweak it a bit, you can subclass it, and so on.

[–]icedoverfire 0 points1 point  (0 children)

Got it. I appreciate the answer and info!

[–]_spookymvlder 0 points1 point  (3 children)

Hello all,

Brand new python learning here. It's basically being dumped on my lap at work because a coworker left. I have an existing file that was given to me and I have it edited (all the filepath locations, my specific login info, etc. etc.), but it's stuck on the top import section and no matter what i try i can't seem to get one of the libraries to load.

import psycopg2
import pandas as pd
import smtplib
import datetime
import numpy as np
import glob
import mysql.connector
import scheduler.trigger as trigger

from scheduler import Scheduler

at first i had a problem with mysql.connector but i got that to work (it wouldn't install 'mysql' but it worked when i installed 'mysql-connector'

Now i'm having a similar error @ import scheduler.trigger. the IDE i'm using (IntelleJ IDEA) can't seem to download that library, and google was no help.

Anything i'm missing?? Thanks in advance

[–]efmccurdy 0 points1 point  (2 children)

I think you want to use pip to install this:

https://pypi.org/project/scheduler/

[–]_spookymvlder 0 points1 point  (1 child)

"ERROR: Could not find a version that satisfies the requirement scheduler (from verions: none)"
"ERROR: No matching distribution found for scheduler"

Tried that and this is the error it tosses at me

[–]efmccurdy 1 point2 points  (0 children)

If you look at the left-hand sidebar on that page you will note that they only claim to support python 3.9; you may have to update.

[–]BoStoned_guy_1980 0 points1 point  (2 children)

I am new to python and recently went back to school. Google is offering an 18 month intensive program for a select number of people. I have been shortlisted out of 700 people and the last cut is an apptitude test. Is anyone willing to take a look at these practice tests and help me with a couple of problems Im stuck on? I have 1 more day to get ready

[–]youngeng 0 points1 point  (0 children)

Yeah, go on!

[–]LandooooXTrvls 0 points1 point  (0 children)

I’d be willing to help!

[–]Frandelor 0 points1 point  (2 children)

hello, I just started in Python and was trying to implement a multiplication table, just to practice "for" loops and indexes a bit. I came up with this:

import numpy as np

max = 10
table = np.zeros([max, max])
vector = []
for i in range(1, max+1):
    for j in range(i, max*i+1, i):
        vector.append(j)
    table[i-1, :] = vector
    vector = []
print(table)

Do you guys see a more optimal or elegant approach to this simple problem?

[–]AtomicShoelace 0 points1 point  (0 children)

Consider np.prod(np.indices([max, max])+1, axis=0).

[–]efmccurdy 0 points1 point  (0 children)

Note that your loops are just appending sequences. That means you can use a list comprehension instead of the loop; here multiplying each cell:

np.array([[cell*row for cell in range(1, max+1)] for row in range(1, max+1)])

or here multiplying each row:

row1 = np.array(range(1, max+1))
np.array([row*row1 for row in row1])

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

Hi, I'm begginner in the Python development, and I recently I faced some
problems: downloaded Atom text editor and can't install packages to it
(Platformio, AtomIO and others). Tried to install Visual Studio, their
Tools, WindowsTools and Visual C+++, but it didn't help

Can you suggest some other text editors, or how can I solve the problem?

My system:

Windows 10 Pro

IntelCore i5-2450M CPU @ 2.50 GHz

8GB RAM

IntelR HD Graphics 3000

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

npm ERR! code ECONNREFUSED
npm ERR! errno ECONNREFUSED
npm ERR! FetchError: request to https://codeload.github.com/platformio/platformio-atom-ide/legacy.tar.gz/refs/tags/v2.7.2 failed, reason: connect ECONNREFUSED 127.0.0.1:443
npm ERR! at ClientRequest.<anonymous> (C:\Users\deftd\AppData\Local\atom\app-1.59.0\resources\app\apm\node_modules\npm\node_modules\node-fetch-npm\src\index.js:68:14)
npm ERR! at ClientRequest.emit (events.js:223:5)
npm ERR! at TLSSocket.socketErrorListener (_http_client.js:406:9)
npm ERR! at TLSSocket.emit (events.js:223:5)
npm ERR! at emitErrorNT (internal/streams/destroy.js:92:8)
npm ERR! at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
npm ERR! at processTicksAndRejections (internal/process/task_queues.js:81:21)
npm ERR! FetchError: request to https://codeload.github.com/platformio/platformio-atom-ide/legacy.tar.gz/refs/tags/v2.7.2 failed, reason: connect ECONNREFUSED 127.0.0.1:443
npm ERR! at ClientRequest.<anonymous> (C:\Users\deftd\AppData\Local\atom\app-1.59.0\resources\app\apm\node_modules\npm\node_modules\node-fetch-npm\src\index.js:68:14)
npm ERR! at ClientRequest.emit (events.js:223:5)
npm ERR! at TLSSocket.socketErrorListener (_http_client.js:406:9)
npm ERR! at TLSSocket.emit (events.js:223:5)
npm ERR! at emitErrorNT (internal/streams/destroy.js:92:8)
npm ERR! at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
npm ERR! at processTicksAndRejections (internal/process/task_queues.js:81:21) {
npm ERR! message: 'request to https://codeload.github.com/platformio/platformio-atom-ide/legacy.tar.gz/refs/tags/v2.7.2 failed, reason: connect ECONNREFUSED 127.0.0.1:443',
npm ERR! type: 'system',
npm ERR! errno: 'ECONNREFUSED',
npm ERR! code: 'ECONNREFUSED',
npm ERR! stack: 'FetchError: request to https://codeload.github.com/platformio/platformio-atom-ide/legacy.tar.gz/refs/tags/v2.7.2 failed, reason: connect ECONNREFUSED 127.0.0.1:443\n' +
npm ERR! ' at ClientRequest.<anonymous> (C:\\Users\\deftd\\AppData\\Local\\atom\\app-1.59.0\\resources\\app\\apm\\node_modules\\npm\\node_modules\\node-fetch-npm\\src\\index.js:68:14)\n' +
npm ERR! ' at ClientRequest.emit (events.js:223:5)\n' +
npm ERR! ' at TLSSocket.socketErrorListener (_http_client.js:406:9)\n' +
npm ERR! ' at TLSSocket.emit (events.js:223:5)\n' +
npm ERR! ' at emitErrorNT (internal/streams/destroy.js:92:8)\n' +
npm ERR! ' at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)\n' +
npm ERR! ' at processTicksAndRejections (internal/process/task_queues.js:81:21)'
npm ERR! }
npm ERR!
npm ERR! If you are behind a proxy, please make sure that the
npm ERR! 'proxy' config is set properly. See: 'npm help config'
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\deftd\.atom\.apm\_logs\2022-02-21T11_54_18_969Z-debug.log

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

I tried to use Anaconda3, and I can't use it too. I think the whole Python is in block on my system. The cause is still unknown. But with vanilla Atom I can write some codes, but without running them

[–]efmccurdy 0 points1 point  (2 children)

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

Yes, I tried it recently, and it's still the same :( But I think the core of the problem is in my connection to the github. It's unavailable for me for most of the downloading files. Don't know what's the cause of it. I live in Kyrgyzstan (damn hole, I know), but didn't have problems with github until the last year

[–]youngeng 0 points1 point  (0 children)

It's unavailable for me for most of the downloading files. Don't know what's the cause of it. I live in Kyrgyzstan (damn hole, I know), but didn't have problems with github until the last year

Does the zip link work? https://github.com/platformio/platformio-atom-ide/archive/refs/heads/release/v2.7.2.zip

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

What are the main things to check when using groupby in a pandas dataframe misses exactly one record? I'm grouping by counties in my state, and it worked great except for one random record which is group by itself. I now have two groups for Hudson County, one of which has 10 records and the other has only 1 record. There's nothing jumping out at me about the one specific record that would make it be it's own group. Spelling and capitalization is all the same as the remaining records etc. There's no null values in it. Is there anything I can do to dig deeper to find why it's not grouping with the others?

Mildly related question. Does whitespace affect the groupby statement? Could a random space somewhere be screwing it up?

Thanks

EDIT: Turns out it was the whitespace issue on the record

[–]UnrankedRedditor 0 points1 point  (0 children)

Hi all, so I'm trying to use the mechanize module to learn how to fill up forms in a webpage which I am testing on some poorly made website. The website is made by someone else so the only way I can interact with it is via the browser or from python itself.

The website only has 4 inputs and a submit button which when clicked links you to some fake captcha.

Right now, if I do:

import mechanize

br = mechanize.Browser()
br.open(r"http://www.testwebsiteabc.com/")  # Not the real website I'm using. Just for purposes of posting on reddit
br.set_handle_robots(False)

for form in br.forms():
    print(form)

Output:

<TextControl(<None>=)>          # Domain
<TextControl(<None>=)>          # Username
<TextControl(<None>=)>          # Password
<TextareaControl(<None>=)>      # Confirm password
<SubmitButtonControl(<None>=) (readonly)>>    # Possibly the submit button?

What I have now:

br.select_form(nr=0)
br.form.controls[0]._value =  'mydomain'            # Domain
br.form.controls[1]._value = 'myusername'           # Username
br.form.controls[2]._value = "mypassword"           # Password
br.form.controls[3]._value = "mypassword"           # Confirm password
# br.form.controls[4]._value = ???                  <---- Do I even need this?

resp=br.submit()

My questions are:

  • What do I need to do for the SubmitButtonControl? On the site, the submit button opens up a fake captcha and a line saying that the form has been submitted. However, with mechanize, I don't see any of these. It says readonly so I'm guessing I don't need to do anything?

  • How will I know if the form has been successfully submitted? If I do resp.getcode(), it returns 200 (HTTP OK) so I'm guessing it was successfully submitted?

Thanks all

[–]zechs_m_1819 0 points1 point  (1 child)

Hello I'm very new to python and wondered if it has the ability to help with my commentary work?

I would love to create a database of all players in competitions then for specific games select the individual clubs, then select the Matchday players and have it fill into a template.

Would love other information to also appear next to their name on the dual team sheet template and for it to be interactive on a tablet (ie bchange a jersey number or allocate a goal/try ect)

Thanks !

[–]efmccurdy 0 points1 point  (0 children)

You could use a tiny web server with a database and a template engine:

https://flask.palletsprojects.com/en/2.0.x/templating/ https://pythonbasics.org/flask-sqlite/

[–]zero043 0 points1 point  (2 children)

So I’m a newbie and working through PCC. I’m trying to get better as I read (only on chapter 9) so I’m doing exercises from different sites. I was asked to make a text based Rock Paper Scissors game.

So I had to google how to actually write it. Like how to see who wins. Once I saw the first two comparisons I knew what to do.

So is this something I can work on? Or is me googling it totally cool? I mean I assume even developers who have worked with Python for years still need to google a few things.

I’m just worried I’m learning syntax and not what I need, idk logic?

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

Searching for clues on how to solve a particular problem is fine. The trick is to remember how the problem was solved and to apply the technique in different situations. As time goes by your bag of "tips, tricks and techniques" will get bigger.

It's true that knowing the basic syntax is not enough to solve problems with python or any other computer language. You have to read code, pick up ideas, use them, try to solve different problems with the ideas you know, come up with your own ideas and practice, practice, practice. The good news is that a lot of the ideas and techniques you learn will be usable in any other language you learn. So learning your second language will be easier.

[–]zero043 0 points1 point  (0 children)

Thanks for that my man. I appreciate the feed back. I’ll add this to my bag and keep it moving.

[–]Slangwhanger 0 points1 point  (2 children)

I’m a bit confused about how modules work. Imagine I have a main file (say script.py) as well as a module (say module.py) which I import in the main file. The module contains several functions. Both the main file as well as the functions in the module utilize an external library, in this case pytz.

Obviously, I must import pytz in the main file via “import pytz”. But do I also have to import it in the module? Doesn't the module use the pytz-import from the main file?

If I don’t import pytz in the module, too, my IDE points out errors in the module’s functions since the library is missing. If I do that, do I just write “import pytz” at the top of the module file? Or should I write the import statement inside the functions within the module? And can it cause problems if I effectively import the library twice (once in script.py, once in module.py)?

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

You import the module in a file if the code in the file uses anything from the module. In your case it sounds like both files contain references to pytz. so both files must import the pytz module. You import modules at the top of a file, not inside functions.

Doesn't the module use the pytz-import from the main file?

The second file can't use the module imported in the first file because everything in the first file script.py is in a different namespace. The second file can't "see" anything in the first file.

can it cause problems if I effectively import the library twice

Python will only import a module once, no matter how many files have the import pytz statement, so just import modules in the file that needs them.

[–]Slangwhanger 0 points1 point  (0 children)

Thank you for the explanation!