Search

Series List Filter

How To Write Beautiful Python Code With PEP 8

It gets difficult to understand a messed up handwriting, similarly an unreadable and unstructured code is not accepted by all. However, you can benefit as a programmer only when you can express better with your code. This is where PEP comes to the rescue. Python Enhancement Proposal or PEP is a design document which provides information to the Python community and also describes new features and document aspects, such as style and design for Python.Python is a multi-paradigm programming language which is easy to learn and has gained popularity in the fields of Data Science and Web Development over a few years and PEP 8 is called the style code of Python. It was written by Guido van Rossum, Barry Warsaw, and Nick Coghlan in the year 2001. It focuses on enhancing Python’s code readability and consistency. Join the certification course on Python Programming and gain skills and knowledge about various features of Python along with tips and tricks.A Foolish Consistency is the Hobgoblin of Little Minds‘A great person does not have to think consistently from one day to the next’ — this is what the statement means.Consistency is what matters. It is considered as the style guide. You should maintain consistency within a project and mostly within a function or module.However, there will be situations where you need to make use of your own judgement, where consistency isn’t considered an option. You must know when you need to be inconsistent like for example when applying the guideline would make the code less readable or when the code needs to comply with the earlier versions of Python which the style guide doesn’t recommend. In simple terms, you cannot break the backward compatibility to follow with PEP.The Zen of PythonIt is a collection of 19 ‘guiding principles’ which was originally written by Tim Peters in the year 1999. It guides the design of the Python Programming Language.Python was developed with some goals in mind. You can see those when you type the following code and run it:>>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!The Need for PEP 8Readability is the key to good code. Writing good code is like an art form which acts as a subjective topic for different developers.Readability is important in the sense that once you write a code, you need to remember what the code does and why you have written it. You might never write that code again, but you’ll have to read that piece of code again and again while working in a project. PEP 8 adds a logical meaning to your code by making sure your variables are named well, sufficient whitespaces are there or not and also by commenting well. If you’re a beginner to the language, PEP 8 would make your coding experience more pleasant.Following PEP 8 would also make your task easier if you’re working as a professional developer. People who are unknown to you and have never seen how you style your code will be able to easily read and understand your code only if you follow and recognize a particular guideline where readability is your de facto.And as Guido van Rossum said— “Code is read much more than it is often written”.The Code LayoutYour code layout has a huge impact on the readability of your code.IndentationThe indentation level of line is computed by the leading spaces and tabs at the beginning of a line of logic. It influences the grouping of statements. The rules of PEP 8 says to use 4 spaces per indentation level and also spaces should be preferred over tabs.An example of code to show indentation:x = 5 if x < 10:   print('x is less than 10') Tabs or Spaces?Here the print statement is indented which informs Python to execute the statement only if the if statement is true. Indentation also helps Python to know what code it will execute during function calls and also when using classes.PEP 8 recommends using 4 spaces to show indentation and tabs should only be used to maintain consistency in the code.Python 3 forbids the mixing of spaces and tabs for indentation. You can either use tabs or spaces and you should maintain consistency while using Python 3. The errors are automatically displayed:python hello.py  File "hello.py", line 3       print(i, j)                 ^TabError: inconsistent use of tabs and spaces in indentationHowever, if you’re working in Python 2, you can check the consistency by using a -t flag in your code which will display the warnings of inconsistencies with the use of spaces and tabs.You can also use the -tt flag which will show the errors instead of warnings and also the location of inconsistencies in your code. Maximum Line Length and Line BreakingThe Python Library is conservative and 79 characters are the maximum required line limit as suggested by PEP 8. This helps to avoid line wrapping.Since maintaining the limit to 79 characters isn’t always possible, so PEP 8 allows wrapping lines using Python’s implied line continuation with parentheses, brackets, and braces:def function(argument_1, argument_2,             argument_3, argument_4):     return argument_1Or by using backslashes to break lines:with open('/path/to/some/file/you/want/to/read') as example_1, \     open('/path/to/some/file/being/written', 'w') as example_2:     file_2.write(file_1.read())When it comes to binary operators, PEP 8 encourages to break lines before the binary operators. This accounts for more readable code.Let us understand this by comparing two examples:# Example 1 # Do total = ( variable_1 + variable_2 - variable_3 ) # Example 2 # Don't total = ( variable_1 + variable_2 - variable_3 )In the first example, it is easily understood which variable is added or subtracted, since the operator is just next to the variable to which it is operated. However, in the second example, it is a little difficult to understand which variable is added or subtracted.Indentation with Line BreaksIndentation allows a user to differentiate between multiple lines of code and a single line of code that spans multiple lines. It enhances readability too.The first style of indentation is to adjust the indented block with the delimiter:def function(argument_one, argument_two,               argument_three, argument_four):         return argument_oneYou can also improve readability by adding comments:x = 10 if (x > 5 and     x < 20):     # If Both conditions are satisfied     print(x)Or by adding extra indentation:x = 10 if (x > 5 and       x < 20):     print(x)Another type of indentation is the hanging indentation by which you can symbolize a continuation of a line of code visually:foo = long_function_name(       variable_one, variable_two,       variable_three, variable_four)You can choose any of the methods of indentation, following line breaks, in situations where the 79 character line limit forces you to add line breaks in your code, which will ultimately improve the readability.Closing Braces in Line ContinuationsClosing the braces after line breaks can be easily forgotten, so it is important to put it somewhere where it makes good sense or it can be confusing for a reader.One way provided by PEP 8 is to put the closing braces with the first white-space character of the last line:my_list_of_numbers = [     1, 2, 3,     4, 5, 6,     7, 8, 9     ]Or lining up under the first character of line that initiates the multi-line construct:my_list_of_numbers = [     1, 2, 3,     4, 5, 6,     7, 8, 9 ]Remember, you can use any of the two options keeping in mind the consistency of the code.Blank LinesBlank lines are also called vertical whitespaces. It is a logical line consisting of spaces, tabs, formfeeds or comments that are basically ignored.Using blank lines in top-level-functions and classes:class my_first_class:     pass class my_second_class:     pass def top_level_function():     return NoneAdding two blank lines between the top-level-functions and classes will have a clear separation and will add more sensibility to the code.Using blank lines in defining methods inside classes:class my_class:     def method_1(self):         return None     def method_2(self):         return NoneHere, a single vertical space is enough for a readable code.You can also use blank spaces inside multi-step functions. It helps the reader to gather the logic of your function and understand it efficiently. A single blank line will work in such case.An example to illustrate such:def calculate_average(number_list):     sum_list = 0     for number in number_list:         sum_list = sum_list + number         average = 0     average = sum_list / len(number_list)    return averageAbove is a function to calculate the average. There is a blank line between each step and also before the return statement.The use of blank lines can greatly improve the readability of your code and it also allows the reader to understand the separation of the sections of code and the relation between them.Naming ConventionsChoosing names which are sensible and can be easily understandable, while coding in Python, is very crucial. This will save time and energy of a reader. Inappropriate names might lead to difficulties when debugging.Naming StylesNaming variables, functions, classes or methods must be done very carefully. Here’s a list of the type, naming conventions and examples on how to use them:TypeNaming ConventionsExamplesVariableUsing short names with CapWords.T, AnyString, My_First_VariableFunctionUsing a lowercase word or words with underscores to improve readability.function, my_first_functionClassUsing CapWords and do not use underscores between words.Student, MyFirstClassMethodUsing lowercase words separated by underscores.Student_method, methodConstantsUsing all capital letters with underscores separating wordsTOTAL, MY_CONSTANT, MAX_FLOWExceptionsUsing CapWords without underscores.IndexError, NameErrorModuleUsing short lower-case letters using underscores.module.py, my_first_module.pyPackageUsing short lowercase words and underscores are discouraged.package, my_first_packageChoosing namesTo have readability in your code, choose names which are descriptive and give a clearer sense of what the object represents. A more real-life approach to naming is necessary for a reader to understand the code.Consider a situation where you want to store the name of a person as a string:>>> name = 'John William' >>> first_name, last_name = name.split() >>> print(first_name, last_name, sep='/ ') John/ WilliamHere, you can see, we have chosen variable names like first_name and last_name which are clearer to understand and can be easily remembered. We could have used short names like x, y or z but it is not recommended by PEP 8 since it is difficult to keep track of such short names.Consider another situation where you want to double a single argument. We can choose an abbreviation like db for the function name:# Don't def db(x):     return x * 2However, abbreviations might be difficult in situations where you want to return back to the same code after a couple of days and still be able to read and understand. In such cases, it’s better to use a concise name like double_a_variable:# Do def double_a_value(x):     return x * 2Ultimately, what matters is the readability of your code.CommentsA comment is a piece of code written in simple English which improves the readability of code without changing the outcome of a program. You can understand the aim of the code much faster just by reading the comments instead of the actual code. It is important in analyzing codes, debugging or making a change in logic. Block CommentsBlock comments are used while importing data from files or changing a database entry where multiples lines of code are written to focus on a single action. They help in interpreting the aim and functionality of a given block of code.They start with a hash(#) and a single space and always indent to the same level as the code:for i in range(0, 10):     # Loop iterates 10 times and then prints i     # Newline character     print(i, '\n')You can also use multiple paragraphs in a block comment while working on a more technical program. Block comments are the most suitable type of comments and you can use it anywhere you like.Inline CommentsInline comments are the comments which are placed on the same line as the statement. They are helpful in explaining why a certain line of code is essential.Example of inline comments:x = 10  # An inline comment y = 'JK Rowling' # Author NameInline comments are more specific in nature and can easily be used which might lead to clutter. So, PEP 8 basically recommends using block comments for general-purpose coding.Document StringsDocument strings or docstrings start at the first line of any function, class, file, module or method. These type of comments are enclosed between single quotations ( ''') or double quotations ( """ ).An example of docstring:def quadratic_formula(x, y, z, t):     """Using the quadratic formula"""     t_1 = (- b+(b**2-4*a*c)**(1/2)) / (2*a)     t_2 = (- b-(b**2-4*a*c)**(1/2)) / (2*a)     return t_1, t_2Whitespaces in Expressions and StatementsIn computing, whitespace is any character or sequence of characters which are used for spacing and have an ‘empty’ representation. It is helpful in improving the readability of expressions and statements if used properly.Whitespace around Binary OperatorsWhen you’re using assignment operators ( =, +=, -=,and so forth ) or comparisons ( ==, !=, >, <. >=, <= ) or booleans ( and, not, or ), it is suggested to use a single whitespace on the either side.Example of adding whitespace when there is more than one operator in a statement:# Don't b = a ** 2 + 10 c = (a + b) * (a - b) # Do b = a**2 + 10 c = (a+b) * (a-b)In such mathematical computations, you should add whitespace around the operators with the least priority since adding spaces around each operator might be confusing for a reader.Example of adding whitespaces in an if statement with many conditions:# Don't if a < 10 and a % 5 == 0:     print('a is smaller than 10 and is divisible by 5!') # Do if a<10 and a%5==0:     print('a is smaller than 10 and is divisible by 5!')Here, the and operator has the least priority, so whitespaces have been added around it.Colons act as binary operators in slices:ham[3:4]ham[x+1 : x+2]ham[3:4:5]ham[x+1 : x+2 : x+3]ham[x+1 : x+2 :]Since colons act as a binary operator, whitespaces are added on either side of the operator with the lowest priority. Colons must have the same amount of spacing in case of an extended slice. An exception is when the slice parameter is omitted, space is also omitted.Avoiding WhitespacesTrailing whitespaces are whitespaces placed at the end of a line. These are the most important to avoid. You should avoid whitespaces in the following cases—Inside a parentheses, brackets, or braces:# Do list = [1, 2, 3] # Don't list = [ 1, 2, 3, ]Before a comma, a semicolon, or a colon:x = 2 y = 3 # Do print(x, y) # Don't print(x , y)Before open parenthesis that initiates the argument list of a function call:def multiply_by_2(a):       return a * 2 # Do multiply_by_2(3) # Don't multiply_by_2 (3)Before an open bracket that begins an index or a slice:# Do ham[5] # Don't ham [5]Between a trailing comma and a closing parenthesis:# Do spam = (1,) # Don't spam = (1, )To adjust assignment operators:# Do variable_1 = 5 variable_2 = 6 my_long_var = 7 # Don't variable_1    = 5 variable_2    = 6 my_long_var  = 7Programming RecommendationsPEP 8 guidelines suggest different ways to maintain consistency among multiple implementations of Python like PyPy, Jython or Cython.An example of comparing boolean values:# Don't bool_value = 5 > 4 if bool_value == True: return '4 is smaller than 5' # Do if bool_value: return '4 is smaller than 5'Since bool can only accept values True or False, it is useless to use the equivalence operator == in these type of if executions. PEP 8 recommends the second example which will require lesser and simpler coding. An example to check whether a list is empty or not:# Don't list_value = [] if not len(list_value):     print('LIST IS EMPTY') # Do list_value = [] if not list_value:     print('LIST IS EMPTY')Any empty list or string in Python is falsy. So you can write a code to check an empty string without checking the length of the list. The second example is more simple, so PEP encourages to write an if statement in this way.The expression is not and not ... is are identical in functionality. But the former is more preferable due to its nature of readability:# Do if x is not None:     return 'x has a value' # Don't if not x is None:     return 'x has a value'String slicing is a type of indexing syntax that extracts substrings from a string. Whenever you want to check if a string is prefixed or suffixed, PEP recommends using .startswith() and .endswith() instead of list slicing. This is because they are cleaner and have lesser chances of error:# Do if foo.startswith('cat'): # Don't if foo[:3] == 'cat':An example using .endswith():# Don't if file_jpg[-3:] == 'jpg':     print('It is a JPEG image file') # Do if file_jpg.endswith('jpg'):     print('It is a JPEG image file')Though there exists multiple ways to execute a particular action, the main agenda of the guidelines laid by PEP 8 is simplicity and readability.When to Ignore PEP 8You should never ignore PEP 8. If the guidelines related to PEP8 are followed, you can be confident of writing readable and professional codes. This will also make the lives of your  colleagues and other members working on the same project much easier. There are some exclusive instances when you may ignore a particular guideline:After following the guidelines, the code becomes less readable, even for a programmer who is comfortable with reading codes that follow PEP 8.If the surrounding code is inconsistent with PEP.Compatible of code with older version of Python is the priority.Checking PEP 8 Compliant CodeYou can check whether your code actually complies with the rules and regulations of PEP 8 or not. Linters and Autoformatters are two classes of tools used to implement and check PEP 8 compliance.LintersIt is a program that analyzes your code and detects program errors, syntax errors, bugs and structural problems. They also provide suggestions to correct the errors.Some of the best linters used for Python code:pycodestyle is a tool to verify the PEP 8 style conventions in your Python code.You can run the following from the command line to install pycodestyle using pip:pip install pycodestyleTo display the errors of a program, run pycodestyle in this manner:pycodestyle my_code.pymy_code.py:1:11: E231 missing whitespace after '{'my_code.py:3:19: E231 missing whitespace after ')'my_code.py:4:31: E302 expected 2 blank lines, found 1flake8 is a Python wrapper that verifies PEP 8, pyflakes, and circular complexity.Type the command to install flake8 using pip:pip install flake8Run flake8 from the terminal using the command:flake8 calc.py calc.py:24:3: E111 indentation is not a multiple of twocalc.py:25:3: E111 indentation is not a multiple of twocalc.py:45:9: E225 missing whitespace around operatorYou can also use some other good linters like pylint, pyflakes, pychecker and mypy.AutoformattersAn autoformatter is a tool which will format your code to adapt with PEP 8 automatically.One of the most commonly used autoformatter is black.To install black using pip, type:pip install blackRemember, you need to have Python 3.6 or above to install black.An example of code that doesn’t follow PEP 8:def add(a, b): return a+b def multiply(a, b):       return \         a   * bNow run black following the filename from the terminal:black my_code.pyreformatted my_code.pyAll done! The reformatted code will look like:def add(a, b):     return a + b def multiply(a, b):     return a * bSome other autoformatters include autopep8 and yapf. Their work is similar to black.ConclusionSince you have now learnt to write a good-quality and readable Python code using PEP 8, you’ll consider it a bliss while working in a project. Though it might be too precise in its nature, it will be useful to everyone working in a particular project by making the code more understandable and making changes and debugging easier.Let us sum up what we’ve learnt so far:What is PEP 8 and what is its importance.Multiple guidelines for writing PEP 8 compliant code.How to check code against PEP 8 using linters and autoformatters.If you intend to know more about PEP 8 and its book of guidelines, you can refer to pep8.org or simply enroll for the Python certification course offered by KnowledgeHut.
Rated 4.5/5 based on 1 customer reviews

How To Write Beautiful Python Code With PEP 8

8683
How To Write Beautiful Python Code With PEP 8

It gets difficult to understand a messed up handwriting, similarly an unreadable and unstructured code is not accepted by all. However, you can benefit as a programmer only when you can express better with your code. This is where PEP comes to the rescue. 

Python Enhancement Proposal or PEP is a design document which provides information to the Python community and also describes new features and document aspects, such as style and design for Python.

Python is a multi-paradigm programming language which is easy to learn and has gained popularity in the fields of Data Science and Web Development over a few years and PEP 8 is called the style code of Python. It was written by Guido van Rossum, Barry Warsaw, and Nick Coghlan in the year 2001. It focuses on enhancing Python’s code readability and consistency. Join the certification course on Python Programming and gain skills and knowledge about various features of Python along with tips and tricks.

A Foolish Consistency is the Hobgoblin of Little Minds

‘A great person does not have to think consistently from one day to the next’ — this is what the statement means.

Consistency is what matters. It is considered as the style guide. You should maintain consistency within a project and mostly within a function or module.

However, there will be situations where you need to make use of your own judgement, where consistency isn’t considered an option. You must know when you need to be inconsistent like for example when applying the guideline would make the code less readable or when the code needs to comply with the earlier versions of Python which the style guide doesn’t recommend. 

In simple terms, you cannot break the backward compatibility to follow with PEP.

The Zen of Python

It is a collection of 19 ‘guiding principles’ which was originally written by Tim Peters in the year 1999. It guides the design of the Python Programming Language.

Python was developed with some goals in mind. You can see those when you type the following code and run it:

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

The Need for PEP 8

Readability is the key to good code. Writing good code is like an art form which acts as a subjective topic for different developers.

Readability is important in the sense that once you write a code, you need to remember what the code does and why you have written it. You might never write that code again, but you’ll have to read that piece of code again and again while working in a project. 

PEP 8 adds a logical meaning to your code by making sure your variables are named well, sufficient whitespaces are there or not and also by commenting well. If you’re a beginner to the language, PEP 8 would make your coding experience more pleasant.

Following PEP 8 would also make your task easier if you’re working as a professional developer. People who are unknown to you and have never seen how you style your code will be able to easily read and understand your code only if you follow and recognize a particular guideline where readability is your de facto.

And as Guido van Rossum said— “Code is read much more than it is often written”.

The Code Layout

Your code layout has a huge impact on the readability of your code.

Indentation

The indentation level of line is computed by the leading spaces and tabs at the beginning of a line of logic. It influences the grouping of statements. 

The rules of PEP 8 says to use 4 spaces per indentation level and also spaces should be preferred over tabs.

An example of code to show indentation:

x = 5
if x < 10:
  print('x is less than 10') 

Tabs or Spaces?

Here the print statement is indented which informs Python to execute the statement only if the if statement is true. Indentation also helps Python to know what code it will execute during function calls and also when using classes.

PEP 8 recommends using 4 spaces to show indentation and tabs should only be used to maintain consistency in the code.

Python 3 forbids the mixing of spaces and tabs for indentation. You can either use tabs or spaces and you should maintain consistency while using Python 3. The errors are automatically displayed:

python hello.py
  File "hello.py", line 3
      print(i, j)
                ^

TabError: inconsistent use of tabs and spaces in indentation

However, if you’re working in Python 2, you can check the consistency by using a -t flag in your code which will display the warnings of inconsistencies with the use of spaces and tabs.

You can also use the -tt flag which will show the errors instead of warnings and also the location of inconsistencies in your code. 

Maximum Line Length and Line Breaking

The Python Library is conservative and 79 characters are the maximum required line limit as suggested by PEP 8. This helps to avoid line wrapping.

Since maintaining the limit to 79 characters isn’t always possible, so PEP 8 allows wrapping lines using Python’s implied line continuation with parentheses, brackets, and braces:

def function(argument_1, argument_2,
            argument_3, argument_4):
    return argument_1

Or by using backslashes to break lines:

with open('/path/to/some/file/you/want/to/read') as example_1, \
    open('/path/to/some/file/being/written', 'w') as example_2:
    file_2.write(file_1.read())

When it comes to binary operators, PEP 8 encourages to break lines before the binary operators. This accounts for more readable code.

Let us understand this by comparing two examples:

# Example 1
# Do
total = ( variable_1 + variable_2 - variable_3 )
# Example 2
# Don't
total = ( variable_1 + variable_2 - variable_3 )

In the first example, it is easily understood which variable is added or subtracted, since the operator is just next to the variable to which it is operated. However, in the second example, it is a little difficult to understand which variable is added or subtracted.

Indentation with Line Breaks

Indentation allows a user to differentiate between multiple lines of code and a single line of code that spans multiple lines. It enhances readability too.

The first style of indentation is to adjust the indented block with the delimiter:

def function(argument_one, argument_two,
              argument_three, argument_four):
        return argument_one

You can also improve readability by adding comments:

x = 10
if (x > 5 and
    x < 20):
    # If Both conditions are satisfied
    print(x)

Or by adding extra indentation:

x = 10
if (x > 5 and
      x < 20):
    print(x)

Another type of indentation is the hanging indentation by which you can symbolize a continuation of a line of code visually:

foo = long_function_name(
      variable_one, variable_two,
      variable_three, variable_four)

You can choose any of the methods of indentation, following line breaks, in situations where the 79 character line limit forces you to add line breaks in your code, which will ultimately improve the readability.

Closing Braces in Line Continuations

Closing the braces after line breaks can be easily forgotten, so it is important to put it somewhere where it makes good sense or it can be confusing for a reader.

One way provided by PEP 8 is to put the closing braces with the first white-space character of the last line:

my_list_of_numbers = [
    1, 2, 3,
    4, 5, 6,
    7, 8, 9
    ]

Or lining up under the first character of line that initiates the multi-line construct:

my_list_of_numbers = [
    1, 2, 3,
    4, 5, 6,
    7, 8, 9
]

Remember, you can use any of the two options keeping in mind the consistency of the code.

Blank Lines

Blank lines are also called vertical whitespaces. It is a logical line consisting of spaces, tabs, formfeeds or comments that are basically ignored.

Using blank lines in top-level-functions and classes:

class my_first_class:
    pass
class my_second_class:
    pass
def top_level_function():
    return None

Adding two blank lines between the top-level-functions and classes will have a clear separation and will add more sensibility to the code.

Using blank lines in defining methods inside classes:

class my_class:
    def method_1(self):
        return None

    def method_2(self):
        return None

Here, a single vertical space is enough for a readable code.

You can also use blank spaces inside multi-step functions. It helps the reader to gather the logic of your function and understand it efficiently. A single blank line will work in such case.

An example to illustrate such:

def calculate_average(number_list):
    sum_list = 0
    for number in number_list:
        sum_list = sum_list + number
   
    average = 0
    average = sum_list / len(number_list)

   return average

Above is a function to calculate the average. There is a blank line between each step and also before the return statement.

The use of blank lines can greatly improve the readability of your code and it also allows the reader to understand the separation of the sections of code and the relation between them.

Naming Conventions

Choosing names which are sensible and can be easily understandable, while coding in Python, is very crucial. This will save time and energy of a reader. Inappropriate names might lead to difficulties when debugging.

Naming Styles

Naming variables, functions, classes or methods must be done very carefully. Here’s a list of the type, naming conventions and examples on how to use them:

TypeNaming ConventionsExamples
VariableUsing short names with CapWords.T, AnyString, My_First_Variable
FunctionUsing a lowercase word or words with underscores to improve readability.function, my_first_function
ClassUsing CapWords and do not use underscores between words.Student, MyFirstClass
MethodUsing lowercase words separated by underscores.Student_method, method
ConstantsUsing all capital letters with underscores separating wordsTOTAL, MY_CONSTANT, MAX_FLOW
ExceptionsUsing CapWords without underscores.IndexError, NameError
ModuleUsing short lower-case letters using underscores.module.py, my_first_module.py
PackageUsing short lowercase words and underscores are discouraged.package, my_first_package

Choosing names

To have readability in your code, choose names which are descriptive and give a clearer sense of what the object represents. A more real-life approach to naming is necessary for a reader to understand the code.

Consider a situation where you want to store the name of a person as a string:

>>> name = 'John William'
>>> first_name, last_name = name.split()
>>> print(first_name, last_name, sep='/ ')
John/ William

Here, you can see, we have chosen variable names like first_name and last_name which are clearer to understand and can be easily remembered. We could have used short names like x, y or z but it is not recommended by PEP 8 since it is difficult to keep track of such short names.

Consider another situation where you want to double a single argument. We can choose an abbreviation like db for the function name:

# Don't
def db(x):
    return x * 2

However, abbreviations might be difficult in situations where you want to return back to the same code after a couple of days and still be able to read and understand. In such cases, it’s better to use a concise name like double_a_variable:

# Do
def double_a_value(x):
    return x * 2

Ultimately, what matters is the readability of your code.

Comments

A comment is a piece of code written in simple English which improves the readability of code without changing the outcome of a program. You can understand the aim of the code much faster just by reading the comments instead of the actual code. It is important in analyzing codes, debugging or making a change in logic. 

Block Comments

Block comments are used while importing data from files or changing a database entry where multiples lines of code are written to focus on a single action. They help in interpreting the aim and functionality of a given block of code.

They start with a hash(#) and a single space and always indent to the same level as the code:

for i in range(0, 10):
    # Loop iterates 10 times and then prints i
    # Newline character
    print(i, '\n')

You can also use multiple paragraphs in a block comment while working on a more technical program. 

Block comments are the most suitable type of comments and you can use it anywhere you like.

Inline Comments

Inline comments are the comments which are placed on the same line as the statement. They are helpful in explaining why a certain line of code is essential.

Example of inline comments:

x = 10  # An inline comment
y = 'JK Rowling' # Author Name

Inline comments are more specific in nature and can easily be used which might lead to clutter. So, PEP 8 basically recommends using block comments for general-purpose coding.

Document Strings

Document strings or docstrings start at the first line of any function, class, file, module or method. These type of comments are enclosed between single quotations ( ''') or double quotations ( """ ).

An example of docstring:

def quadratic_formula(x, y, z, t):
    """Using the quadratic formula"""
    t_1 = (- b+(b**2-4*a*c)**(1/2)) / (2*a)
    t_2 = (- b-(b**2-4*a*c)**(1/2)) / (2*a)

    return t_1, t_2

Whitespaces in Expressions and Statements

In computing, whitespace is any character or sequence of characters which are used for spacing and have an ‘empty’ representation. It is helpful in improving the readability of expressions and statements if used properly.

Whitespace around Binary Operators

When you’re using assignment operators ( =, +=, -=,and so forth ) or comparisons ( ==, !=, >, <. >=, <= ) or booleans ( and, not, or ), it is suggested to use a single whitespace on the either side.

Example of adding whitespace when there is more than one operator in a statement:

# Don't
b = a ** 2 + 10
c = (a + b) * (a - b)

# Do
b = a**2 + 10
c = (a+b) * (a-b)

In such mathematical computations, you should add whitespace around the operators with the least priority since adding spaces around each operator might be confusing for a reader.

Example of adding whitespaces in an if statement with many conditions:

# Don't
if a < 10 and a % 5 == 0:
    print('a is smaller than 10 and is divisible by 5!')

# Do
if a<10 and a%5==0:
    print('a is smaller than 10 and is divisible by 5!')

Here, the and operator has the least priority, so whitespaces have been added around it.

Colons act as binary operators in slices:

ham[3:4]

ham[x+1 : x+2]

ham[3:4:5]

ham[x+1 : x+2 : x+3]

ham[x+1 : x+2 :]

Since colons act as a binary operator, whitespaces are added on either side of the operator with the lowest priority. Colons must have the same amount of spacing in case of an extended slice. An exception is when the slice parameter is omitted, space is also omitted.

Avoiding Whitespaces

Trailing whitespaces are whitespaces placed at the end of a line. These are the most important to avoid. 

You should avoid whitespaces in the following cases—

Inside a parentheses, brackets, or braces:

# Do
list = [1, 2, 3]

# Don't
list = [ 1, 2, 3, ]

Before a comma, a semicolon, or a colon:

x = 2
y = 3

# Do
print(x, y)

# Don't
print(x , y)

Before open parenthesis that initiates the argument list of a function call:

def multiply_by_2(a):
      return a * 2

# Do
multiply_by_2(3)

# Don't
multiply_by_2 (3)

Before an open bracket that begins an index or a slice:

# Do
ham[5]

# Don't
ham [5]

Between a trailing comma and a closing parenthesis:

# Do
spam = (1,)

# Don't
spam = (1, )

To adjust assignment operators:

# Do
variable_1 = 5
variable_2 = 6
my_long_var = 7

# Don't
variable_1    = 5
variable_2    = 6
my_long_var  = 7

Programming Recommendations

PEP 8 guidelines suggest different ways to maintain consistency among multiple implementations of Python like PyPy, Jython or Cython.

An example of comparing boolean values:

# Don't
bool_value = 5 > 4
if bool_value == True:
return '4 is smaller than 5'

# Do
if bool_value:
return '4 is smaller than 5'

Since bool can only accept values True or False, it is useless to use the equivalence operator == in these type of if executions. PEP 8 recommends the second example which will require lesser and simpler coding. 

An example to check whether a list is empty or not:

# Don't
list_value = []
if not len(list_value):
    print('LIST IS EMPTY')

# Do
list_value = []
if not list_value:
    print('LIST IS EMPTY')

Any empty list or string in Python is falsy. So you can write a code to check an empty string without checking the length of the list. The second example is more simple, so PEP encourages to write an if statement in this way.

The expression is not and not ... is are identical in functionality. But the former is more preferable due to its nature of readability:

# Do
if x is not None:
    return 'x has a value'

# Don't
if not x is None:
    return 'x has a value'

String slicing is a type of indexing syntax that extracts substrings from a string. Whenever you want to check if a string is prefixed or suffixed, PEP recommends using .startswith() and .endswith() instead of list slicing. This is because they are cleaner and have lesser chances of error:

# Do
if foo.startswith('cat'):

# Don't
if foo[:3] == 'cat':

An example using .endswith():

# Don't
if file_jpg[-3:] == 'jpg':
    print('It is a JPEG image file')

# Do
if file_jpg.endswith('jpg'):
    print('It is a JPEG image file')

Though there exists multiple ways to execute a particular action, the main agenda of the guidelines laid by PEP 8 is simplicity and readability.

When to Ignore PEP 8

You should never ignore PEP 8. If the guidelines related to PEP8 are followed, you can be confident of writing readable and professional codes. This will also make the lives of your  colleagues and other members working on the same project much easier. 

There are some exclusive instances when you may ignore a particular guideline:

  • After following the guidelines, the code becomes less readable, even for a programmer who is comfortable with reading codes that follow PEP 8.
  • If the surrounding code is inconsistent with PEP.
  • Compatible of code with older version of Python is the priority.

Checking PEP 8 Compliant Code

You can check whether your code actually complies with the rules and regulations of PEP 8 or not. Linters and Autoformatters are two classes of tools used to implement and check PEP 8 compliance.

Linters

It is a program that analyzes your code and detects program errors, syntax errors, bugs and structural problems. They also provide suggestions to correct the errors.

Some of the best linters used for Python code:

  • pycodestyle is a tool to verify the PEP 8 style conventions in your Python code.

You can run the following from the command line to install pycodestyle using pip:

pip install pycodestyle

To display the errors of a program, run pycodestyle in this manner:

pycodestyle my_code.py

my_code.py:1:11: E231 missing whitespace after '{'

my_code.py:3:19: E231 missing whitespace after ')'

my_code.py:4:31: E302 expected 2 blank lines, found 1

  • flake8 is a Python wrapper that verifies PEP 8, pyflakes, and circular complexity.

Type the command to install flake8 using pip:

pip install flake8

Run flake8 from the terminal using the command:

flake8 calc.py 

calc.py:24:3: E111 indentation is not a multiple of two

calc.py:25:3: E111 indentation is not a multiple of two

calc.py:45:9: E225 missing whitespace around operator

You can also use some other good linters like pylintpyflakes, pychecker and mypy.

Autoformatters

An autoformatter is a tool which will format your code to adapt with PEP 8 automatically.One of the most commonly used autoformatter is black.

To install black using pip, type:

pip install black

Remember, you need to have Python 3.6 or above to install black.

An example of code that doesn’t follow PEP 8:

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

def multiply(a, b):
      return \
        a   * b

Now run black following the filename from the terminal:

black my_code.py

reformatted my_code.py

All done! 

The reformatted code will look like:

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

def multiply(a, b):
    return a * b

Some other autoformatters include autopep8 and yapf. Their work is similar to black.

Conclusion

Since you have now learnt to write a good-quality and readable Python code using PEP 8, you’ll consider it a bliss while working in a project. Though it might be too precise in its nature, it will be useful to everyone working in a particular project by making the code more understandable and making changes and debugging easier.

Let us sum up what we’ve learnt so far:

  • What is PEP 8 and what is its importance.
  • Multiple guidelines for writing PEP 8 compliant code.
  • How to check code against PEP 8 using linters and autoformatters.

If you intend to know more about PEP 8 and its book of guidelines, you can refer to pep8.org or simply enroll for the Python certification course offered by KnowledgeHut.

Priyankur

Priyankur Sarkar

Data Science Enthusiast

Priyankur Sarkar loves to play with data and get insightful results out of it, then turn those data insights and results in business growth. He is an electronics engineer with a versatile experience as an individual contributor and leading teams, and has actively worked towards building Machine Learning capabilities for organizations.

Join the Discussion

Your email address will not be published. Required fields are marked *

1 comments

Ramya 16 Aug 2019

NIce article.

Suggested Blogs

Scala Vs Kotlin

Ever-changing requirements in coding have always been happening, ones that cause programmers to change their minds about using the appropriate programming language and tools to code. Java has been there for a long time, a really long time, 24 years ago. It is relatively easy to use, write, compile, debug, and learn than other programming languages. However, its certain inhibitions like slow performance, unavailability of any support for low-level programming, possessing poor features in GUI 4, and having no control over garbage collection is putting Java developers in a dilemma on choosing an alternative to Java, such as JetBrains’ programming language, Kotlin, presently an officially supported language for Android development or Scala, an all-purpose programming language supporting functional programming and a strong static type system. Today, we will discuss how developers can decide to choose Scala or Kotlin as an alternative to Java. We will briefly talk about Scala and Kotlin separately and talk about their application before moving forward to looking at the differences, advantages, and disadvantages of both and finally have you decide which one of these two suits your requirements. User’s requirement Before we begin, here is a question for the readers, ‘What are you looking for in the next programming language that you will use?’ It is an obvious question because the programming purposes drive the actual basis and need of developing a language. Do you need a language that strives to better Java or use a language that lets you do things that aren’t possible in Java? If it is the first reason, then Scala might be the best one for you, otherwise, it is a simplified programming language like Kotlin. Now let us first briefly discuss Scala and Kotlin individually. ScalaDeveloped by Martin Odersky, the first version of Scala was launched in the year 2003 and is a classic example of a  general-purpose, object-oriented computer language, offering a wide range of functional programming language features and a strong static type system. Inspired from Java itself, Scala, as the name suggests, is highly scalable and this very feature sets Scala apart from other programming languages. When we say that Scala is inspired from Java, that means developers can code Scala in the same way they do for Java. Additionally, Scala makes it possible to use numerous Java and libraries within itself as well. It is designed to be able to use an elegant, concise and type-safe method to express common programming patterns. Scala is a very popular programming language amongst developers and rising up its ranks in the world of technology. Although Scala comes with a number of plus points, there are some which make it a bit ineffective. Here are the strengths and weaknesses of Scala. Strengths: Full Support for Pattern Matching, Macros, and Higher-Kinded Types Has a very flexible code syntax Gets a bigger Community Support Enables overloading operators Weaknesses: Slow in compilation Challenging Binary Compilation Not so proficient in the Management of Null SafetyKotlin Developed by JetBrains, Kotlin was released on February 2012 as an open-source language. Until now, there have been two released versions with the latest one being Kotlin 1.2, the most stable version that was released on November 28, 2017. Since Kotlin is extremely compatible with Java 6 the latest version of Java on Android, it has gained critical acclaim on Android worldwide and additionally, it offers various key features that are prepared only for Java 8 and not even Java 6 developers have access to that. Kotlin provides seamless and flawless interoperability with Java. That means, developers can easily call Java codes from Kotlin and same goes the other way around. The built-in null safety feature avoids showing the NullPointerException (NPE) that makes developing android apps easy and joyful, something every android programmer wants. Below mentioned are the key pointers on the strengths and weaknesses of Kotlin. Strengths Takes a Functional Programming Approach and Object-Oriented Programming style(OOP) Style  Has Higher-Order Functions Short, Neat, and Verbose-Free Expression  Supported by JetBrains and Google. Weaknesses: More limited Pattern Matching Additional Runtime Size Initial Readability of Code Shortage of Official Support Smaller Support Community. Ease of learning: Scala vs Kotlin Scala is a powerful programming language packed with superior features and possesses a flexible syntax. It is not an easy language to learn and is a nightmare for newcomers. Kotlin, on the other hand, has been reported to have been an easy-to-learn language for many Java developers as getting started with Kotlin is relatively easy and so is writing codes. Even though it is a comparatively easier language to learn and code with, Kotlin lacks the solid set of features that is common in Scala. It might take less time to learn a programming language, but the most important thing to look for is a comprehensive array of features. Scala, even though a very difficult language to learn, is cherished by the developers as it lets them do things that cannot be done in Kotlin Here are the major differences between Scala and Kotlin: ScalaKotlinType inferenceEfficientImmutabilityExtension FunctionsSingleton objectMassive InteroperabilityConcurrency controlLessens Crashes at RuntimeString interpolationSmart Cast FunctionHigher-order functionSafe and ReliableCase classes and Pattern matching Lazy computationLow adoption costRich collection setMaking the appropriate choice of languageNow, whether you may like a programming language or not, if that very language helps you get the best out of your job, then you will have to live with it. These are the facts about getting the best results. The outcome is the main factor in you deciding the appropriate language for your job. Kotlin is the only option for Android development as Android doesn’t use JVM, so any old JVM-compatible language will not work in Android. Kotlin has it all what it takes to compile, debug, and run the software on Android because of which it is in-built into Android Studio. However, Kotlin is not so usable outside Android development. If you are one of the developers who like working with Eclipse for your IDE, then Scala IDE is better than the Kotlin Plugin even if you can make Eclipse work with both the languages with limitations. Scala IDE is more advanced than the Kotlin plugin and is easier to set up. Some developers found it quite difficult to make the Kotlin plugin work. This case is quite the same with NetBeans. Kotlin is still getting there but is already popular amongst Java developers as it offers an easier transition than Scala. Kotlin is still maturing, but many Java people find adopting it is an easier transition than Scala is.  Scala, however, is for developers who are focused more on discovering new ideas while Kotlin is for those who want to get results. Kotlin stresses fast compilation but is more restrictive while Scala gives a lot of flexibility. Go for Scala if you breathe functional programming! It has more appropriate features for this type of programming than Kotlin does. Scala supports currying and partial application, the methods of breaking down functions requiring multiple arguments offering more flexibility. Go for the one that is the most appropriate one for your work, style of working and what you are aiming at. Think before you leap. The Outcome At the end of the day, all that matters is what you want to use the language for. While Scala goes well for the projects that require a combination of functional, OOP style programming languages, and where programmers need to handle lots of data or complex modelling, Kotlin becomes the best choice when you want something less frustrating than Java while developing apps because using Kotlin makes app development less cumbersome and a great thing to work on. It is just like a better-looking version of Java with less lengthy codes. 
Rated 4.5/5 based on 19 customer reviews
7590
Scala Vs Kotlin

Ever-changing requirements in coding have always b... Read More

Xcode vs Swift

Xcode and Swift are two different products developed by Apple for macOS, iOS, iPadOS, watchOS, and tvOS. While Xcode is an integrated development environment (IDE) for macOS containing a suite of software development tools to develop software for macOS, iOS, iPadOS, watchOS, and tvOS, Swift is a general-purpose, multi-paradigm, compiled programming language developed iOS, macOS, watchOS, tvOS, Linux, and z/OS. So it is clear that they can not be compared with each other. On the contrary, Swift is compatible with Xcode as Swift v 5.1, the default version of Swift is included in Xcode v 11. In this article, we will go through what Xcode and Swift are in general and cover their features strengths and weaknesses followed by how Swift is compatible with Xcode. XcodeIt was first released in 2003 as version 1 with the latest stable one being version 10.2.1 released on 17 April 2019. It can be downloaded from the Mac App Store and is free to use for macOS Mojave users. Registered developers may download the preview releases and previous versions of the suite using via the Apple Developer website.  Overview of the major featuresSupport: Programming languages such as C, C++, Objective-C, Objective-C++, Java, AppleScript, Python, Ruby, ResEdit (Rez), and Swift are supported by Xcode with source code along with support for a variety of programming models including Cocoa, Carbo, and Java. Not only that, there is additional support via third parties for GNU Pascal, Free Pascal, Ada, C#, Perl, and D Capability: Xcode can build fat binary files that include the code for various architectures in the Mach-O executable format. Known as universal binary files, these allow the application to run on both PowerPC and Intel-based (x86) platforms including both 32-bit and 64-bit codes Compiling and debugging: Xcode uses the iOS SDK to compile and debug applications for iOS that run on ARM architecture processors GUI tool: Xcode comprises of the GUI tool, Instruments that runs dynamic tracing framework on the top of DTrace, a dynamic tracing framework designed by Sun Microsystems and released as a part of OpenSolaris. Advantages and disadvantages of Xcode: Xcode is designed by Apple and will only work with Apple operating systems: macOS, iOS, iPadOS, watchOS, and tvOS. Since its release in 2003, Xcode has made significant improvements and the latest version, Xcode 10.2.1 has all the features that are needed to perform continuous integration. Let us have a look at the pros of using Xcode: Equipped with a well designed and easy to use UI creator Excellent for code completion Using Xcode, a developer can learn profiling and heap analysis in a natural way Xcode’s simulator lets you easily test your app while you build it in an environment that simulates your iPhone The app store has a wide range of audience who are willing to pay for apps. Now, the cons: Clunky and outdated Objective C makes it more frustrating if you are habituated to use a modern language No support for tabbed work environments makes it difficult to work with multiple windows Hardly any information can be found online to solve problems due to a previous Apple NDA on Xcode development It is a complicated process to export your app onto a device Will only work with Apple operating systems The App Store approval process can be annoyingly lengthy.SwiftSwift was launched at Apple's 2014 Worldwide Developers Conference as a general-purpose, multi-paradigm, compiled programming language for iOS, macOS, watchOS, tvOS, Linux, and z/OS Being a new entry these operating systems, Swift accelerates on the best parts of C and Objective C without being held back by its compatibility. It utilises safe patterns for programming, adding more features to it, thus making programming easier and more flexible. By developing their existing debugger, compiler and framework infrastructure, it took quite some time to create the base for Swift. Furthermore, Automatic Reference Counting was used to simplify the memory management part. The framework stack which was once built upon a solid framework of Cocoa and Foundation has undergone significant changes and is now completely regulated and refurbished. Developers who have worked with Objective-C do find Swift quite similar. Objective-C’s dynamic object model and its comprehensively named parameters provide a lot of control to Swift.  Developers can use Swift to have access to the existing Cocoa framework in addition to the mix and match interoperability with an objective C code. Swift uses this common rule to offer multiple new features in combination with object-oriented and procedural portions of the language. The idea is to create the best possible language for a wide range of uses, varying from desktop and mobile apps, systems programming, and scaling up to cloud services. The designing of Swift was done to make sure that developers find it easy to maintain and write correct programs. Coding done in Xcode is safe, fast and expressive. Swift offers a host of features that give developers the control needed to make the code easy to read and write. Furthermore, Apple made Swift to be easily understandable to help developers avoid making mistakes while coding and make the code look organised, along with the modules that give namespaces and eliminate headers. Since Swift uses some features present in other languages, one of them being named parameters written with clean syntax that makes the APIs much easier to maintain and read. Here are some of the additional features of Swift: Multiple return values and Tuples Generics Short and quick iterations over a collection or range Structs that support extensions, methods and protocols Functional programming patterns Advanced control flow Powerful error handling. These features are systematically designed to make them work together resulting in creating a powerful but fun-to-use language. Advantages and disadvantages of Swift: Pros of using the Swift Programming language: Easy to read and maintain: The Swift program codes are based on natural English as it has borrowed syntaxes from other programming languages. This makes the language more expressive Scalable: Users can add more features to Swift, making it a scalable programming language. In the future, Swift is what Apple is relying on and not Objective C Concise: Swift does not include long lines of code and that favours the developers who want a concise syntax, thus increasing the development and testing rate of the program Safety and improved performance: It is almost 40% better than the Objective-C when speed and performance are taken into consideration as it is easy to tackle the bugs which lead to safer programming Cross-device support: This language is capable of handling a wide range of Apple platforms such as iOS, iOS X, macOS, tvOS, and watchOS. Automatic Memory Management: This feature present in Swift prevents memory leaks and helps in optimizing the application’s performance that is done by using Automatic Reference Counting. Cons of Swift: Compatibility issues: The updated versions Swift is found to a bit unstable with the newer versions of Apple leading to a few issues. Switching to a newer version of Swift is the fix but that is costly Speed Issues: This is relevant to the earlier versions of the Swift programming language Less in number: The number of Swift developers is limited as Swift is a new programming language Delay in uploading apps: Developers will be facing delays over their apps written in Swift to be uploaded to the App Store only after iOS 8 and Xcode 6 are released. The estimated time for release is reported to be September-October, 2014. Conclusion So as we discussed both Xcode and Swift, it is clear that they cannot be compared to each other. In fact, they both complement each other to deliver impressive results without any headaches. Apple relies on both quite a lot and it is certain to have Swift and Xcode the perfect combination of a robust application and a user-friendly programming language.
Rated 4.5/5 based on 11 customer reviews
8588
Xcode vs Swift

Xcode and Swift are two different products develop... Read More

ASP.NET VS PHP

ASP.NET and PHP are pretty popular languages in the programming world used by a huge number of developers and this makes it difficult for the new developers to choose either one of them. The comparison between these two has been in debate in recent times. Both of these languages are used in large web-based applications. Some successful companies like Google, Facebook, and Twitter, etc, also use these languages. In this article, we will understand the differences between PHP and ASP.Net also, will discuss which is better ASP.NET or PHP.Before we learn more about the differences between the two languages, we must first understand some basics of the two technologies:PHPPHP stands for Hypertext Preprocessor. It is an open-source programming language that is used for web development and can be embedded into HTML. The best part of PMP is that it’s free and possesses a  ton of frameworks which simplifies web development and also great for beginners since it allows simple and easy coding techniques. PHP is great for professionals as well because of its advanced features.Why use a PHP framework?A PHP framework provides a basic structure for streamlining the development of web apps. The applications and websites built using PHP frameworks will help the businesses to improve their performance needs.The best PHP frameworks available:LaravelCodeIgniterSymfonyZendPhalconCakePHPYiiFuelPHPPros and Cons of PHP frameworkPros:Rapid Development                                              Centralized DatabaseStronger TeamworkMakes your application more secure               Cons:Slower ExecutionPHP is unsecuredPoor error handling methodLimited Visibility and ControlDemand for PHP Developer:In today’s web development market, most of the websites are developed using PHP development tools which indicates a huge demand for PHP developers. If you are looking to make an entry to the IT world as a developer, then PHP programming will be an easy entry point.Taking up a PHP training from an authentic and reliable training provider will be a great platform to hone your skills.ASP.NETASP.NET is an open-source server-side web development tool developed by Microsoft for easy building of web applications and web pages. It can be written using any .Net supported language which makes it more popular among .NET developers. High speed and low cost are the main reasons to use it. Websites built ASP.NET is faster and more efficient than a website built with PHP.Pros and Cons of ASP.NET frameworkPros:Less coding timeWorld class toolboxConsistencyCustomizability and ExtensibilityCons:Limited Object-Relational (OR) supportBit expensiveSlower than Native CodeDemand for ASP.NET Developer:If you are a .NET developer, you will find yourself demanded by several asp.net development companies as your programming skills are extremely valuable in today’s market. There are many companies hunting for developers who can do programming with .NET. Therefore, it is advisable that you brush up your skills with ASP.NET Certification Training which will increase your value many times and have an edge over others. The ASP.NET Certification Training program will definitely make your future bright and offer you heaps of career opportunities. Whether you are a fresher or a working professional, you can take up the certification course.Comparison Between ASP.NET and PHPBoth ASP.NET and PHP frameworks are effective frameworks to work with, however, one may have few advantages over the other. Let’s dive deeper and compare these frameworks to understand which one is better than the other.1. Market Share:According to the report, BuiltWith data source PHP is the most used programming language which has 73% of market share, ASP.NET has 23% of market share. PHP also has a market share of 58% in top 100K websites and market share of PHP in 10K websites is 52%.Statistics for websites using Programming Language technologies:2. WebsitesHere are two lists to compare ASP.NET vs PHP websites:Websites built using PHPWebsites built using ASP.NETWikipediaFacebookYahooWordPress.comiStockPhotoMicrosoftDellGoDaddy3. Inbuilt featuresPHP has many unique in-built features that can help web developers. On the other hand, ASP.NET doesn’t have any such features.4. Speed and PerformanceWhen you compare PHP vs. ASP.NET for speed, PHP will be the winner. ASP.NET is a bit slow compared to PHP as it is built on the COM-based system whereas, PHP program runs on its own memory space.5. Community SupportCompared to ASP.NET, learning support is great in the PHP framework and has a large support community. It will be difficult for you to get hold of #C language of ASP.NET as it is difficult to understand.Key differences between ASP.NET vs PHPPHPASP.NETPHP was launched by Rasmus Lerdorf in the year 1995.ASP.NET was launched by Microsoft in the year 2002.PHP is a scripting languageASP.NET is a paid Microsoft provided web application framework.PHP suits for small sized organizationsASP.NET suits for a large and medium-sized organization.PHP has a decent market share in the  marketASP.NET has a higher market sharePHP works slow for desktop applicationsASP.NET is well equipped to assist and create desktop applications.PHP suits best for applications that contain a prime focus on UIASP.NET suits better for applications where the key concern is security.Easy to learnQuite challenging to learn.Coding using PHP is easy when compared to all other languagesCoding with ASP.NET is complicatedPHP execution is faster since it uses in-built memory spaceCoding with ASP.NET is complicatedPHP can run in Linux Operating System which is available for freeASP.NET requires a Windows platform which is not freeConclusionBoth PHP and ASP.NET come with their pros and cons. PHP is secure, fast, reliable, and inexpensive and ASP.NET is easier to use and maintain because of its class library system. Since both programming languages are similar and accomplish the same results so the company can make a choice based on the needs and requirements of the app they are about to develop.
Rated 4.5/5 based on 1 customer reviews
7708
ASP.NET VS PHP

ASP.NET and PHP are pretty popular languages in th... Read More

20% Discount