Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
Python Data Structures Practice Problems
Next article icon

Structuring Python Programs

Last Updated : 13 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, you would come to know about proper structuring and formatting your python programs.

Python Statements In general, the interpreter reads and executes the statements line by line i.e sequentially. Though, there are some statements that can alter this behavior like conditional statements.
            Mostly, python statements are written in such a format that one statement is only written in a single line. The interpreter considers the ‘new line character’ as the terminator of one instruction. But, writing multiple statements per line is also possible that you can find below.
Examples:




# Example 1
  
print('Welcome to Geeks for Geeks') 
 
 
Output:
  Welcome to Geeks for Geeks  




# Example 2
  
x = [1, 2, 3, 4]
  
# x[1:3] means that start from the index 
# 1 and go upto the index 2
print(x[1:3])  
  
""" In the above mentioned format, the first 
index is included, but the last index is not
included."""
 
 
Output:
  [2, 3]  

Multiple Statements per Line We can also write multiple statements per line, but it is not a good practice as it reduces the readability of the code. Try to avoid writing multiple statements in a single line. But, still you can write multiple lines by terminating one statement with the help of ‘;’. ‘;’ is used as the terminator of one statement in this case.
        For Example, consider the following code.




# Example
  
a = 10; b = 20; c = b + a
  
print(a); print(b); print(c)
 
 
Output:
  10  20  30  

Line Continuation to avoid left and right scrolling
Some statements may become very long and may force you to scroll the screen left and right frequently. You can fit your code in such a way that you do not have to scroll here and there. Python allows you to write a single statement in multiple lines, also known as line continuation. Line continuation enhances readability as well.

# Bad Practice as width of this code is too much.     #code  x = 10  y = 20  z = 30  no_of_teachers = x  no_of_male_students = y  no_of_female_students = z     if (no_of_teachers == 10 and no_of_female_students == 30 and no_of_male_students == 20 and (x + y) == 30):      print('The course is valid')     # This could be done instead:     if (no_of_teachers == 10 and no_of_female_students == 30      and no_of_male_students == 20 and x + y == 30):      print('The course is valid')

Types of Line Continuation
In general, there are two types of line continuation

  • Implicit Line Continuation
    This is the most straightforward technique in writing a statement that spans multiple lines.
    Any statement containing opening parentheses (‘(‘), brackets (‘[‘), or curly braces (‘{‘) is presumed to be incomplete until all matching parentheses, square brackets, and curly braces have been encountered. Until then, the statement can be implicitly continued across lines without raising an error.
    Examples:




    # Example 1
      
    # The following code is valid
    a = [
        [1, 2, 3],
        [3, 4, 5],
        [5, 6, 7]
        ]
      
    print(a)
     
     
    Output:
      [[1, 2, 3], [3, 4, 5], [5, 6, 7]]  




    # Example 2
    # The following code is also valid
      
    person_1 = 18
    person_2 = 20
    person_3 = 12
      
    if (
       person_1 >= 18 and
       person_2 >= 18 and
       person_3 < 18
       ):
        print('2 Persons should have ID Cards')
     
     
    Output:
      2 Persons should have ID Cards  
  • Explicit Line Continuation
    Explicit Line joining is used mostly when implicit line joining is not applicable. In this method, you have to use a character that helps the interpreter to understand that the particular statement is spanning more than one lines.
            Backslash (\) is used to indicate that a statement spans more than one line. The point is to be noted that ” must be the last character in that line, even white-space is not allowed.
    See the following example for clarification




    # Example
      
    x = \
        1 + 2 \
        + 5 + 6 \
        + 10
      
    print(x)
     
     
    Output:
      24  
  • Comments in Python
    Writing comments in the code are very important and they help in code readability and also tell more about the code. It helps you to write details against a statement or a chunk of code. Interpreter ignores the comments and does not count them in commands. In this section, we’ll learn how to write comments in Python.
            Symbols used for writing comments include Hash (#) or Triple Double Quotation marks(“””). Hash is used in writing single line comments that do not span multiple lines. Triple Quotation Marks are used to write multiple line comments. Three triple quotation marks to start the comment and again three quotation marks to end the comment.
    Consider the following examples:




    # Example 1
      
    ####### This example will print Hello World ####### print('Hello World')  # This is a comment
     
     




    # Example 2
      
    """ This example will demonstrate 
        multiple comments """
      
    """ The following
        a variable contains the 
        string 'How old are you?'
    """
    a = 'How old are you?'
      
    """ The following statement prints
        what's inside the variable a 
    """
    print(a)
     
     

    Note Do note that Hash (#) inside a string does not make it a comment. Consider the following example for demonstration.




    # Example
      
    """ The following statement prints the string stored
        in the variable """
      
    a = 'This is # not a comment #'
    print(a) # Prints the string stored in a
     
     

    White spaces
    The most common whitespace characters are the following:

    Character ASCII Code Literal Expression
    Space 32 (0x20) ‘ ‘
    tab 9 (0x9) ‘\t’
    newline 10 (0xA) ‘\n’

    * You can always refer to ASCII Table by clicking here.

    Whitespace is mostly ignored, and mostly not required, by the Python interpreter. When it is clear where one token ends and the next one starts, whitespace can be omitted. This is usually the case when special non-alphanumeric characters are involved.
    Examples:




    # Example 1
      
    # This is correct but whitespace can improve readability
      
    a = 1-2  # Better way is a = 1 - 2
      
    print(a)
     
     




    # Example 2
      
    # This is correct
    # Whitespace here can improve readability.
    x = 10
    flag =(x == 10)and(x<12)
    print(flag)
      
    """ Readable form could be as follows
    x = 10
    flag = (x == 10) and (x < 12)
    print(flag)
    """
      
    # Try the more readable code yourself
     
     

    Whitespaces are necessary in separating the keywords from the variables or other keywords. Consider the following example.




    # Example
      
    x = [1, 2, 3]
    y = 2
      
    """ Following is incorrect, and will generate syntax error
    a = yin x
    """
      
    # Corrected version is written as
    a = y in x
    print(a)
     
     

    Whitespaces as Indentation
    Python’s syntax is quite easy, but still you have to take some care in writing the code. Indentation is used in writing python codes.
            Whitespaces before a statement have significant role and are used in indentation. Whitespace before a statement can have a different meaning. Let’s try an example.




    # Example
      
    print('foo') # Correct
      
       print('foo') # This will generate an error
      
    # The error would be somewhat 'unexpected indent'
     
     

    Leading whitespaces are used to determine the grouping of the statements like in loops or control structures etc.
    Example:




    # Example
      
    x = 10
      
    while(x != 0):  
     if(x > 5):   # Line 1
      print('x > 5')  # Line 2
     else:        # Line 3
      print('x < 5') # Line 4
     x -= 2       # Line 5
      
    """
    Lines 1, 3, 5 are on same level
    Line 2 will only be executed if if condition becomes true.
    Line 4 will only be executed if if condition becomes false.
    """
     
     
    Output:
      x > 5  x > 5  x > 5  x < 5  x < 5  


    Next Article
    Python Data Structures Practice Problems

    A

    AnasShamoon
    Improve
    Article Tags :
    • Python
    • Python Programs
    Practice Tags :
    • python

    Similar Reads

    • Python Programs
      Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples. The below Python section contains a wide collection of Python programming examples. These Python c
      11 min read
    • Output of Python Programs | Set 19 (Strings)
      1) What is the output of the following program? [GFGTABS] PYTHON3 str1 = '{2}, {1} and {0}'.format('a', 'b', 'c') str2 = '{0}{1}{0}'.format('abra', 'cad') print(str1, str2) [/GFGTABS]a) c, b and a abracad0 b) a, b and c abracadabra c) a, b and
      3 min read
    • Python Data Structures Practice Problems
      Python Data Structures Practice Problems page covers essential structures, from lists and dictionaries to advanced ones like sets, heaps, and deques. These exercises help build a strong foundation for managing data efficiently and solving real-world programming challenges. Data Structures OverviewLi
      1 min read
    • Output of Python programs | Set 7
      Prerequisite - Strings in Python Predict the output of the following Python programs. These question set will make you conversant with String Concepts in Python programming language. Program 1[GFGTABS] Python var1 = 'Hello Geeks!' var2 = "GeeksforGeeks" print "var1[0]: ",
      3 min read
    • Output of Python programs | Set 8
      Prerequisite - Lists in Python Predict the output of the following Python programs. Program 1 [GFGTABS] Python list = [1, 2, 3, None, (1, 2, 3, 4, 5), ['Geeks', 'for', 'Geeks']] print len(list) [/GFGTABS]Output: 6Explanation: The beauty of python list datatype is that within
      3 min read
    • Output of Python Program | Set 1
      Predict the output of following python programs: Program 1: [GFGTABS] Python r = lambda q: q * 2 s = lambda q: q * 3 x = 2 x = r(x) x = s(x) x = r(x) print (x) [/GFGTABS]Output: 24Explanation : In the above program r and s are lambda functions or anonymous functions and q is the argument to both of
      3 min read
    • Output of Python program | Set 5
      Predict the output of the following programs: Program 1: [GFGTABS] Python def gfgFunction(): &quot;Geeksforgeeks is cool website for boosting up technical skills&quot; return 1 print (gfgFunction.__doc__[17:21]) [/GFGTABS]Output: coolExplanation: There is a docstring defined for this method,
      3 min read
    • Python String Input Output
      In Python, input and output operations are fundamental for interacting with users and displaying results. The input() function is used to gather input from the user and the print() function is used to display output. Input operations in PythonPython’s input() function allows us to get data from the
      3 min read
    • Understanding the Execution of Python Program
      This article aims at providing a detailed insight into the execution of the Python program. Let's consider the below example. Example: C/C++ Code a = 10 b = 10 print("Sum ", (a+b)) Output: Sum 20 Suppose the above python program is saved as first.py. Here first is the name and .py is the e
      2 min read
    • Python List Creation Programs
      Python provides multiple ways to create lists based on different requirements, such as generating lists of numbers, creating nested lists, forming lists of tuples or dictionaries, and more. This article covers various ways to create lists efficiently, including: Generating lists of numbers, strings,
      2 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