Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
PEP 8 : Coding Style guide in Python
Next article icon

PEP 8 : Coding Style guide in Python

Last Updated : 24 Nov, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
Indeed coding and applying logic is the foundation of any programming language but there's also another factor that every coder must keep in mind while coding and that is the coding style. Keeping this in mind, Python maintains a strict way of order and format of scripting.Following this sometimes mandatory and is a great help on the user's end, to understand. Making it easy for others to read code is always a good idea, and adopting a nice coding style helps tremendously for that. For Python, PEP 8 has emerged as the style guide that most projects adhere to; it promotes a very readable and eye-pleasing coding style. Every Python developer should read it at some point; here are the most important points extracted for you: 1. Use 4-space indentation and no tabs. Examples:
# Aligned with opening delimiter.  grow = function_name(variable_one, variable_two,                       variable_three, variable_four)  
  # First line contains no argument. Second line onwards  # more indentation included to distinguish this from   # the rest.  def function_name(          variable_one, variable_two, variable_three,          variable_four):      print(variable_one)  
The 4 space rule is not always mandatory and can be overruled for continuation line. 2. Use docstrings : There are both single and multi-line docstrings that can be used in Python. However, the single line comment fits in one line, triple quotes are used in both cases. These are used to define a particular program or define a particular function. Example:
def exam():      """This is single line docstring"""        """This is      a      multiline comment"""  
3. Wrap lines so that they don't exceed 79 characters : The Python standard library is conservative and requires limiting lines to 79 characters. The lines can be wrapped using parenthesis, brackets, and braces. They should be used in preference to backslashes. Example:
with open('/path/from/where/you/want/to/read/file') as file_one, \       open('/path/where/you/want/the/file/to/be/written', 'w') as file_two:      file_two.write(file_one.read())  
4. Use of regular and updated comments are valuable to both the coders and users : There are also various types and conditions that if followed can be of great help from programs and users point of view. Comments should form complete sentences. If a comment is a full sentence, its first word should be capitalized, unless it is an identifier that begins with a lower case letter. In short comments, the period at the end can be omitted. In block comments, there are more than one paragraphs and each sentence must end with a period. Block comments and inline comments can be written followed by a single '#'. Example of inline comments:
geek = geek + 1                 # Increment  
5. Use of trailing commas : This is not mandatory except while making a tuple. Example:
tup = ("geek",)  
5. Use Python's default UTF-8 or ASCII encodings and not any fancy encodings, if it is meant for international environment. 6. Use spaces around operators and after commas, but not directly inside bracketing constructs:
a = f(1, 2) + g(3, 4)
7. Naming Conventions : There are few naming conventions that should be followed in order to make the program less complex and more readable. At the same time, the naming conventions in Python is a bit of mess, but here are few conventions that can be followed easily. There is an overriding principle that follows that the names that are visible to the user as public parts of API should follow conventions that reflect usage rather than implementation. Here are few other naming conventions:
b (single lowercase letter)    B (single upper case letter)    lowercase    lower_case_with_underscores    UPPERCASE    UPPER_CASE_WITH_UNDERSCORES    CapitalizedWords (or CamelCase). This is also sometimes known as StudlyCaps.  Note: While using abbreviations in CapWords, capitalize all the letters   of the abbreviation. Thus HTTPServerError is better than HttpServerError.    mixedCase (differs from CapitalizedWords by initial lowercase character!)    Capitalized_Words_With_Underscores
In addition to these few leading or trailing underscores are also considered. Examples: single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore. single_trailing_underscore_: used to avoid conflicts with Python keyword. Example:
Tkinter.Toplevel(master, class_='ClassName')
__double_leading_underscore: when naming a class attribute, invokes name mangling. (inside class FooBar, __boo becomes _FooBar__boo;). __double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Only use them as documented. 8. Characters that should not be used for identifiers : 'l' (lowercase letter el), 'O' (uppercase letter oh), or 'I' (uppercase letter eye) as single character variable names as these are similar to the numerals one and zero. 9. Don’t use non-ASCII characters in identifiers if there is only the slightest chance people speaking a different language will read or maintain the code. 10. Name your classes and functions consistently : The convention is to use CamelCase for classes and lower_case_with_underscores for functions and methods. Always use self as the name for the first method argument. 11. While naming of function of methods always use self for the first argument to instance methods and cls for the first argument to class methods.If a functions argument name matches with reserved words then it can be written with a trailing comma. For e.g., class_ You can refer to this simple program to know how to write an understandable code: Python3
# Python program to find the # factorial of a number provided by the user.   # change the value for a different result  num = 7  # uncomment to take input from the user  #num = int(input("Enter a number: "))   factorial = 1  # check if the number is negative, positive or zero  if num < 0:      print("Sorry, factorial does not exist for negative numbers")  elif num == 0:      print("The factorial of 0 is 1")  else:      for i in range(1,num + 1):          factorial = factorial*i           print("The factorial of",num,"is",factorial)  
Output:
The factorial of 7 is 5040  

Next Article
PEP 8 : Coding Style guide in Python

C

Chinmoy Lenka
Improve
Article Tags :
  • Misc
  • Python
Practice Tags :
  • Misc
  • python

Similar Reads

    Python - Conventions and PEP8
    Convention means a certain way in which things are done within a community to ensure order. Similarly, Coding conventions are also a set of guidelines, but for a programming language that recommends programming style, practices, and methods. This includes rules for naming conventions, indentations,
    4 min read
    Types of Arguments in Python
    Arguments are the values passed inside the parenthesis of the function. A function can have any number of arguments separated by a comma. There are many types of arguments in Python .In this example, we will create a simple function in Python to check whether the number passed as an argument to the
    3 min read
    Statement, Indentation and Comment in Python
    Here, we will discuss Statements in Python, Indentation in Python, and Comments in Python. We will also discuss different rules and examples for Python Statement, Python Indentation, Python Comment, and the Difference Between 'Docstrings' and 'Multi-line Comments. What is Statement in Python A Pytho
    7 min read
    Python – The new generation Language
    INTRODUCTION: Python is a widely-used, high-level programming language known for its simplicity, readability, and versatility. It is often used in scientific computing, data analysis, artificial intelligence, and web development, among other fields. Python's popularity has been growing rapidly in re
    6 min read
    Comparing Old-Style and New-Style Classes in Python
    In Python, the difference between old-style and new-style classes is based on the inheritance from the built-in object class. This distinction was introduced in Python 2.x and was fully adopted in Python 3.x, where all classes are new-style classes. In this article, we will see the difference betwee
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences