L-01: Syntax, Variables & Comments

L-01: Syntax, Variables & Comments

Understanding the syntax, variables, comments and their types.

·

7 min read

Syntax

In Python, indentation is a critical aspect of the language's syntax. Unlike many other programming languages that use braces {} or other symbols to define code blocks, Python uses indentation to indicate the grouping and nesting of code. Indentation helps improve code readability and enforces a consistent coding style. Here are some key points about Python indentation:

  1. Indentation Level: Python code blocks are defined by the level of indentation. Typically, you use four spaces for each level of indentation. This is the most common convention, although some programmers use tabs or a different number of spaces. The key is to be consistent throughout your code.

    Example:

     if condition:
         # This block is indented by four spaces
         statement_1
         statement_2
     # Back to the previous level of indentation
    
  2. Whitespace: Python is sensitive to whitespace, so you should not mix tabs and spaces for indentation within the same block. Choose one and stick with it.

    Example:

     # Mixing tabs and spaces can lead to an error
     if condition:
         statement_1
     # The following line is indented with a tab
     statement_2
    
  3. Consistency: Consistency in indentation is crucial for Python code. If you start a block with a certain level of indentation, you must maintain that level throughout the block. Mixing different levels of indentation can lead to syntax errors.

    Example:

     if condition:
         statement_1
             # This inconsistent indentation will result in an error
             statement_2
    
  4. Nested Blocks: Indentation is used to indicate nested code blocks. When one block of code is contained within another, it should be indented further to the right.

    Example:

     if condition:
         statement_1
         if nested_condition:
             # This block is further indented
             statement_2
    
  5. Blank Lines: Blank lines with consistent indentation can be used to separate different parts of your code for improved readability.

    Example:

     def function1():
         statement_1
    
     def function2():
         statement_2
    
     # A blank line for separation
     result = function1()
    
     # Another blank line for separation
     result2 = function2()
    
  6. End of Block: Dedent (reduce indentation) to the previous level when you want to exit a code block or function.

    Example:

     if condition:
         statement_1
     # Dedent to exit the if block
     statement_after_if
    

By following these guidelines, you can ensure that your Python code is well-structured and readable, making it easier to debug and maintain. Proper indentation is not just a matter of style; it's a fundamental part of Python's syntax.

Variables

In Python, variables are used to store and manipulate data in your programs. A variable is like a container that holds a value, and you can give it a name to refer to that value later in your code. Variables in Python have the following characteristics:

  1. Dynamic Typing: Python is dynamically typed, which means you don't need to declare the data type of a variable explicitly. The interpreter infers the data type based on the value assigned to the variable.

  2. Variable Names: Variable names in Python must follow these rules:

    • Must start with a letter (a-z, A-Z) or an underscore (_).

    • Can contain letters, numbers (0-9), and underscores.

    • Variable names are case-sensitive (e.g., my_var and My_Var are different variables).

  3. Assignment: You can assign values to variables using the = operator.

x = 10    # Integer type
s = "Welcome to Python 101: A Beginner's Guide"        # String type
y = 3.14159265359        # Float type

Assigning multiple values to multiple variables (Shorthand syntax)

In Python, you can assign multiple values to multiple variables in a single line by separating the values with commas. The number of values should match the number of variables on the left side of the assignment. This is often referred to as "unpacking" or "multiple assignment." Here's how it works:

# Assign multiple values to multiple variables
var1, var2, var3 = value1, value2, value3

Here's an example:

x, y, z = 10, 20, 30

In this example, we have assigned the value 10 to the variable x, 20 to y, and 30 to z.

You can also use this technique to swap the values of two variables without needing a temporary variable:

a = 5
b = 10

# Swap the values of a and b
a, b = b, a

print("a =", a)  # Output: a = 10
print("b =", b)  # Output: b = 5

Python will automatically unpack the values from the right side of the assignment and assign them to the variables on the left side in order. This can be very useful for making code concise and readable.

Controlling precision of floating-point numbers

The round() function in Python is used to round floating-point numbers to a specified number of decimal places. It allows you to control the precision of floating-point numbers by specifying the number of decimal places to round to. Here's how to use the round() function:

rounded_number = round(number, decimal_places)
  • number: The floating-point number you want to round.

  • decimal_places: The number of decimal places to round the number to.

Here are some examples of using the round() function for different levels of precision:

x = 3.14159265359

# Round to 2 decimal places
rounded_x_2dp = round(x, 2)
print(rounded_x_2dp)  # Output: 3.14

# Round to 3 decimal places
rounded_x_3dp = round(x, 3)
print(rounded_x_3dp)  # Output: 3.142

# Round to the nearest integer
rounded_integer = round(x)
print(rounded_integer)  # Output: 3

In the first example, we round x to 2 decimal places, resulting in 3.14. In the second example, we round x to 3 decimal places, resulting in 3.142. In the last example, we round x to the nearest integer, resulting in 3.

Keep in mind that rounding can introduce some degree of approximation, especially when dealing with numbers that cannot be represented exactly in binary (e.g., numbers like 0.1).

If you require high precision and control over rounding, consider using the decimal module for more accurate decimal arithmetic.

from decimal import Decimal, getcontext

# Set the precision (number of decimal places)
getcontext().prec = 50  # Set precision to 50 decimal places

a = Decimal("0.1")
b = Decimal("0.2")
c = a + b

print(c)  # Output: 0.3 (with 50 decimal places of precision)

Determine the data type of a variable

In Python, you can determine the data type of a variable using the built-in type() function. The type() function returns the type of an object or variable. Here's how you can use it:

x = 42
print(type(x))  # Output: <class 'int'>

y = "Hello, Python!"
print(type(y))  # Output: <class 'str'>

z = [1, 2, 3]
print(type(z))  # Output: <class 'list'>

# You can also use it directly in expressions
if type(x) == int:
    print("x is an integer")

In this example, we create three variables (x, y, and z) with different data types and then use the type() function to determine their respective data types. The type() function returns a type object, which you can compare with the built-in Python types (e.g., int, str, list, etc.) to perform type checks or take specific actions based on the data type of a variable.

Comments and their types

Comments in Python are used to provide explanations, documentation, or notes within your code. They are essential for making your code more understandable and maintainable. Python supports two types of comments:

  1. Single-line Comments: Single-line comments are used for adding comments to a single line of code. In Python, single-line comments are created using the # character. Anything after # on a line is treated as a comment and is not executed by the Python interpreter.

     # This is a single-line comment
     x = 5  # This comment explains the purpose of the variable
    
  2. Multi-line Comments (Docstrings): Python does not have a specific syntax for multi-line comments as some other programming languages do. Instead, you typically use multi-line strings (triple-quoted strings) to create multi-line comments or docstrings. These are often used for function or module documentation.

     """
     This is a multi-line comment or docstring.
     It can span multiple lines and is used for documentation.
     """
    

    Docstrings are often placed at the beginning of a module, class, or function to provide information about their purpose, parameters, return values, and usage. They can be accessed using the .__doc__ attribute.

     def welcome():
         """
         Welcome to Python 101: A Beginner's Guide
         """
         pass
    
     print(welcome.__doc__)
    

Remember that while multi-line strings can be used for comments, they are also valid string literals and may be included in the documentation of your code.

In practice, single-line comments are more commonly used for explaining individual lines of code or adding short comments, while multi-line comments (docstrings) are used for documenting functions, classes, and modules to provide helpful information for developers who read and maintain the code.

Did you find this article valuable?

Support Anuj Das by becoming a sponsor. Any amount is appreciated!