Jump to content

I'm confused about the commenting part in python

pcnoobie007
6 minutes ago, pcnoobie007 said:

I still don't get how I should comment in python. Is there like a good tutorial on how and what I should comment? Also I wanted to know if I commented correctly for the programs I written.

MassAndWeight2.py

DayofTheWeek2.py

Commenting is for you, the programmer, to make it easier to know what's what. You don't need to comment and you don't need to write a full paragraph of comments. Put what you need in them and you're good!

CPU: Intel Core i7 8700  

GPU: Gigabyte GeForce GTX 1070

MOBO: ASUS Z370-F STRIX  

RAM: 16GB Corsair Vengeance DDR4 2133MHz

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, EvilCat70 said:

Commenting is for you, the programmer, to make it easier to know what's what. You don't need to comment and you don't need to write a full paragraph of comments. Put what you need in them and you're good!

Well my professor want's us to add comments. I'm confused what exactly to put.

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, pcnoobie007 said:

Well my professor want's us to add comments. I'm confused what exactly to put.

Well, because I'm on mobile right now I can't view your code. But, go to an important method or variable and comment what this is/does. 

CPU: Intel Core i7 8700  

GPU: Gigabyte GeForce GTX 1070

MOBO: ASUS Z370-F STRIX  

RAM: 16GB Corsair Vengeance DDR4 2133MHz

Link to comment
Share on other sites

Link to post
Share on other sites

Here's how I would comment those 2 files.

Spoiler

 


# Author: James Malone

userNumber = int(input("Please enter a number from 1 through 7: " ))

if userNumber == 1:
        print("Monday")
elif userNumber == 2:
        print("Tuesday")
elif userNumber == 3:
        print("Wednesday")
elif userNumber == 4:
        print("Thursday")
elif userNumber == 5:
        print("Friday")
elif userNumber == 6:
        print("Saturday")
elif userNumber == 7:
        print("Sunday")
else:
    print(str(userNumber) + " is not a number from 1 to 7. Please enter a "\
                "correct number")
           
        
        
        

# Auther: James Malone

userMass = float(input("Please enter object mass:"))
weight = userMass * 9.8

print()

if weight > 500:
    print("The object weighing " + format(weight, ".2f") + "newtons is too heavy")
elif weight < 100:
    print("The object weighing " + format(weight, ".2f") + \
          "newtons is too light")
else:
    print("The object weighing " + format(weight, ".2f") + \
          "newtons is too neither " + \
          "heavy nor light")
    

 

A comment that says, "ask the user to enter an object's mass in killograms (kg)" when the next line is input("enter object mass") is useless. Repeating yourself just for the sake of having comments actually makes the code harder to read.

1474412270.2748842

Link to comment
Share on other sites

Link to post
Share on other sites

6 minutes ago, EvilCat70 said:

Commenting is for you, the programmer, to make it easier to know what's what. You don't need to comment and you don't need to write a full paragraph of comments. Put what you need in them and you're good!

Commenting is for all the other people who can read or modify your program, it is NOT for you.

You DO need to comment if you want to make good programs that are readable to more than just you, which is the proper way of programming.

NEW PC build: Blank Heaven   minimalist white and black PC     Old S340 build log "White Heaven"        The "LIGHTCANON" flashlight build log        Project AntiRoll (prototype)        Custom speaker project

Spoiler

Ryzen 3950X | AMD Vega Frontier Edition | ASUS X570 Pro WS | Corsair Vengeance LPX 64GB | NZXT H500 | Seasonic Prime Fanless TX-700 | Custom loop | Coolermaster SK630 White | Logitech MX Master 2S | Samsung 980 Pro 1TB + 970 Pro 512GB | Samsung 58" 4k TV | Scarlett 2i4 | 2x AT2020

 

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, Enderman said:

Commenting is for all the other people who can read or modify your program, it is NOT for you.

You DO need to comment if you want to make good programs that are readable to more than just you, which is the proper way of programming.

Usually people write comments for themselves. 

CPU: Intel Core i7 8700  

GPU: Gigabyte GeForce GTX 1070

MOBO: ASUS Z370-F STRIX  

RAM: 16GB Corsair Vengeance DDR4 2133MHz

Link to comment
Share on other sites

Link to post
Share on other sites

3 minutes ago, EvilCat70 said:

Usually people write comments for themselves. 

Nope. That is not the purpouse of comments.

I don't think you were taught to program correctly...

Who taught you that?

NEW PC build: Blank Heaven   minimalist white and black PC     Old S340 build log "White Heaven"        The "LIGHTCANON" flashlight build log        Project AntiRoll (prototype)        Custom speaker project

Spoiler

Ryzen 3950X | AMD Vega Frontier Edition | ASUS X570 Pro WS | Corsair Vengeance LPX 64GB | NZXT H500 | Seasonic Prime Fanless TX-700 | Custom loop | Coolermaster SK630 White | Logitech MX Master 2S | Samsung 980 Pro 1TB + 970 Pro 512GB | Samsung 58" 4k TV | Scarlett 2i4 | 2x AT2020

 

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, Enderman said:

Nope. That is not the purpouse of comments.

I don't think you were taught to program correctly...

Who taught you that?

I self taught myself a lot. But I'm still learning lots and am having trouble finding  courses and lessons online for it

CPU: Intel Core i7 8700  

GPU: Gigabyte GeForce GTX 1070

MOBO: ASUS Z370-F STRIX  

RAM: 16GB Corsair Vengeance DDR4 2133MHz

Link to comment
Share on other sites

Link to post
Share on other sites

10 minutes ago, fizzlesticks said:

Here's how I would comment those 2 files.

  Reveal hidden contents

 



# Author: James Malone

userNumber = int(input("Please enter a number from 1 through 7: " ))

if userNumber == 1:
        print("Monday")
elif userNumber == 2:
        print("Tuesday")
elif userNumber == 3:
        print("Wednesday")
elif userNumber == 4:
        print("Thursday")
elif userNumber == 5:
        print("Friday")
elif userNumber == 6:
        print("Saturday")
elif userNumber == 7:
        print("Sunday")
else:
    print(str(userNumber) + " is not a number from 1 to 7. Please enter a "\
                "correct number")
           
        
        
        


# Auther: James Malone

userMass = float(input("Please enter object mass:"))
weight = userMass * 9.8

print()

if weight > 500:
    print("The object weighing " + format(weight, ".2f") + "newtons is too heavy")
elif weight < 100:
    print("The object weighing " + format(weight, ".2f") + \
          "newtons is too light")
else:
    print("The object weighing " + format(weight, ".2f") + \
          "newtons is too neither " + \
          "heavy nor light")
    

 

A comment that says, "ask the user to enter an object's mass in killograms (kg)" when the next line is input("enter object mass") is useless. Repeating yourself just for the sake of having comments actually makes the code harder to read.

Okay I will take that comment out

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, EvilCat70 said:

I self taught myself a lot. But I'm still learning lots and am having trouble finding  courses and lessons online for it

Oh, that's probably why then.

 

Well, comments aren't meant for you at all, they are a way of making code readable for other people because it is extremely important when doing it as your job or writing programs that people will use for more than a short time.

Other people need to be able to understand what you write so they can modify and improve it.

Also, programs need to constantly change to fix or improve or add stuff, and when you have a billion lines of code that only you can understand, if you ever leave the company or stop updating your program it will quickly become obsolete because nobody can keep it going.

Sometimes after long periods of time even you won't be able to understand your program because programming style changes as you get more experienced, so sometimes yes comments can help you out too, but 99% of the time they are intended for others.

NEW PC build: Blank Heaven   minimalist white and black PC     Old S340 build log "White Heaven"        The "LIGHTCANON" flashlight build log        Project AntiRoll (prototype)        Custom speaker project

Spoiler

Ryzen 3950X | AMD Vega Frontier Edition | ASUS X570 Pro WS | Corsair Vengeance LPX 64GB | NZXT H500 | Seasonic Prime Fanless TX-700 | Custom loop | Coolermaster SK630 White | Logitech MX Master 2S | Samsung 980 Pro 1TB + 970 Pro 512GB | Samsung 58" 4k TV | Scarlett 2i4 | 2x AT2020

 

Link to comment
Share on other sites

Link to post
Share on other sites

One thing of note, there are two types of commenting in Python:

  • Single linecommenting which is the pound sign (#). This comments out the rest of the line.
  • Docstring commenting, which is text surrounded by tripe double-quotes (""").

Docstrings are supposed to be for documenting your code, like describing what a file, class, or function does. Single line commenting is more for making small comments, like if a part of a function may look strange to someone at first glance and you need explain it.

 

A good rule of thumb of commenting though is less is preferably better. Your code should be written in a way that's understandable without comments. Like if you have variables to hold say... payer, payee, and money, don't name the variables a, b, and c.

Link to comment
Share on other sites

Link to post
Share on other sites

4 hours ago, pcnoobie007 said:

I still don't get how I should comment in python. Is there like a good tutorial on how and what I should comment? Also I wanted to know if I commented correctly for the programs I written.

In the future, please use code tags and copy/paste the code into here. However, what I always do for comments is to add only the comments that help me personally remember what is going on, but I do so in a general way that other people can understand. Yes, that means in many cases things don't get commented, as comments are only added on hard to understand or complex parts.

Docstrings are used to document code. Code documenting basically just outlines what a "thing" does, as well as any parameters, fields, methods, and limitations for such. The point of Docstrings as opposed to comments is mostly so that you can use a tool to read your code and produce nice, formatted documentation in a form usable by others. Things like Intellisense also use docstrings to generate short descriptions for the autocompletion window.

Since this is for homework, and your teacher probably requires atleast one comment per "section" (like mine do, unfortunately) here's how I would comment your programs:

# Get mass and adjust to weight
userMass = float(input("Please enter object mass:"))
weight = userMass * 9.8

print()

# Determine if the object meets the criteria and tell the user
if weight > 500:
    print("The object weighing " + format(weight, ".2f") + "newtons is too heavy")
elif weight < 100:
    print("The object weighing " + format(weight, ".2f") + \
          "newtons is too light")
else:
    print("The object weighing " + format(weight, ".2f") + \
          "newtons is too neither " + \
          "heavy nor light")
# Get day of week from user
userNumber = int(input("Please enter a number from 1 through 7: " ))


# Display name associated with numerical day of week.
if userNumber == 1:
        print("Monday")
elif userNumber == 2:
        print("Tuesday")
elif userNumber == 3:
        print("Wednesday")
elif userNumber == 4:
        print("Thursday")
elif userNumber == 5:
        print("Friday")
elif userNumber == 6:
        print("Saturday")
elif userNumber == 7:
        print("Sunday")
else:
    print(str(userNumber) + " is not a number from 1 to 7. Please enter a "\
                "correct number")

 

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

3 hours ago, pcnoobie007 said:

Okay I will take that comment out

Keep in mind that school assignment requirements don't always match industry best practices. In industry, it's a common practice to try and make your code as understandable as possible without comments. So in many cases, adding comments can often be unnecessary.

 

However, in a school setting, choosing to leave them out may cause you to lose marks on an assignment if they are an explicit requirement. You might be able to argue to your professor that your code is clear and doesn't need comments, however I wouldn't risk it. That doesn't necessarily mean you need to comment every line of code, but don't remove them all either. A comment per "section", like straight_stewie said, is a good general approach. Adjust as you feel it's necessary.

 

You can always ask your professor for clarification on what they consider "useful" vs "redundant/unnecessary". What you have may be similar to what they are looking for. Maybe not. Ultimately we can't know what your professor wants.

 

There's a lot of tips on when it's good/bad to write comments in your code (ex: Google things like "when to comment code" and browse the results) but the advice won't necessarily apply to school assignments (or may just include advice that's too advanced for you right now). When in doubt, follow the professors requirements above all else, and ask them for help/clarification if necessary.

Link to comment
Share on other sites

Link to post
Share on other sites

If i may add a small suggestion, I would also have the upper and lower weight limit declared as variables.

Have it defined as a variable at the top makes it easily changeable and reusable. Also makes it readable in the places you use it without requiring you to comment what your trying to accomplish. (having it as weight > maxWeight is more understandable than weight > 500)

 

readable code >>> commented code

Link to comment
Share on other sites

Link to post
Share on other sites

12 hours ago, Enderman said:

Nope. That is not the purpouse of comments.

 

Of course it is. The best comments are comments you write for your future self.

Write in C.

Link to comment
Share on other sites

Link to post
Share on other sites

14 hours ago, pcnoobie007 said:

I still don't get how I should comment in python. Is there like a good tutorial on how and what I should comment? Also I wanted to know if I commented correctly for the programs I written.

MassAndWeight2.py

DayofTheWeek2.py

Comments are meant both for your future self (It does not take long to forget how something you wrote yourself actually worked) and other ppl having to read/work on your code.

 

That said, one should always try to let the code speak for itself, so comments can be minimized.

Class names, function names, parameter names and so on should be chosen so they are self explanatory. If you find you have to add too much comment to a function that's a big sign the code needs to be refactored, by breaking it up further into more functions (each with their own self-explanatory name), for example.

 

Don't try to be too clever as well. Some programmers seem to think that cramming lots of clever tricks into a few lines of code is somehow faster and some comments will explain what the code does to the unfortunate soul that stumbles across it. It's been proven that simple, clean code compiles into faster machine code. The compiler/optimizer is a stupid machine, it dislikes clever tricks as much as you and me.

 

If you must add comments to a function to clarify what it does try to be as generic as possible. Comments that are too verbose and detailed run the risk of becoming outdated/wrong when the code is modified but you "forgot" to update the comment accordingly. I put forgot in quotes because most programmers "forget" on purpose because constantly updating comments is a hassle.

 

Valid comments:
-A small explanation what a module does at the top of the file in each module. For example, if I'm writing some communications module that has some complex input/output buffering under the hood, some comments explaining how the system works as a whole are welcome.

 

-A new, complex, type such as a class (object type, I don't know the phyton name) will probably need some comment explaining broadly what it does/how it functions. Notice i said "Complex", don't go doing this for a simple struct .

 

-A function that already has been broken down as much as it can but still is not clear as how it works from looking at the code can have some comment. This is rare and should not be an excuse to simply be lazy and not break up the code into smaller functions.

 

-Code that interacts with some outside system that not everyone is familiar with. For example, when writing code to receive infrared commands on a micro-controller, the IR receiver inverts the signal in hardware. Not every programmer might know this so a comment clarifying why you're inverting it back again in the code is acceptable.

 

Also note that there is a difference between "release comments" and "work in progress comments". When coding, one often adds lots of comments to help understand the process better and remember things while the code in question is still being worked on and slowly morphing into the final product. Once done however, the code should be self explanatory and (most) of those comments are removed.

 

Since this is a school project, it could very well be that your teacher asks you to very verbosely comment the code just to see if you understand what's happening and if you're not just copying someone else's code. Copying code with comments and all will quickly give you away. Copying the code and then making up your own comments requires you to understand what the code does, if you don't the comments will give you away. 

 

I think that is your teacher's motivation. But even if it is, he would do well to explain this, and also explain that such verbose commenting is frowned upon in the real world.

Link to comment
Share on other sites

Link to post
Share on other sites

Any non-trivial class, method, or function should have a docstring with:

  1. a brief (1-2 sentences) explaining what it does.
  2. inputs, with descriptions and any expected preconditions.
  3. output.
  4. Any likely exceptions

Obviously 2, 3, and 4 aren't applicable to classes, and classes might need slightly more summary, but if a method or function takes much more than that (1-2 sentences, pre/post conditions withstanding) to explain, it is probably doing too much.

Line comments should be added when a code section isn't obvious.  Being the author, it might seem obvious at the time of writing what it does, but if you had to pause to think a moment while writing the section...it probably needs a comment.  For example, if something needs to be special cased, you should probably mention how to detect it and why it needs to be treated differently.

 

22 minutes ago, Unimportant said:

Since this is a school project, it could very well be that your teacher asks you to very verbosely comment the code just to see if you understand what's happening and if you're not just copying someone else's code. Copying code with comments and all will quickly give you away. Copying the code and then making up your own comments requires you to understand what the code does, if you don't the comments will give you away.

And for now, there is also this.

Link to comment
Share on other sites

Link to post
Share on other sites

15 hours ago, Enderman said:

Commenting is for all the other people who can read or modify your program, it is NOT for you.

You DO need to comment if you want to make good programs that are readable to more than just you, which is the proper way of programming.

unless it's a obscure function or algorithm  it's normally quite obvious what a function, for example, does. 

public static function logIn($username, $password){
    $login = db::query("SELECT * FROM users WHERE name=:u LIMIT 1", array(":u" => $username));
    if($login->rowCount() > 0){
        $row = $login->fetch(PDO::FETCH_ASSOC);
        if(password_verify($password, $row['password']))
            $_SESSION['login'] = $row;
            return 'true';
        }
    }else{
        return 'false';
    }
}

 

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

3 hours ago, Dat Guy said:

 

Of course it is. The best comments are comments you write for your future self.

Looks to me like you weren't taught to program correctly...

Yes it can help your future self but the main purpouse is for others.

NEW PC build: Blank Heaven   minimalist white and black PC     Old S340 build log "White Heaven"        The "LIGHTCANON" flashlight build log        Project AntiRoll (prototype)        Custom speaker project

Spoiler

Ryzen 3950X | AMD Vega Frontier Edition | ASUS X570 Pro WS | Corsair Vengeance LPX 64GB | NZXT H500 | Seasonic Prime Fanless TX-700 | Custom loop | Coolermaster SK630 White | Logitech MX Master 2S | Samsung 980 Pro 1TB + 970 Pro 512GB | Samsung 58" 4k TV | Scarlett 2i4 | 2x AT2020

 

Link to comment
Share on other sites

Link to post
Share on other sites

On 20.2.2017 at 0:12 AM, Enderman said:

Nope. That is not the purpouse of comments.

I don't think you were taught to program correctly...

Who taught you that?

Why not. It helps a lot, f.e. when looking at older code of yours to have comments. Saying you don't comment for yourself is stupid because it can help a lot. If you're writing a larger program you will likely not remember what some methods do or what a variable is used for etc. 

Edit:

I guess another good example is html. On a website with several <div> tags in a row it helps a lot to comment where which div tag ends, instead of just </div>

My Rig: AMD Ryzen 5800x3D | Scythe Fuma 2 | RX6600XT Red Devil | B550M Steel Legend | Fury Renegade 32GB 3600MTs | 980 Pro Gen4 - RAID0 - Kingston A400 480GB x2 RAID1 - Seagate Barracuda 1TB x2 | Fractal Design Integra M 650W | InWin 103 | Mic. - SM57 | Headphones - Sony MDR-1A | Keyboard - Roccat Vulcan 100 AIMO | Mouse - Steelseries Rival 310 | Monitor - Dell S3422DWG

Link to comment
Share on other sites

Link to post
Share on other sites

9 hours ago, -iSynthesis said:

Why not. It helps a lot, f.e. when looking at older code of yours to have comments. Saying you don't comment for yourself is stupid because it can help a lot. If you're writing a larger program you will likely not remember what some methods do or what a variable is used for etc.

In the first place try to avoid comments. When writing code you have the power to use meaningful variable, function, method, class names so that the code is readable just by looking on it. If have comments then it's something extra to maintain. If you change the code you also have to change the comments which is additional burden (and what may happen is that you receive new code with old comments because someone didn't notice or was lazy).

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, riklaunim said:

In the first place try to avoid comments. When writing code you have the power to use meaningful variable, function, method, class names so that the code is readable just by looking on it. If have comments then it's something extra to maintain. If you change the code you also have to change the comments which is additional burden (and what may happen is that you receive new code with old comments because someone didn't notice or was lazy).

if I do comments it is for a place holder for something I need to add or fix later.

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×