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 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 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")
else:
print("x is non-positive")
Variables
Variables are used to store values in Python. You can assign a value to a variable using the assignment operator (=
).
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 ({}).
age = 25
pi = 3.14159
name = "John"
fruits = ['apple', 'banana', 'orange']
coordinates = (10, 20)
student = {'name': 'Alice', 'age': 20}
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.
x = 5 + 3
y = 10 - 2
z = 2 * 4
w = 16 / 2
remainder = 7 % 3
power = 2 ** 3
is_equal = x == y
is_greater = x > y
is_true = True and False
is_false = True or False
is_not = not True
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.
x = 10
if x > 0:
print("x is positive")
elif x == 0