Understanding Basic Syntax in Python

Python is a widely-used programming language known for its simplicity and readability. In this article, we’ll explore the basic syntax of Python, common practices, and a few things to watch out for.

 

Basic Syntax Elements in Python

The following aspects make up the fundamental syntax of Python, making it accessible and powerful. This intuitive design is part of what has made Python one of the most popular programming languages today.

Indentation
In Python, indentation is used to define blocks of code. Unlike other programming languages that use braces {}, Python relies on consistent spacing (typically 4 spaces or a tab) to indicate a block of code. It’s crucial for the code’s structure and readability. For example, in a loop:

for i in range(5): 
    print(i) # This line is indented, so it is part of the loop

 

Comments
Comments in Python start with a # symbol. Anything after # on a given line is ignored by Python. This allows developers to add notes or explain complex code. For example:

# This is a comment explaining the code below
print("Hello, World!") # This prints a greeting

 

Statements
Statements are instructions that Python executes. The code is executed sequentially, from top to bottom. Here’s an example of sequential execution:

x = 5 # First statement
y = 10 # Second statement
z = x + y # Third statement
print(z) # Fourth statement, prints 15

 

Importing Modules
Python has an extensive collection of libraries and modules. To use them, you utilize the import statement. Here is an example for importing a math library:

import math # Imports the math library
result = math.sqrt(16) # Uses the sqrt function from the math library

 

End of Line as Termination
Unlike some other languages that require semicolons to end a statement, Python uses the end of a line to denote the end of a statement:

x = 5
y = 10
print(x + y) # Prints 15, and no semicolons are needed

 

Start Writing Python Scripts

Let’s discuss each of the following steps and provide examples to get started with writing Python scripts.

Use Comments to Plan Your Program
Before diving into the code, plan your program by jotting down comments. This aids in organization and helps anyone who reads the code.

  • Single-line Comments
    Use # to write a single-line comment. Example:

    # This is a single-line comment explaining the code

     

  • Multi-line Comments
    Though Python doesn’t have specific syntax for multi-line comments, you can use triple quotes. Example:

    '''
    This is a multi-line comment
    that spans several lines
    '''

Use the Built-in Print Function
Printing messages is essential for debugging and interaction.

  • Printing Simple Messages:
    print("Hello, World!")
  • Printing Multiple Items:
    print("Hello, World!")

Write Basic Arithmetic Operations
Performing basic arithmetic is a common task in Python.

  • Addition
    sum_result = 5 + 3
  • Subtraction
    difference = 5 - 3
  • Multiplication
    product = 5 * 3

  • Division
    quotient = 8 / 2
  • Modulus (often denoted by the % symbol, gives the remainder of a division operation)
    remainder = 7 % 3

Write Basic String Operations
Manipulating strings is essential for data processing and manipulation.

  • Concatenation
    greeting = "Hello, " + "World!"
  • Multiplication
    repeated_string = "Hi" * 3

Control the Format with F-strings
F-strings are a modern way to format strings in Python.

  • Basic Formatting
    name = "Alice"
    greeting = f"Hello, {name}!"
  • Expressions within F-strings. Since you can include any expression, you can make computations, call methods, or access attributes directly within the f-string.
    age = 30
    message = f"She is {age + 5} years old in five years."
  • Precision and Formatting
    price = 19.99
    formatted_price = f"Price: ${price:.2f}"

Use the Built-in Input Function
Collecting user input allows interactive programs

  • Non-Numeric
    user_name = input("Enter your name: ")
  • Numeric
    If you need to input a numeric value (integer or floating-point number), you’ll need to convert the input string to a numeric data type after reading it using the input() function.

    n = int(input("How many dogs?"))
    F = float(input("How much does a puppy cost?"))
Tips When Writing Python Scripts

Strings Can Be Defined Using Single, Double, or Triple Quotes
Depending on the situation, you can use different quotes.

single_quotes = 'This is a single-quoted string.'
double_quotes = "This is a double-quoted string."
triple_quotes = """This is a triple-quoted string."""


Keep Line Length Manageable

Follow the PEP 8 style guide, limiting line length to 79 characters for code and 72 for comments.

Use Parentheses for Clarity in Complex Expressions
Make expressions clearer by using parentheses. Example:

result = (a + b) * (c - d)


Import Modules Using Clear and Conventional Names

When importing, use conventional names. Example:

import numpy as np
Gotchas When Writing Python Scripts

Error: Using Any Other Symbol Than ‘#’ to Start a Comment
SyntaxError: invalid syntax. Using symbols like // will cause an error. Example:

// This will cause a SyntaxError in Python


Error: Forgetting the Parentheses in Python 3.x

SyntaxError: Missing parentheses in call to ‘print’. Did you mean print(“Hello, World!”)? The print statement requires parentheses. Fix:

print("Hello, World!") # Correct



Error: Trying to Concatenate a String with a Non-String Type Without Conversion
TypeError: can only concatenate str (not “int“) to str. Python does not automatically typecast integer (or other data types) to string when concatenating. Avoid this TypeError by converting types. Fix:

age = 30
message = "Age: " + str(age) # Correct


Error: Trying to Perform Arithmetic Operations on the Raw Input Without Conversion
TypeError: can’t multiply sequence by non-int of type ‘float’. The input() function returns a string, so convert before arithmetic. Fix:

user_input = input("Enter a number: ")
result = float(user_input) * 2 # Convert to float before multiplying



Related Tags: