Trying to get into good code habbits

Trying to get into good code habbits

Author
Discussion

SystemParanoia

Original Poster:

14,343 posts

198 months

Tuesday 17th March 2015
quotequote all
Hey guys,

Im currently filling my spare time messing around with python and learning how to use it blah blah blah.

Ive created a couple quick a dirty programs to get me used to the new syntax im learning and when best to use it.

ill paste my code below.

Its a simple program to calculate the area of a triangle. with pretty basic error checking.

if any of you have suggestions on making it more elegant or "pythonic" as they say; i'd love to hear it smile

I appreciate that im probably on completely the wrong website for receiving feedback on this sort of thing, but signing up for new webforums all the time is alot of effort!



#! /usr/bin/env python

#
#
#========= ( EXPLANATION OF FIRST LINE )=========#
#
#

'''
If you have several versions of Python installed, /usr/bin/env will
ensure the interpreter used is the first one on your environment's
$PATH. The alternative would be to hardcode something line
#!/usr/bin/python or the like -- that's OK but less flexible.

In Unix / Linux, an executable file that's meant to be interpreted can
indicate what interpreter to use by having a #! at the start of the
first line, followed by the interpreter (and any flags it may need).

With other platforms like Windows, of course, this rule does not
apply (but that "shebang line" does no harm, and will help if you ever
copy that script to a platform with a Unix base, such as Linux or Mac.
'''

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
#
#========= ( SYSTEMPARANOIAS INTRODUCTION NOTES )=========#
#
#

'''
Program created by SYSTEMPARANOIA 3/2015
Final revision and most robust version of python calculator that not
only works out the area of a triangle using the base x height divided
by 2 method.
It also has an Error Checking function on the user input to make sure
the user is entering a number and not a letter and forces the program
to run again if an error is found.
I have also added a continuation function to allow the programme to exit
cleanly when the user is ready.
This version is set within a (while) loop using multiple
definitions (def) that can be called repeatedly in this and other
programs.
This version gives the workings out for the user and exits cleanly.
'''

#
#
#========= ( DEFINITIONS OF FUNCTIONS )=========#
#
#

'''
This function performs the main calculations for the program and
prints the results on screen including the workings out for the sum.

To explain the first print statement, see sample code below:

name = 'maths'
number = 42
print '%s %d' % (name, number)

will print maths 42.

Note that name is a string (%s) and
number is an integer (%d for decimal)

'''

def triangle(base, height): # Name of the function with arguments
base = float(base) # Convert Variable to decimal
height = float(height) # Convert Variable to decimal
area = base * height / 2 # Perform calculation
print "The working out is, %d x %d / 2" % (base, height)
print "Base x height =", base * height
print "Once divided by 2 the area of your triangle is ",area

'''
This Function performs a check of the user's input to make sure
that it is a number and will not cause the program to crash due to
the user entering a string.
'''

def is_number(n): #Name of the function with argument
try: #Attempt the following action
float(n) #Convert to float with argument
return True #If successful return True
except ValueError: #Check if error message is received
return False #If Error, return False

'''
This function performs a check if the user would like to continue
and run another calculation, or to end the program. it returns a true
or a false value.
'''

def re_run(c): #Name of Function with argument
c.lower() #Force string to Lower case
if c == "y" or c == "yes": #If one of these values are True then..
return True #End function with True value
else: #If both are False then..
print "\nGood Bye\n" #Print String
return False #End function with False value

#
#
#========= ( DEFINITIONS OF VARIABLES )=========#
#
#

'''
This variable is what the while loop checks to see if it should
loop again or not. Once set, a variable can be changed to any other
value at any time
'''

i = True #Set variable to True

#
#
#========= ( DEFINITIONS OF PROGRAM LOOPS )=========#
#
#

# Start of loop, check if 'i' is true, otherwise do not loop
while i == True:
print "\nThis programme calculates the area of a triangle\n"
base = raw_input("Enter Base Value: ")
height = raw_input("Enter Height value: ")
# Call function and check if both results return a True value
if is_number(base) and is_number(height):

# Print contents of triangle function
print triangle(base, height)

#If error or exception
else:
print "\nPlease enter numbers and not letters"

# Call continue function to change variable to true or false
# This will change the value of the variable 'i' above to either True
# or False.

i = re_run(raw_input("\nDo you wish to continue? Y/N "))



'''
This version that will work with decimals, and wont break with letters
it will also loop over and over to allow for repeated use until
the user decides to quit.

This version has Error Checking and is very robust.
These definitions can be taken and used in other programmes the user
may create

Notice that the main programme is only 10 lines of code. if you want to
change how it works, you do not have to change much. The previous
versions of the program would need a complete re-write.
'''



grumbledoak

31,532 posts

233 months

Tuesday 17th March 2015
quotequote all
Hateful language. All the problems with C and make identified and made worse! yuck

More constructively, applies to any script:
1. you don't need to explain #! and exec() in every script you write
2. comments like "call a function" before you call a function don't add any information, they just lower the signal to noise ratio.
3. Unix scripts are generally better written to take their arguments from the command line and output the result so they can be chained using pipes. It is a bit of a myth that this is the best approach, but it is the Unix way.


Edited by grumbledoak on Tuesday 17th March 03:35

scorp

8,783 posts

229 months

Tuesday 17th March 2015
quotequote all
Way too many comments.


i = True #Set variable to True


hehe

GnuBee

1,272 posts

215 months

Tuesday 17th March 2015
quotequote all
scorp said:
Way too many comments.


i = True #Set variable to True


hehe
Definitely! You've spent more time typing comments that typing code and the code is harder to read because of that.

I'm probably at the opposite end of the spectrum but I assume the person reading the code knows how to code so they don't need comments that restate the code in "English".

I comment things I suspect may catch people out, gotchas or where the code does things in a specific way and where that decision process may not be clear and that's it.

Also, meaningful variable names can save you a lot of comments; which is more useful i++ or nameArrayIndex++


SystemParanoia

Original Poster:

14,343 posts

198 months

Tuesday 17th March 2015
quotequote all
Brilliant.. Thanks for the feedback.

I guess I have gone way way overboard on the comments just a little smile

I've chosen python as I couldnt make a choice of the many languages out there, and instead of procrastinate over choosing. I just picked one and got on with trying to learn one.

Not sure what I'll try to learn next. Maybe java or c. Regardless that's a looking way off at the mo smile

I shall take onboard the comment about using more meaningful variable names, and get reading about grep and piping commands in shell. I don't think I have to worry about windows cross compatibility as I haven't used the os since XP lol

Edited by SystemParanoia on Tuesday 17th March 13:30

davek_964

8,804 posts

175 months

Tuesday 17th March 2015
quotequote all
GnuBee said:
Also, meaningful variable names can save you a lot of comments; which is more useful i++ or nameArrayIndex++
Adding to that comment further :

Whether good or bad, using "i" (and sometimes j if you have a nested loop) as a variable for loop counting / array indexing is pretty common in the coding world. Using a real name does make it easier to read though - and it does mean that in the example given by the OP, seeing "i" as a boolean just seems a bit wrong, even though technically i can be whatever the programmer wants.


Tonsko

6,299 posts

215 months

Tuesday 17th March 2015
quotequote all
I think python is an ace language to learn. It's pretty much cross platform (assuming you stick to one of the main branches, personally I use 2.7, but have no wish to start a religious war). Also, with python if you want to do something special, chances are that there's a module already written for you to use. It would be a rare thing to have to write your own. Makes life really easy. Also, the development environment is a text editor.

I use meaningful variable names for 'important' variables, for loop counters, I just use 'i'.

I also always declare the shebang in the first line, then everyone knows where you are and what you're doing. Especially the interpreter!

With regards to importing modules, just import the whole bang-shoot. Don't bother arsing around with specific functions of a module, as chances are you're on a box that can spare the itty bit of memory and CPU time it takes to get it all. E.g not 'FROM NETIFACES IMPORT IFADDRESSES' but 'IMPORT NETIFACES'.

Once you've defined all your functions, define a function called main to keep your, er, main stuff in, then call main. This is the 'pythonic' way of doing things.

So for example:

def main():
i = True

while i == True:
print "\nThis programme calculates the area of a triangle\n"
base = raw_input("Enter Base Value: ")
height = raw_input("Enter Height value: ")
if is_number(base) and is_number(height):
print triangle(base, height)
else:
print "\nPlease enter numbers and not letters"

i = re_run(raw_input("\nDo you wish to continue? Y/N "))

if __name__=="__main__":
main()


To tidy up the 'while' statement, you can just use the 'while True:' command, then insert a 'break' when you want it to stop, without having to worry about having a boolean variable floating around.

Edited by Tonsko on Tuesday 17th March 14:26

GnuBee

1,272 posts

215 months

Tuesday 17th March 2015
quotequote all
I'd not get too hung up on the language; it's the concepts at this point that matter. Then we can have the debate about real men using assembler and how Microsoft ruined it all by introducing C# and automatic garbage collectors.

Tonsko

6,299 posts

215 months

Tuesday 17th March 2015
quotequote all
Religious war incoming! laugh

Depends what you want to do, as ever. I only really need python and shell scripting, so haven't really taken it further. The only time I go near a compiler is when someone gives me source files.

onomatopoeia

3,469 posts

217 months

Tuesday 17th March 2015
quotequote all
GnuBee said:
I'd not get too hung up on the language; it's the concepts at this point that matter. Then we can have the debate about real men using assembler and how Microsoft ruined it all by introducing C# and automatic garbage collectors.
I still write assembly language when required getmecoat . x64 this morning. It has its uses. What I don't do is comment like this :


mov rax,1 ;set rax to 1


GHW

1,294 posts

221 months

Tuesday 17th March 2015
quotequote all
I'm not going to add much here, because it's been a while since I did any meaningful Python.

However, PEP 8 and the Google Python style guide should be all the style advice you need smile

anonymous-user

54 months

Tuesday 17th March 2015
quotequote all
I see that you didn't make use of the goto command.

All the best programs use goto commands!

silly

CountZero23

1,288 posts

178 months

Tuesday 17th March 2015
quotequote all
I'm of the 'good code doesn't require comments' mentality.

Useful variable names and moving logic into well named methods can pretty much eliminate them from your code.

Can't give any language specific advice (C# dev and totally biassed) though:

Move functions into a service class so you separate the implementation details from the program logic. This way the intent of the program is clear and you are separating out your concerns.

By breaking programs into decoupled components you allow for reuse and it makes them much easier to test.


As a quick and dirty pseudo code example see below. No comments required and if your program grows then it won't turn into spaghetti code.



var validationService = new ValidationService()
var calculationService = new CalculationService()
var messageService = new MessageService()

Run(arguments)
bool isValid = validationService.ValidateArguments(arguments)

if(!isValid)
messageService.PrintError();
else
var areaResult = calculationService.CalculateAreaOfTriangle(arguments)
messageService.PrintAreaResult(areaResult)

One of the most important principles in coding is SOLID.

http://en.wikipedia.org/wiki/SOLID_%28object-orien...

Look into unit testing and test driven development. Right bd at first but really helps you (forces you!) to write good code and now is a given in the industry.

As a first bash into the world of python - bloody good work.

Just out of interest are you coding just for fun or did you have a view to change careers?


Edited by CountZero23 on Tuesday 17th March 19:22

SystemParanoia

Original Poster:

14,343 posts

198 months

Tuesday 17th March 2015
quotequote all
CountZero23 said:
Just out of interest are you coding just for fun or did you have a view to change careers?
Short term, its for fun and to allow me to know enough teach the kids how to code ( they're currently 9 )

Long term, I am very focused on this and once I become a code ninja, I will definitely be trying to change career. once i've learnt vanilla python inside and out maybe even go for an OU computer science degree if it will help.

Tonsko said:
if name__=="__main":
I will look into this so that i fully understand what's happening when i use it smile thank you


Thanks for the links above all, ill try and digest as much of that as i can.
im currently using various free online resources to learn, and a couple of books.

codecademy
codecombat <--- coding game
checkio <--- really hard coding game / challenge
and learnpythonthehardway

I try to do each new thing in both python 2.xx and 3.xx so that I can keep aware of the differences between the 2.

CountZero23

1,288 posts

178 months

Tuesday 17th March 2015
quotequote all
Awesome you want to get your kids into it smile

Worth checking out what Python jobs are available as it's a rare you have a job which only requires one language or competency. After a quick look on jobsite it appears it is sys-admin / 3d and web. All of these have their own stacks of tech / domain knowledge to learn. Try to approach it from one of these angles to get a head start on the jobs side of things.

Think you are going in the right direction by sticking to one language to begin with, to be fair there are more similarities than differences between them all so worth putting more time into common concepts like design patterns where you'll find elegant solutions to all your coding challenges. Really essential to nail most of these (apart from the visitor pattern - never managed to fit that one in!).

Great book here and the only one which made it easy
http://www.amazon.co.uk/Head-First-Design-Patterns...

Examples in Java but don't let that put you off.

Another great resource - paid for but does offer free trial and well worth it.
http://www.pluralsight.com

Good luck!

mikees

2,747 posts

172 months

Tuesday 17th March 2015
quotequote all

grumbledoak

31,532 posts

233 months

Tuesday 17th March 2015
quotequote all
mikees said:
thumbup It's the only book on coding I have kept or re-read.

mikees

2,747 posts

172 months

Tuesday 17th March 2015
quotequote all
grumbledoak said:
mikees said:
thumbup It's the only book on coding I have kept or re-read.
I also have a signed copy of this from Jim when we were in Seattle porting to Chicago (windows 95)

http://www.amazon.co.uk/Dynamics-Software-Developm...


A brilliant book on creating a great product

Mike

CountZero23

1,288 posts

178 months

Tuesday 17th March 2015
quotequote all
OP is going to have his work cut out getting through that lot hehe

Still if he does he'll be a better coder than the last two guys we've had in for interview for a senior 40k+ position. Struggled with most of the SOLID principles.

Bloody impossible finding good devs.

Tonsko

6,299 posts

215 months

Tuesday 17th March 2015
quotequote all
OP, if you fancy some projects that are a bit more fun, check out these python books.

Violent Python http://www.amazon.co.uk/Violent-Python-Cookbook-Pe...
Blackhat Python http://www.amazon.co.uk/Black-Hat-Python-Programmi...