Структурирование программ Python

Опубликовано: 4 Февраля, 2022

В этой статье вы узнаете о правильном структурировании и форматировании ваших программ на Python.

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]

Несколько операторов в строке. Мы также можем писать несколько операторов в строке, но это не очень хорошая практика, поскольку это снижает читаемость кода. Старайтесь не писать несколько операторов в одной строке. Но, тем не менее, вы можете написать несколько строк, завершив один оператор с помощью ';'. ';' в этом случае используется как терминатор одного оператора.
Например, рассмотрим следующий код.

Продолжение строки, чтобы избежать прокрутки влево и вправо
Некоторые утверждения могут быть очень длинными и заставлять вас часто прокручивать экран влево и вправо. Вы можете подогнать свой код таким образом, чтобы вам не приходилось прокручивать здесь и там. Python позволяет вам писать один оператор в несколько строк, также известный как продолжение строки. Продолжение строки также улучшает читаемость.

 # Плохая практика, так как ширина этого кода слишком велика.
 
#код
х = 10
у = 20
г = 30
no_of_teachers = х
no_of_male_students = y
no_of_female_students = z
 
если (no_of_teachers == 10 и no_of_female_students == 30 и no_of_male_students == 20 и (x + y) == 30):
    print ('Курс действителен')
 
# Это можно было бы сделать вместо этого:
 
если (no_of_teachers == 10 и no_of_female_students == 30
    и no_of_male_students == 20 и x + y == 30):
    print ('Курс действителен')

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:

    CharacterASCII CodeLiteral Expression
    Space32 (0x20)‘ ‘
    tab9 (0x9)‘ ’
    newline10 (0xA)‘ ’

    * 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
    

     Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

    To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course