Python Syntax
Python is a high-level programming language known for its simplicity and readability. Here are some fundamental aspects of Python syntax:
Statements and Indentation:
- Python uses indentation to define blocks of code instead of brackets or braces like other programming languages. It is recommended to use 4 spaces for indentation.
- Statements in Python are typically written on separate lines.
Example:
1 2 |
if x > 7: print("x is greater than 7") |
Comments:
- Comments are used to add explanatory notes to code and are ignored by the Python interpreter.
- Single-line comments start with the
#
symbol, while multi-line comments are enclosed between triple quotes ('''
or"""
).
Example:
1 2 3 4 5 |
# This is a single-line comment ''' This is a multi-line comment ''' |
Variables and Data Types:
- Variables are used to store values. In Python, you can assign a value to a variable using the
=
operator. - Python is dynamically typed, meaning you don’t need to declare the data type explicitly. It is inferred based on the assigned value.
- Common data types in Python include integers (
int
), floating-point numbers (float
), strings (str
), booleans (bool
), and more.
Example:
1 2 3 |
x = 10 name = "John" is_valid = True |
Operators:
- Python supports various operators, such as arithmetic operators (
+
,-
,*
,/
,%
,**
), comparison operators (==
,!=
,>
,<
,>=
,<=
), logical operators (and
,or
,not
), assignment operators (=
,+=
,-=
,*=
,/=
,%=
), and more.
Example:
1 2 |
x = 10 + 5 y = (x > 5) and (x < 20) |
Conditional Statements:
- Python has
if
,elif
, andelse
statements for conditional execution. - Indentation is crucial to define the block of code executed under each condition.
Example:
1 2 3 4 5 6 |
if x > 10: print("x is greater than 10") elif x == 10: print("x is equal to 10") else: print("x is less than 10") |
Loops:
- Python provides
for
andwhile
loops for iterative execution. - Again, indentation is essential to define the block of code inside the loop.
Example:
1 2 3 4 5 |
for i in range(5): print(i) while x < 10: print(x) x += 1 |
These are just some of the basic syntax elements of Python. Python offers a vast set of libraries and advanced features to accomplish various programming tasks.