Skip to main content

Introduction to Python Syntax

Python Syntax​

Python has a straightforward and readable syntax that emphasizes code readability.

Here are some key elements of Python syntax:

Comments​

Comments are used to add explanatory notes within the code. They are not executed by the interpreter.

In Python, single-line comments start with the # symbol, and multiline comments are enclosed between triple quotes (''' or """).

# This is a single-line comment

'''
This is a multiline comment.
It can span multiple lines.
'''

Indentation​

Python uses indentation to define the structure and scope of code blocks.

It replaces traditional braces or brackets used in other programming languages.

Indentation is typically four spaces or a tab.

if x > 0:
print("x is positive") # This code block is indented
else:
print("x is non-positive") # This code block is indented the same way

Variables​

Variables are used to store values in Python. You can assign a value to a variable using the assignment operator (=).

x = 10  # Assigns the value 10 to the variable x
name = "John" # Assigns the string "John" to the variable name

Data Types​

Python has several built-in data types, including:

  • Numbers: Integers (int), floating-point numbers (float), and complex numbers (complex).

  • Strings: Ordered sequences of characters enclosed in single quotes (') or double quotes (").

  • Lists: Ordered and mutable collections of items enclosed in square brackets ([]).

  • Tuples: Ordered and immutable collections of items enclosed in parentheses (()).

  • Dictionaries: Unordered collections of key-value pairs enclosed in curly braces ({}).

  • Sets: Unordered collections of unique items enclosed in curly braces ({}).

# Examples of different data types
age = 25 # integer
pi = 3.14159 # float
name = "John" # string
fruits = ['apple', 'banana', 'orange'] # list
coordinates = (10, 20) # tuple
student = {'name': 'Alice', 'age': 20} # dictionary

Operators​

Python supports various operators for performing operations on variables and values.

These include arithmetic operators (+, -, *, /, %, **), comparison operators (<, >, ==, !=, <=, >=), logical operators (and, or, not), and more.

# Examples of operators
x = 5 + 3 # addition
y = 10 - 2 # subtraction
z = 2 * 4 # multiplication
w = 16 / 2 # division
remainder = 7 % 3 # modulo
power = 2 ** 3 # exponentiation

is_equal = x == y # equality comparison
is_greater = x > y # greater than comparison

is_true = True and False # logical AND
is_false = True or False # logical OR
is_not = not True # logical NOT

Conditional Statements​

Conditional statements allow you to perform different actions based on specific conditions.

Python uses the if, elif (optional), and else keywords for conditional branching.

# Example of a conditional statement
x = 10

if x > 0:
print("x is positive")
elif x == 0