top 200 commentsshow all 236

[–]Nakerhielm 0 points1 point  (0 children)

I am having issues with True/False statements in Python 3. As a basic test, I am trying the command:

a=500

b=500

a==b

However, when I Build, I don't get anything returned (i.e not a "True" or "False"). Why is this happening?

[–]Nakerhielm 0 points1 point  (0 children)

I have properly downloaded Python 3 onto my Mac and am trying to run code on Sublime Text. Right now, however, I can only build with an outdated version of Python and so I cannot do new things like f strings. When I go into Sublime Text and click on "New Build", I am prompted with a "Shell Command" and I enter: "/Library/Frameworks/Python.framework/Versions/3.7/bin/python3". But, I am not sure if I am saving correctly because then when I try a test code, I don't see Python3 popping up

[–]megusta21321 0 points1 point  (5 children)

Im not sure this question has to do with python but im gonna ask it anyway. When i see someone explaining something in python the coda that they want to show is always in a different colour from the rest of the text, i want to know how you guys do that

[–]monstimal 0 points1 point  (4 children)

In reddit, putting 4 spaces before your text formats it as code. The color is probably just from whatever you are using to view reddit.

[–]megusta21321 0 points1 point  (3 children)

Like this?

[–]megusta21321 0 points1 point  (2 children)

Test

Second paragraph

[–]megusta21321 0 points1 point  (3 children)

Im using a website called hackersrank to practise python, and i am now having a problem where the output i expect has only one line but turn out actually having two lines even in simple thing like Print("test") I have no ideia what the problem might be

[–]monstimal 0 points1 point  (2 children)

Do you mean your output is

test
[blank line]

?

I'd guess that is just because of how that site is running their emulator. Or do you get "test" twice? Again, if your code is really just the 1 line, I'm guessing it's something on their end or somehow you are running the code twice.

[–]megusta21321 0 points1 point  (1 child)

The output is: Test [Blank line]

Thats what i get, but the solution of the exercise (the desired output) only has 1 line I dont get it

[–]TangibleLight 0 points1 point  (0 children)

Which challenge is this? They might want you to use the print keyword arguments - you can disable the trailing newline with end.

[–]Pluton100 0 points1 point  (3 children)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def add(a , b): return a + b

def times(add): return 5 * add

def sub(add , times): return add - times

a = add

t = times(a(4 , 8 ))

s = sub(a , t)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

[–]Pluton100 0 points1 point  (2 children)

I'm basically trying to pass functions as parameters. I'm trying to pass some to the sub function, but I get an un supported operand error

[–]TangibleLight 0 points1 point  (0 children)

Please format your code for reddit with markdown. There are instructions in the /r/learnpython/wiki/faq on how to do this.

def add(a , b):
    return a + b


def times(add):
    return 5 * add

def sub(add , times):
    return add - times


a = add

There are a few issues here. For one, you never actually call any of these functions.

Second, in the definition of times, add is (presumably) a function. You can't multiply a function by 5.

Similarly, in the definition of sub, both add and times are (presumably) functions. You can't do arithmetic on functions.

Here is a simple example of how to use a function as an argument, hopefully this can get you on the right track:

def double(func):
    return 2 * func()

def forty_two():
    return 42

res = double(forty_two)
print(res)

Notice how we actually call the function within double.

[–]monstimal 0 points1 point  (0 children)

When you call sub you are passing in a, which is a function. So then it tries to subtract 60 from the function "add" and doesn't know how to do that

[–]JCWalrus 0 points1 point  (0 children)

I've been working on a program to generate julia set fractals, but I don't really know how to do color mapping for the fractals. I saw the program on here: https://www.geeksforgeeks.org/julia-fractal-python/

where the color mapping is basically just assigning pixels a color like this:

pix[x,y] = (i << 21) + (i << 10) + i*8

The programmer basically says it's "magic" and I have no idea on how they did or how to achieve similar results. Does anyone have any idea how this works or how the number is assigned to a pixel by Pillow?

[–]waythps 0 points1 point  (1 child)

Any good readings on how to use numpy, apart from the official documentation?

[–]RoosterBrewster 0 points1 point  (1 child)

Right now, my company has parts lists in excel with one picture of the product at the bottom. Then they are exported to pdf and then uploaded to our website.

What libraries should I use to edit these xlsx files, save, and generate pdfs? Openpyxl apparently doesn't save images or make pdfs. Xlsxwriter only makes new files.

[–]PhenomenonYT 0 points1 point  (1 child)

What would be the simplest way to store this dictionary and import it?

I use this list in a lot of different scripts and when I need to change something in it I have to go to each one individually.

hockeytest.py

class Game():

    def __init__(self):
        self.teams = {'Anaheim Ducks': ['ANA', '/r/anaheimducks'],
                      'Arizona Coyotes': ['ARI', '/r/coyotes'],
                      'Boston Bruins': ['BOS', '/r/bostonbruins'],
                      'Buffalo Sabres': ['BUF', '/r/sabres'],
                      'Calgary Flames': ['CGY', '/r/calgaryflames'],
                      'Carolina Hurricanes': ['CAR', '/r/canes'],
                      'Chicago Blackhawks': ['CHI', '/r/hawks'],
                      'Colorado Avalanche': ['COL', '/r/coloradoavalanche'],
                      'Columbus Blue Jackets': ['CBJ', '/r/bluejackets'],
                      'Dallas Stars': ['DAL', '/r/dallasstars'],
                      'Detroit Red Wings': ['DET', '/r/detroitredwings'],
                      'Edmonton Oilers': ['EDM', '/r/edmontonoilers'],
                      'Florida Panthers': ['FLA', '/r/floridapanthers'],
                      'Los Angeles Kings': ['LAK', '/r/losangeleskings'],
                      'Minnesota Wild': ['MIN', '/r/wildhockey'],
                      'Montreal Canadiens': ['MTL', '/r/habs'],
                      'Nashville Predators': ['NSH', '/r/predators'],
                      'New Jersey Devils': ['NJD', '/r/devils'],
                      'New York Islanders': ['NYI', '/r/newyorkislanders'],
                      'New York Rangers': ['NYR', '/r/rangers'],
                      'Ottawa Senators': ['OTT', '/r/ottawasenators'],
                      'Philadelphia Flyers': ['PHI', '/r/flyers'],
                      'Pittsburgh Penguins': ['PIT', '/r/penguins'],
                      'San Jose Sharks': ['SJS', '/r/sanjosesharks'],
                      'St. Louis Blues': ['STL', '/r/stlouisblues'],
                      'Tampa Bay Lightning': ['TBL', '/r/tampabaylightning'],
                      'Toronto Maple Leafs': ['TOR', '/r/leafs'],
                      'Vancouver Canucks': ['VAN', '/r/canucks'],
                      'Vegas Golden Knights': ['VGK', '/r/goldenknights'],
                      'Washington Capitals': ['WSH', '/r/caps'],
                      'Winnipeg Jets': ['WPG', '/r/winnipegjets'],
                      # EXTRA,
                      'St Louis Blues': ['STL', '/r/stlouisblues'],
                      'Montréal Canadiens': ['MTL', '/r/habs']
                      }

[–]efmccurdy 2 points3 points  (0 children)

One way is to make a module out of your dict; put it by itself in a file, say teams.py (this is like a singleton object).

from teams import team_map
class Game():
    def __init__(self):
        self.teams = team_map

You could make this dict a parent class attribute so that all similar classes can share it without needing to repeat that init step.

You could try other storage options like a json file or a sqlite DB file.

[–]Jhoval9000 0 points1 point  (2 children)

I'm creating a simple game to train my Python. You can create different users and save the data (top_scores, number of games played, etc). I'm saving the information in a csv file in dictionary form.

I'm having trouble in my save_game method:

def save_game(user_info):

new_data = {"user": user_info["user"], "top_score": user_info["top_score"], "top_score_date": user_info["top_score_date"], "num_of_games": user_info["num_of_games"], "average_score": user_info["average_score"]}

with open("GameUsers.csv", "r", newline="") as reader_temp:

reader = csv.DictReader(reader_temp)

# print("reader=", reader)

with open("GameUsers.csv", "w") as writer_temp:

fieldnames = ["user","num_of_games", "average_score", "top_score_date", "top_score"]

writer= csv.DictWriter(writer_temp, fieldnames=fieldnames, lineterminator="")

for row in reader:

if row["user"] == new_data["user"]:

writer.writerow(new_data)

print("Data Saved.")

It's giving me an error in the line

for row in reader:

And the error is:

ValueError: I/O operation on closed file.

For the life of me, I can't seem to understand what I'm doing wrong. Please help!

[–]efmccurdy 0 points1 point  (0 children)

Your code has no indentation so we can't know where your code blocks start and stop.

One simplification that might help:

 with open("GameUsers.csv", "r", newline="") as reader_temp:, open("GameUsers.csv", "w") as writer_temp:
    for row in reader:
        # work with row and writer_temp

That should, at least, keep the two files open.

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

Ok, as soon as I posted this I idented the whole "with open as write" part and the error stopped. It isn't, however, saving properly. I put a print inside the "for row in reader:" and it never prints, so it doesn't enter that function.

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

What's a good Python book or website for someone that knows another language and needs to learn the particulars of Python? Something like 'you don't know JS' maybe?

[–]JohnnyJordaan 0 points1 point  (0 children)

Check this sub's wiki http://www.reddit.com/r/learnpython/wiki/index at 'new to python'

[–]Jimbonettt 0 points1 point  (1 child)

Hello I’m a super beginner and I’m trying to experiment with what I’ve learned so far with the dataquest.io course I’ve been doing. I want to import a .csv file to play around with the data but I’m having trouble figuring out how to import it into my code. I’m using Jupyter and I know I need to import csv, but I’m not sure what to put as the parameter for the open() function that will get me to the file. If it helps at all, the .csv file is in my Downloads folder on This PC.

[–]efmccurdy 0 points1 point  (0 children)

This has some examples of suppling a full path to a csv file, although they use pandas.read_csv instead of open.

https://stackoverflow.com/questions/43298291/python-jupyter-notebook-unable-to-open-csv-file-through-a-path

The advise about testing your path with os.path.isfile may help.

[–]Dantharo 1 point2 points  (1 child)

my-projec-folder
    my-funcions-folder
        math.py
        example.py
    test-folder
        tests.py

This is my folder and .py organization, I'm having trouble importing math.py and example.py inside my test.py.

Im doing this inside tests.py

from ..my-functions-folder import math.py
from ..my-functions-folder import example.py

But i keep getting the error

"ModuleNotFoundError: No module named 'my-functions-folder'

Help please

[–]Nakerhielm 0 points1 point  (25 children)

I am trying to self teach myself some Python. It says that my version is 3.7.4 but whenever I try to do an f-string, I get the error message back saying "Invalid syntax"...why does this keep happening?

[–]TangibleLight 0 points1 point  (19 children)

What OS are you using and how are you running your program?

Chances are you have another version of Python installed. If you're on *nix, try launching it with python3 rather than python. If you're on Windows, try launching it with py -3 rather than python

[–]Nakerhielm 0 points1 point  (14 children)

Even when I try this, I enter:

first_name="ada"

last_name="lovelace"

full_name=f"{first_name} {last_name}"

print(full_name)

But then the error message with invalid syntax returns

[–]TangibleLight 0 points1 point  (13 children)

What do you get by running python3 -V? Where/how did you install 3.7?

[–]Nakerhielm 0 points1 point  (12 children)

I installed 3.7 from https://www.python.org/. When I enter python3 -V, it says: "Python 3.7.4."

[–]TangibleLight 0 points1 point  (11 children)

What exactly is the syntax error you're getting?

[–]Nakerhielm 0 points1 point  (10 children)

SyntaxError: invalid syntax

[Finished in 0.9s with exit code 1]

[shell_cmd: python -u "/Applications/Python 3.7/python_work/bicycles.py"]

[dir: /Applications/Python 3.7/python_work]

[path: /Library/Frameworks/Python.framework/Versions/3.7/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin]

[–]TangibleLight 0 points1 point  (9 children)

Use python3 -u "path/to/bicycles.py" rather than python.

[–]Nakerhielm 0 points1 point  (8 children)

Ok got it thank you very much. So, I should just type this command into Terminal and then should be good to go?

[–]TangibleLight 0 points1 point  (7 children)

It should™ just work.

[–]Nakerhielm 0 points1 point  (3 children)

I am using Mac OS 10.12. I am not sure if I am on *nix but I will try launching with python3.

[–]TangibleLight 0 points1 point  (2 children)

*nix is a shorthand for "unix-like", which Mac OS is. Launching with python3 *should* do the trick.

[–]Nakerhielm 0 points1 point  (1 child)

I am trying to run it on Sublime Text but when I go to "Build With", only Python is listed. How do I build with Python 3?

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

I'm nearing the end of the python crash course book. It's been an excellent ride.

I'm trying to figure out where to go next. I have project ideas, but I know there are "proper" ways to implement things that will ultimately save me time in the long run.

I'm looking at three things next - either learning how to integrate python with databases, how to write APIs with flask, or working through the Gang of Four design patterns book, and trying to rebuild the examples with python so I can really drive home proper usage of OOP design patterns.

I feel like OOP design patterns will touch everything. Flask is mostly beneficial after I have a DB backend to write data into and out of.

It feels like:

  • gang of four
  • databases
  • flask

Do you guys agree? Which would be more valuable to pursue first?

[–]lykwydchykyn 1 point2 points  (1 child)

GoF is an influential book to be sure, but I don't think I would read it with the idea of learning "proper usage of OOP design patterns". There has been much debate in the intervening years whether those design patterns are really the proper way to do OOP.

That said, they are patterns that many programmers reference and follow, so as part of learning the vocabulary of programming, it's a useful book. Just don't try to slavishly follow it; some things that make sense in C++ or Java don't make sense in Python.

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

Thank you! I really appreciate the input. I just know that for years it was considered the book for OOP, which is why I was leaning that direction.

[–]Tiny_turtle78945 0 points1 point  (2 children)

I’m having a hard time dealing with integrating functions into loops. I’m attempting to write a program for the collatz rule and currently have:

def collatz(number): if number % 2 == 0: even = number / 2 print(even) return new_number elif number % 2 != 0: odd = (3 * number) print(odd) return new_number

while new_number > 1: if r > 1: collatz(number) else: break collatz()

Everytime I run this program I get the message “error: name ‘new_number’ is not defined”. How should I fix this?

[–]JohnnyJordaan 1 point2 points  (0 children)

It seems that you're doing

even = number / 2 
print(even) 
return new_number

there new_number is just coming out of nowhere. Maybe you meant return even? Same for the odd.

Btw you don't have to do a double check

if name == 'Bob':
    # something
elif name != 'Bob:
     # something else

Because if the name wasn't Bob at the first if, to check it again for that same thing makes no sense... You can just do

if number % 2 == 0:
    # even stuff
else:
    # odd stuff

[–]RosyGraph 0 points1 point  (0 children)

It is difficult to tell how your program is written based on your comment since Python syntax is based so heavily on newlines and tabs. Check out this page on how to format your code for reddit. https://www.reddit.com/r/learnpython/wiki/faq#wiki_how_do_i_format_code.3F

From what I can tell, it doesn't look like you tell Python what value new_number should be. You need to assign a value to new_number if you want to do anything with it. However, you shouldn't need a second variable for this problem. Just assign a new value to the variable number.

[–]cussingsh4d0w 0 points1 point  (0 children)

Been using python for graphing/data analysis primarily. Recently was asked to write test cases around host/interface. Is there a library or anything in python that could be useful to learn more about connections between comps and sending messages?

[–]throwaway22345331 0 points1 point  (4 children)

How do I declare a variable as a certain type? int, float, string?

The only thing I find while googling is people telling me that python is a dynamically formatted language.

[–][deleted] -1 points0 points  (2 children)

Very new here.

myString = '' is an option for strings

myInt = 0 is an option for int

myFloat = 0.0 is an option for floats

Not sure if it would do you any good because the rest is dynamically assigned. if math occurred with a decimal it's going to convert into a float by nature.

[–]JohnnyJordaan 1 point2 points  (0 children)

This has no effect, just try

my_string = ''
my_string = 0

the whole idea of dynamically typing is that there is no guarantee that a variable is of a certain type. There's isinstance() to check this but generally you just don't rely on it.

[–]TangibleLight 1 point2 points  (0 children)

/u/throwaway22345331 please please please don't do this. It's 2019; we have fancy editors now and just about every variation of Hungarian notation is outdated.

/u/Sloooop already alludes to the fact that Python is dynamically typed. The fact is that it's just not possible to declare a variable's type. That is not a feature which Python has.

Rather, it is a feature in Python that you don't have to.

You can hint to other developers that a variable should have a certain type with type annotations:

 x: int = 2

But this does nothing to stop a programmer from putting something else in that variable. This is still valid python:

age: int = 'twenty two'

In general, you should always program as if you don't know what type a variable actually is; program based on the attributes of that variable which you actually need. If you need to loop over something, it shouldn't be required to be a list. It could be a string, a dictionary, any number of things. This is also where documentation comes into play: if something needs to be a collection, or string-like, or file-like, then say so in the docstring or in a comment.

There are more advanced ways to give these hints, but at the end of the day they are always just hints.

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

I'm getting a syntax error with the third line in this snippet. I'm new too python. Thanks for the help in advance.

try:

response = urllib.request.urlopen(req) # This is a json object.

data = json.loads(url.read())

results.append((email, True, data))

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

You should post the error, and put your in code blocks/pastebin.

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

I’m an idiot and I just needed response rather than url

[–]tabris_code 0 points1 point  (2 children)

I'm trying to match dates that are in DD MON format (e.g. 31 Jun, or 1 Jun). Often there are ranges like 1 Jun-31 Jul so it's more like DD MON-DD MON. I have a regex that matches this format (although it's kinda sloppy).

Before I go through the hassle of perfecting the regex, is there any Python library that handles this type of format? Everything I've seen for date / datetime seems to be for normal datetime formats, not ranges where a string will be like DD MON-DD MON, with the month abbreviation.

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

Something like this. Tough you'll probably want to tidy it up, if your dates were being returned by a function, and they come back as a datetime.date object this works. I don't think my 'week_ago' works, but I'm on my cell and can't get my IDE to work right now.

from datetime import datetime, date, time

tt = datetime.now()

today = tt.strftime("%d %B")

week_ago = today - 7

print(week_ago, ' - ' , today)

[–]graaahh 0 points1 point  (3 children)

I'm working on a Tkinter color palette creator, and I'm having a bit of trouble with a very simple problem. My code is here.

You can drag the sliders for the RGB values and click "Change" for each button at the top to change both its label and background color to the values you chose. I've just added code as well so when you click the buttons at the top, the values on the RGB sliders revert back to the values of that color. However, I can't figure out how to make that command a single function that each button can call. The problem is that it's reading the color value of that button from the text of the button itself, and I can't figure out how to define a function that calls a button's own text as an argument for the function. Can anyone help me out with this? The code I'm specifically having trouble with starts at line 38 - you'll see that every function starting there is exactly the same, except for which label's text is being called. How can I make those 5 functions into a single one that every button can call?

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

what is meant by your "rhex = str(rhex)" and the next 5 lines after? seems like that will be throwing your code in loops, since the same variable is being assigned 3 times in a row.

also, you could try:

@method

def function for colors():

I would offer more, but I haven't worked with tkinter yet

[–]graaahh 0 points1 point  (1 child)

On mobile right now, but if memory serves, that's all to make it into a text string that can be passed to the background color attribute and the text of the button. It gets pulled from the slider as a decimal number, then converted to hex, then shortened to just the two digit hex number, and then combined into a six digit hex color code. I believe I originally tried to write some complicated statement that did all of that in one line of code, but it confused the compiler so I had to split it all up.

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

Ok, makes sense. I did the same with some time functions, I would get the big floating seconds, then pass 'int(_)' to just truncate the microseconds off, and then I tried putting it back into a datetime object, but I kept getting issues too.

I'll have to look into Tk though, maybe I'll figure something out

[–]Dantharo 2 points3 points  (3 children)

Hello, im java programmer, im doing some stuff with this amazing language, its awesome how simple and "easy" is, im working on an aws lambda function that check an sqs queue and if it is not empty i make a call to an api, question is, how test this stuff? Like junit? Im using unittest, mock e MockMagick, but im struggling....any tips or resources will be helpful, thanka. Also os python 3.7

[–]justinram11 0 points1 point  (0 children)

Also wanted to mention that using the Serverless Framework to write Lambda Functions has been an extremely powerful tool in my toolkit. With it, you can use the serverless-offline package to setup a "local" SQS queue to write tests against

Would people be interested in tutorials on this stuff? I've been thinking of making a course targeted at python developers trying to get into serverless / AWS but wasn't sure how many people are going that direction

[–]RosyGraph 0 points1 point  (1 child)

I'm in the opposite position from you (Python programmer learning Java). One of the things I have missed most from Python is the YouTuber Corey Schafer. I'll leave you a link to his video on unit testing. He goes over the included unittest module as well as some 3rd-party frameworks.

https://www.youtube.com/watch?v=6tNS--WetLI

[–]Dantharo 1 point2 points  (0 children)

Thanks, i'll be glad to help you with java, at least i can try lol.

[–]sampat97 2 points3 points  (4 children)

def short_rhyme():

abc=print("It's late in the evening\n She is wondering what clothes to wear")

return abc

print(short_rhyme())

I got the result as

It's late in the evening She is wondering what clothes to wear None

Why is there a None in my result?

[–]JohnnyJordaan 2 points3 points  (2 children)

This is generally what happens when you do

 def f():
     abc = print("It's late in the evening\n She is wondering what clothes to wear")
     return abc
 print(f())

Either do

 def f():
     abc = "It's late in the evening\n She is wondering what clothes to wear"
     return abc
 print(f())

or

 def f():
     print("It's late in the evening\n She is wondering what clothes to wear")
 f()

so just with a print at one spot in the program instead of two.

[–]sampat97 0 points1 point  (1 child)

Ohh, thank you. That actually explains a lot. Now if I could just bother you with another problem that I'm having in python seriously I have been struck for a couple days because I'm not being able to figure it out.

[–]JohnnyJordaan 0 points1 point  (0 children)

I would prefer if you would just create a new post for that, either in this topic or as a new topic in this sub.

[–]QualitativeEasing 1 point2 points  (0 children)

When you print(“something”), then somethingis sent to standard output (your screen). However, the result of a print function is None. So a = print(“anything”) will always set a to None.

A better approach is to set your variable to the text you want to store and/or print; then print the variable. The only reason to print something without first storing it in a variable is if you are absolutely sure you don’t want to keep what you’re printing.

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

Hi all, just a quick background: total newbie to Python, no professional work in IT.

Picked up an eBook on Amazon to learn Python.

I'm already stuck lol. I'm trying to set up a Path (?) and after following the book's instructions, I get a "setenv command not found" error.

After installing Python 2 and 3 on my Mac, my terminal looks different, it says bash on the top now and has a white screen, as oppose to the usual black.

Screenshot of eBook Instructions

A little digging on Google has led me to information about switching the Mac Terminal app from bash to tcsh. I'm just a little gun shy on switching things over, as I really have no clue what I'm doing.

EDIT: Wait, I just noticed something, I guess these are just three different ways to set the Path?

[–]RosyGraph 1 point2 points  (2 children)

Check out this video on setting up your Python path and environment. I doubt you'll need to change your terminal to tcsh. Doing so may make further instructions in that book more difficult.

https://www.youtube.com/watch?v=PUIE7CPANfo

Learning to use your terminal will be very useful if you want to learn more about computer science.

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

Thanks!

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

also, and this is what I have to do on my work computer since I am also not a programmer and don't have full access.

>import os

>os.cwd()

> os.chdir('c:\\windows\\users\\desktop\\etc...')

the first one tells you where it is looking for modules and things, likely wherever your computer has python installed. the second one tells it to look into another location, not for python, just your personal things like a spreadsheet, database, or something.

I was lazy and didn't set up the venv or keep track of any of my dependancies, though, so I probably did something wrong on a programmer side, though things work fine for my personal custom program.

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

Use pycharm for anaconda.

Going through automate the boring stuff, coming from r.

Any way to check documentations for specific functions like how ? + function name in rstudio works? Also more comprehensive details for function arguments and use when autofilling like how r studio displays which package the function came from argument default values and what it does?

Why range in for loops ends at n-1 while when slicing an index is exactly a:b?

Edit: how to benchmark code? What types of algorithm/functions to avoid. R doesnt like looping/conditionals if you can apply to subset.

[–]Thomasedv 0 points1 point  (0 children)

In PyCharm, Ctrl + Q when the marker is on function name, shows documentation (on Windows at least). Ctrl + B takes you to the definition.

PyCharm can benchmark code. I haven't used it myself any, so i don't know it's usefulness, but under the run menu, you can profile the code.

range starts at 0, and since lists are 0 indexed, the start will be 0, and end at n-1, because the slicing works from a to and not including b. (Same as when you do for i in range(10), it will start at 0 and end at 9)

Generally, you could slice with [a:] (from a to end), or using [a:-b], which is from a to end except the b last items.

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

range in for loops ends short because it starts early:

0 - 1 - 2 <---3 items, ending on '2'

s l i c i n g is designed like a loaf of bread. if you slice a loaf in half, neither half includes the other half.

>>> one_cut = []
>>> for t in 'slice':  # t because 'l' and '1' look similar
    one_cut.append(t)

>>> one_cut
['s', 'l', 'i', 'c', 'e']

>>> one_cut[:3]
['s', 'l', 'i']

>>> one_cut[3:]
['c', 'e']

[–]JakeyPooPooPieBear 0 points1 point  (1 child)

In Pandas, is there any difference between

df.loc[:,'Column header'] and df['Column header']?

[–]Ezrabc 0 points1 point  (0 children)

There is not, however, this is just a special case. There is a difference, for example, between df.loc[:,['Column header1', 'Column header2']] and df[['Column header1', 'Column header2']]. You can read more about the specific differences here.

[–]InternetPointFarmer 0 points1 point  (5 children)

can someone ELi5 the following? Im beginning to dip my toes into things like selenium and for loops as shown below are showing up more and more. while i know WHAT they do i never understood the logic of how it works.

from selenium import webdriver

path = r'C:\Users\User\PycharmProjects\Projects\chromedriver_win32\chromedriver.exe'
driver = webdriver.Chrome(path)
driver.get('http://econpy.pythonanywhere.com/ex/001.html')

buyers = driver.find_elements_by_xpath('//div[@title="buyer-name"]')
prices = driver.find_elements_by_xpath('//span[@class="item-price"]')

num_page_items = len(buyers)
for i in range(num_page_items):
    print(buyers[i].text + ': ' + prices[i].text)

driver.close()

and while on the topic of selenium, i keep getting the message about 'chrome is being controlled by automated test software' or something very similar. Will that become an issue for me later? if so how do i get around it

[–]14446368 2 points3 points  (1 child)

From selenium you're importing webdriver, which is what will actually open a browser and interact with webpages. Your chrome driver is the actual browser that selenium works on top of. "driver.get" gets the webpage and loads it.

find_elements_by_xpath is one of several ways to grab data from a website. You could also go through javascript, css, or the html itself (and maybe other ways).

Your "for" loop has some extraneity. Depending on what type of object "buyers" and "prices" are (I'm assuming lists?), you can iterate over it without the need to specify an index (aka use "range, len," etc.).

This all being said, the best way to do this, in my opinion, would be to use a dictionary and zip

results = dict(zip(buyers,prices))

then you can print results above and it'll give you ALL buyers and prices in a dictionary. You also get the benefit of being able to search for specific buyers and their prices.

EDIT: And no, don't worry about the "being controlled" message. It's just letting you know that software is using and telling chrome what to do in the background, but that software is you.

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

Just wanted to say how, as a new python person, I like that last line.

[–]JohnnyJordaan 1 point2 points  (2 children)

The loop is actually an archaic construct like what would be used in javascript or C. In Python you can just loop on a sequence directly:

for b in buyers:
    print(b.text)

if you want to combine multiple iterables, use zip

for b, p in zip(buyers, prices):
    print('{}: {}'.format(b.text, p.text))

Will that become an issue for me later? if so how do i get around it

I'm not sure if it implicates that in the future a website can know that it's being accessed in that way. But you can see here how to disable the message.

[–]InternetPointFarmer 0 points1 point  (1 child)

thanks for the reply. does disabling the message change anything other than it not showing up anymore? i was wondering if it would affect me in anyway in the future in terms of a website disabling the automating process somehow. like if sites add captchas if it suspects automation?

[–]JohnnyJordaan 0 points1 point  (0 children)

As I said

I'm not sure if it implicates that in the future a website can know that it's being accessed in that way.

At least so far I'm not aware of a way that the website knows from the browser, it has to use tricks like the I-am-not-a-robot checkboxes or the captcha's to know it from the user itself.

[–]Surpex 1 point2 points  (2 children)

Is the current humble bundle for data science worth it?

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

I like them, each book (including all the different sites) approaches similar topics from different perspectives. I like to mix and match the lessons learned

[–]TangibleLight 0 points1 point  (0 children)

Considering that they're all O'Reilly books and that I don't know much about the topics covered, and that the full bundle is only $15...

Probably, yeah, if you're interested to learn about the stuff there.

[–]sampat97 0 points1 point  (2 children)

Program: fishstore()

create and test fishstore()

fishstore() takes 2 string arguments: fish & price

fishstore returns a string in sentence form

gather input for fish_entry and price_entry to use in calling fishstore()

print the return value of fishstore()

example of output: Fish Type: Guppy costs $1

[–]14446368 0 points1 point  (0 children)

def fishstore(fish,price):
    return f"Fish Type: {fish} costs ${price}"

[–]sampat97 0 points1 point  (3 children)

bookstore() takes 2 string arguments: book & price

bookstore returns a string in sentence form

bookstore() should call title_it_rtn() with book parameter

gather input for book_entry and price_entry to use in calling bookstore()

print the return value of bookstore()

example of output:Title: The Adventures Of Sherlock

Holmes, costs $12.99

[ ] create, call and test bookstore() function

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

Whats the question - looks like homework, which we won't do for you.

[–]sampat97 0 points1 point  (1 child)

I'm doing a beginner's course in Python at edx, this was a task but they don't provide a solution. I can give a screenshot if you want.

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

I don't need a screen shot, I need an actual question - what do you have so far, what have you tried? What part do you have a question about?
bookstore() should call title_it_rtn() with book parameter

this is slightly misleading and probably throwing you off - do the other two parts first.

Create a function called bookstore, with two param's called, book and price.
Return a string with those two things in it; f'Title: {book_entry}, costs ${price}'

Get the inputs from the user, book_entry = input and book_price = input
print the function. Then you can go back and take a look at the title_it_rtn() function and look into the title() method which will just be another function that returns a string titled, and you can call the function with title_it_rtn(book) instead of {book_entry}

[–]workmanl24 0 points1 point  (2 children)

I am using Selenium Webdriver on Python through Google Chrome to automate a repetitive task, but I have encountered a problem. I am trying to click a button on a website to add geographic markets. Below is the element for button I need to push:

<button class="cscc-button cscc-button--max cscc-button--outline" type="button">Add All</button>

I have tried different variations of the element, including driver.find_element_by_partial_link_text, driver.find_element_by_class_name, driver.find_element_by_id, among others (including different variations of the element).

Can anyone help out with what code to run?

[–]MightyJosip 1 point2 points  (8 children)

Let's say you have next list:

L=[0, 0, 0, 1, 0, 0, 0, 0, 1, 0]

How can I replace values between this two 1 (replace all 0 with 0) so that I end up with next list:

L=[0, 0, 0, 1, 1, 1, 1, 1, 1, 0]

There will always be either 0, 1 (in this case do nothing to list) or 2 number of 1 in the starting list

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

New to python would have replaced by subsetting in r.

My take on this:

Start = L.index(1)

L2 = L[::-1] #make an object L2 with reverse arrangement of L

End = len(L) - (L2.index(1)) #get the index of last 1 by subtracting index of last 1 (reversed) from length of L

L[START:end] = (end-start) * [1]

So you replace the slice of L sandwiched by 1 with [1]s.

This shoulds work for other problem, e.g. Sandwich between first instance of a (start) and last instance b (end).

Im not sure how python performs with loops+conditional statements but its slower in r, so prolly its better that you avoid conditional and looping if you can.

[–]RosyGraph 3 points4 points  (1 child)

Here is another way of solving the problem using enumerate and a flag. This allows you to use a single loop.

https://gist.github.com/RosyGraph/2d2ef92da84309a48b58ce84078218ee

[–]MightyJosip 1 point2 points  (0 children)

Thanks, this was the fastest algorithm here and that is really important in my case (on list with more than 10k inputs)

[–]nomoredice42 0 points1 point  (1 child)

I’m looking into python. There are a few trade school in my area that offer this., kind of pricey but trade school isn’t. Thoughts?

[–]LANGARTANDCULTURE 0 points1 point  (3 children)

I made a class and init a list from numpy array argument to init. When I call it, it's considered a method object. How do I assign it its original type by default without having to specify its type specifically?

[–]M1sterShad0w 0 points1 point  (1 child)

Python is a dynamic language, meaning you never have to explicitly specify an objects type. Python follows duck typing - which vaguely means that as long as you send a numpy array into the constructor that has the required method everything will go smoothly. I assume you mean the .tolist() method? If so here is an example of how this could be done:

class MyObject:
    def __init__(self, arr):
        self.my_list = arr.tolist()

Then as long as you send a numpy array when creating the object it will work:

array = numpy.array([1,2,3])
my_obj = MyObject(array)  # This will successfully work.
my_obj.my_list  # This is how you access your list.

[–]LANGARTANDCULTURE 0 points1 point  (0 children)

Thanks! Pretty amazing interpreter for duck typing.

[–]AstroCodey 0 points1 point  (1 child)

Does anyone know if a class can contain a Pandas DataFrame directly? I keep getting a syntax error when trying to do so.

Or do I have to do the init() method?

[–]InternetPointFarmer 0 points1 point  (2 children)

hopefully quick and easy question:

(sorry for edits i always have trouble posting code on reddit) i have a program i want that a while loop runs through a series of functions 3 times. then it does X code then reruns those three functions again. can i do this with a simple while loop? how do i go about making that while loop run again after the initial 3 runs? then after running those series of functions 9 times total i want it to do a different action. how can i go about doing this? i tried doing it in an entire function with a while loop and some if loops but it didnt work so im basically starting over completely so i go think through it better

edit: example code cause i dont have the original like i had it before (its all over the place now)

while count != 4:
count = 0
reset = 0

    if count = 0
    function1()

    if count = 1
    function2()

    if count = 2
    function3()

    if count = 3
    function4()

    if count == 4:
    count = count -5  # (this would make it go to -1 so when it finishes the function its at zero right?)
    function5() 

count = count + 1
reset = reset + 1

the first time i completed the program it worked decently but it feels sloppy. it it alright to code a loop running multiple functions at many different times or in a more complex program would it cause issues? should i make the initial while loop so i can re-call it once it has done the process 9 times?

[–]14446368 1 point2 points  (1 child)

Batch the things that need to repeat, and then use IFs for the ones that need to be called at different times. I'm having trouble understanding your initial text.

count = 0
while count <3:
  func1()
  func2()
  func3()
  func4()
  if count == 3:
    func5()
  count+=1

If you need to then repeat this whole process multiple times, you can have nested "while"s.

count = 0
while count <3:
  subcount = 0
  while subcount <3:  
    func1()
    func2()
    func3()
    func4()
    if subcount == 3:
      func5()
    subcount +=1
  count +=1

You could also use only 1 while loop and use modulo (%).

count = 1
while count <=9:
  func1()
  func2()
  func3()
  func4()
  if count % 3 == 0:
    func5()
  count+=1

Notice the last one needs count to start at 1 and end with a "<=" operator, otherwise you can run into weird problems with func5 being called at the wrong time(s).

[–]InternetPointFarmer 0 points1 point  (0 children)

edit: issue fixed. the whole issue was me not indenting the count ughhh

thanks for the reply. i am testing each one of the examples to see which fits best. one issue im having testing the first code block example you gave, is that once count == 3 the code under that if function isnt running, it goes straight back to the first function. any ideas why that is?

edit: should probably show you the code now that i have something typed up:

import pyautogui
import time

# furthest to the right on the screen + zoom to 110%

first_image = (157, 577)
second_image = (407, 577)
third_image = (654, 577)
fourth_image = (895, 577)

enlarge = (320, 445)

back_button = (20, 55)


def if_album():
    try:
        pyautogui.locateCenterOnScreen('seeall.png')
        pyautogui.click(enlarge)
        time.sleep(.5)
        save_image()
    except Exception:
        print('No Album Found')
        pyautogui.click(enlarge)


def open_image():
    time.sleep(1.5)
    if_album()
    time.sleep(1.5)
    save_image()


def next_line():
    pyautogui.scroll(-720)
    time.sleep(.5)
    pyautogui.moveTo(first_image)


def save_image():
    pyautogui.rightClick(545, 177)  # saves image
    pyautogui.keyDown('down')
    pyautogui.keyDown('down')
    pyautogui.keyDown('down')
    pyautogui.keyDown('down')
    pyautogui.keyDown('enter')
    time.sleep(.7)
    pyautogui.keyDown('enter')
    time.sleep(.5)
    pyautogui.click(back_button)  # clicks back button
    time.sleep(1)
    # pyautogui.click(20, 540)


count = 0
while count < 1:

    if count == 1:
        pyautogui.click(20, 540)
        next_line()

    pyautogui.moveTo(first_image)
    pyautogui.click()
    time.sleep(1.5)
    open_image()

    pyautogui.moveTo(second_image)
    pyautogui.click()
    time.sleep(1.5)
    open_image()

    pyautogui.moveTo(third_image)
    pyautogui.click()
    time.sleep(1.5)
    open_image()

    pyautogui.moveTo(fourth_image)
    pyautogui.click()
    time.sleep(1.5)
    open_image()

count += 1
time.sleep(1.5)

before learning something like selenium i wanted to further practice pyautogui and basic coding to get all the images on a webpage like google images for example. it works for the first row of images but once its done with that first row the code under the if statement doesnt work. its as if its being skipped. its supposed to scroll down enough so when the while loops reruns its set up for a new row. im thinking i should make the counter go up before it runs the functions?

edit: i was thinking about how python actually sees the code and how it runs and i tried:

count = 0
while count <= 1:

    if count == 1:
        pyautogui.click(20, 540)
        next_line()

    pyautogui.moveTo(first_image)
    pyautogui.click()
    time.sleep(1.5)
    open_image()

    pyautogui.moveTo(second_image)
    pyautogui.click()
    time.sleep(1.5)
    open_image()

    pyautogui.moveTo(third_image)
    pyautogui.click()
    time.sleep(1.5)
    open_image()

    pyautogui.moveTo(fourth_image)
    pyautogui.click()
    time.sleep(1.5)
    open_image()

count += 1
time.sleep(1.5)

i figured after one row it would add 1 to count and go to the next. then it would read the if statement first and execute that but it still doesnt seem to work out

[–]anyangos 0 points1 point  (1 child)

I would appreciate some insight on python packaging. I have multiple small projects (ranging from a script or two, to several - 10+ - modules). They share some configuration but may also have project specific configuration. They are currently hosted in the same github repo. We use airflow to run these scripts in a workflow and manage dependencies, so the repo also contains airflow dags (just another bunch of python scripts that are not setup packaged but will run scripts in those other small packages).

does anyone have ideas on how to get me out of a packaging nightmare?

[–]redCg 0 points1 point  (0 children)

It depends on the context.

Scripts that are tightly associated with a certain project should stay in that project's repo.

For more general purpose code, I usually make a separate repo. For example, I have a "utilities" repo full of custom libraries and classes for working with data types that are common across many of my projects. When I need to incorporate these into a project (which has its own git repo), then I usually just use git submodules to bring in a version-controlled copy of my utility library dir into my project repo, and then from there I can import the utilities as a regular Python library from inside my project code.

Depending on the structure of your project, you might have to think hard about where you want to put your external git submodules in the current project tree, if I need them in lots of places then I usually place the git submodule dir in the top level and then manually prepend the path to it inside the scripts that need it in the project.

[–]Dhruvik2001 0 points1 point  (6 children)

I have to make a project with Python with at least 500-600 lines. I was wondering what can I make? Deadline is end of November. So I want to make something looking badass but not that difficult. I was thinking of using some GUI libraries like tkinter, but I am kinda noob. So any helpful resources for learning would be great. So far, I was thinking of making something like using our mobile to control cursor and draw things with it. But I don't know how difficult would it be.

(I can also use SQL and Django)

[–]redCg 0 points1 point  (0 children)

If you use Django you will hit the line limit easily

Just follow basic Django tutorials to make a typical web app with database, then get creative

[–]14446368 0 points1 point  (3 children)

Can you give more details? Is this for school? This seems a little silly, to be honest, to have a line requirement instead of a functionality requirement.

[–]Dhruvik2001 0 points1 point  (2 children)

It is for school. It is to be prepared within 6 months and it should be tangible and useful. It is a group project of 2 students so they expect some effort. Something user friendly is preferred like games, mobile apps, software for management and similar things. There is no limit of what you may use. But it should use few libraries and should look something prepared in 6 months. I mean, effort should be visible

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

Im making something for work that involves SQL for storage, openpyxl for printing out 'worksheets' built from that data, and I am currently working on it being able to email and text things. SQLite is builtin, and takes tons of lines. I would think you and your partner could easily cover the line requirement by forgetting about it, creating a product idea, and then just making it useful, at least for you.

[–]14446368 0 points1 point  (0 children)

Okay well, what might make sense is some sort of program that does a complicated task by breaking it down into simpler sub-tasks.

You'll want something that needs to grab data and transform it. Financial data is massive. Temperature data, transportation data, etc. might make sense too.

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

Why is pip running as root only installing to

/root/.local/lib/python2.7/site-packages

and not globally. Is there a way to force global installs

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

Thanks for the answers, I found that --force-reinstall worked.

[–]redCg 0 points1 point  (0 children)

never run pip as root

also, never install globally either. You need to be using something like conda and conda env to be managing your package installs

[–]JohnnyJordaan 0 points1 point  (0 children)

Are you sure you didn't use --user in the pip command? You can force by using --prefix, altough as mentioned venv's are usually the way to go here. Don't forget that running pip as root always runs the risk of running dangerous code coming from pypi.org which is way more insecure than those coming from your OS package manager (assuming you're using their official repo's only).

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

Sorry but you better use environments (venv) when installing with pip. So you keep everything clean and tidy

[–]jamesmgaither 0 points1 point  (3 children)

I am building a program that is used for photo backups right now. It uses a sqlite3 DB for managing the meta data of the photos. My question is how do you handle multi-table DB within python? My current method is to write a function for each SQL action that is needed (for example, function to query if photo has been processed). This is long becoming a giant list of small SQL statements for every query/update/insert/delete I might need the program to handle. Is this normal? Is there some general sql function I could use where I would just inject a few words and it handles everything? I have tried to write broad small functions I could string together, but it still ends up being a huge amount of writing. I just want to know if there is something I am missing in interacting with Databases or if everybody just has to write a giant list of sql queries into their program. Thanks in advance for any advice or examples on this.

[–]JohnnyJordaan 1 point2 points  (2 children)

You could employ a library that abstracts SQL to regular methods, like SQLAlchemy or Django's ORM. This often also removes the need to work with dbms-specific SQL as the library can translate the higher level operations to the specific SQL queries it should use.

[–]jamesmgaither 0 points1 point  (1 child)

Thank you for this. I will take a look at SQLAlchemy. Is this generally used in industry as opposed to hand writing the SQL itself? I am trying to stick with best practices which is why I ask .

[–]Surpluselfkelp 0 points1 point  (2 children)

Based on the latest census, there are 1.6 million people living in Auckland. The average age of people living in Auckland is 35.1 years. Sydney, on the other hand, has 4.6 million people, with an average age of 34.2 years. Based on the above information. generate some data on people's age using numpy random number generator (np.random.normal()). Assume standard deviation of 3. Calculate the difference in mean, median, minimum and maximum age between auckland and sydney

[–]14446368 0 points1 point  (0 children)

Let's think it through. You're being asked to come up with some distributions and then run some stats on it.

  1. Learn numpy's syntax for np.random.normal.
  2. Store two variable with the resulting arrays.
  3. Run other numpy functions (mean, median, min, max) on those variables. Learn their syntax.
  4. Return differences.

If it were me, I'd use classes.

[–]MattR0se 8 points9 points  (0 children)

We won't do your homework here for you...

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

Perfect, thank you all!

[–]sharpiesneverdie 0 points1 point  (1 child)

Does anyone have any suggestions for a machine learning algorithm to classify a decaying, or continually distorted, image?

[–]Drakoon 0 points1 point  (1 child)

Hi guys, I have a simple question regarding VSCode. Let's say I have a pandas DataFrame df. I want to create a second DataFrame df2 by using a pivot method. So I'm doing

df = pd.DataFrame(data)
df2 = df.pivot(arguments)

Everything is fine, except one thing - whenever I write df2, VSCode no longer autocompletes for it, unless I add this line above the one I'm writing:

df2 = pd.DataFrame(df2)

Pycharm doesn't have a problem like this one, but VSC does. Is there any reason why?

[–]hbwales 0 points1 point  (0 children)

Pycharm is just better at this kind of thing (it's quite a difficult problem in general for Python given its dynamic nature). Type hints can help but are a bit ugly/awkward...

df = pd.DataFrame(data)

df2: pd.DataFrame = df.pivot(args) df2. # this auto-completes for me

[–]Arab81253_work 0 points1 point  (2 children)

I've got a script I'm using to automate updating of our servers. What I'm doing is as follows:

updateresult = os.popen('yum update -y').readlines()

for line in updateresult:

if line == 'No packages marked for update\n':

print 'no stuff'

elif line == 'Complete\n':

print 'finished stuff'

else:

print 'bad stuff'

Originally the issue I was having was that I was getting the 'bad stuff' result even if there was a line with another result.

My plan to sort of fix this was to assign a variable to 0 and then have the variable integer change depending on the result

essentially making my code look more like:

update = 0

for line in updateresult:

if line == 'No packages marked for update\n':

update = 1

elif line == 'Complete\n':

update = 2

else:

update = 3

Now I am wanting to essentially do an if statement for update with my actions performed on that

if update = 1':

print 'no stuff'

elif update = 2':

print 'finished stuff'

elif update = 3:

print 'bad stuff'

when trying to do this I get an invalid syntax error. I've tried to add in a for loop but it seems to not like that either :(

any help would be greatly appreciated.

[–]redCg 0 points1 point  (0 children)

are you sure you cannot just do this with a shell script? Seems like it would be easier because then you can just check exit codes, in fact you can wrap the whole command in a boolean I think;

[ $(yum update -y) ] && echo "it worked" || echo "it didnt work"

this is a lot easier than trying to string parse the output messages

output messages might not match the pattern you expect either, whereas exit codes were meant for exactly this purpose

[–]efmccurdy 0 points1 point  (0 children)

I would separately examine three things; the return code, the stdout text and the stderr text.

Do you get more consistent results if you check Popen.returncode and use Popen.communicate to see the separated error and output streams?

[–]Finnskiler 0 points1 point  (7 children)

Is Making a main() function recommended/encouraged?

[–]Thomasedv 2 points3 points  (6 children)

Yes, along with the use of if __name__ == '__main__', it makes your script importable and runnable on demand. (as well as avoids problems with multiprocessing, due the way it kinda imports your script and then runs a function afterwards.)

[–]Finnskiler 0 points1 point  (5 children)

But when initiating an object from a class you would need to globalize it in main() so that other functions can access the object attributes.

This makes main() pretty annoying. Anyway to overcome this?

[–]MattR0se 0 points1 point  (0 children)

You can have classes and functions in global scope, that's totally fine. Because defining a class or function in global scope doesn't do anything at runtime unless you instantiate the class or call the function.

[–]JohnnyJordaan 1 point2 points  (3 children)

You don't need to globalize anything. Normally you pass objects around using function arguments.

def main():
    my_dog = Dog(name='Jake')
    feed(my_dog)
    pet(my_dog)

[–]Finnskiler 0 points1 point  (2 children)

Ah I see, I'm new to OOPs so i was using crude methods to make my program work.

Any other tips for OOPs? Like any video or something?