Python syntax refers to the rules and conventions that dictate how Python code is written and structured. Here are some fundamental aspects of Python syntax:
Statements and Indentation:
Python uses indentation to define blocks of code, such as loops, conditionals, and function definitions. Indentation is typically four spaces, but consistency is more important than the actual number of spaces.
Statements are typically written one per line, but you can use a semicolon (;
) to write multiple statements on a single line.
Comments:
Comments start with the #
character and extend to the end of the line. They are used to document code and are ignored by the Python interpreter.
#symbol is used for comment in python. The keyboard should is largely ‘Ctrl + /’, however in idle uses #’Alt + 3′ to comment.
x = 10 # this is a commment
Variables and Data Types:
Variables are created by assigning a value to a name. Variable names can contain letters, numbers, and underscores but must start with a letter or underscore.
Python supports various data types, including integers, floats, strings, booleans, lists, tuples, dictionaries, and more.
It is possible to assign multiple variable to multiple values respectively in python.
x, y, z = 1, 2.3, "hello" print(x, y, z)
Another form of multiple assignment is
x = y = z = 1 Multiple assignment makes swapping variable values very easy in python.
x, y = 1, 2
x, y = y, x
Variable naming conventions in Python:
1. Rules:
- Start with a letter or underscore (_): Variable names must begin with a letter (a-z, A-Z) or an underscore. Numbers cannot be the first character.
- Alphanumeric and underscores: The rest of the variable name can contain letters, numbers, and underscores.
- Case-sensitive: Python is case-sensitive. So,
age
,Age
, andAGE
are considered different variables.
2. Best Practices:
- Descriptive: Choose names that clearly reflect the variable’s purpose. For example,
customer_name
is better thanx
. - Lowercase with underscores: The most common convention is to use lowercase letters separated by underscores (e.g.,
total_cost
,is_admin
). - Avoid reserved words: Don’t use words that have special meanings in Python (like
if
,for
,def
). These are called keywords and cannot be used as variable names.
3. Examples:
- Good:
user_input
,calculation_result
,in_stock
- Bad:
x
(unclear),userName
(mixed case),1stPlace
(starts with a number)
4. Additional Tips:
- Long names: For complex variable names, consider using abbreviations or prefixes (e.g.,
api_key
,num_items
). - Constants: If a variable’s value won’t change, use uppercase letters with underscores (e.g.,
PI = 3.14159
).
Comprehensive list of operators in Python:
- Arithmetic Operators:
- Addition:
+
- Subtraction:
-
- Multiplication:
*
- Division:
/
- Floor Division (integer division):
//
- Modulus (remainder):
%
- Exponentiation:
**
- Addition:
- Comparison Operators:
- Equal to:
==
- Not equal to:
!=
- Greater than:
>
- Less than:
<
- Greater than or equal to:
>=
- Less than or equal to:
<=
- Equal to:
- Assignment Operators:
- Assign value:
=
- Add and assign:
+=
- Subtract and assign:
-=
- Multiply and assign:
*=
- Divide and assign:
/=
- Floor divide and assign:
//=
- Modulus and assign:
%=
- Exponentiate and assign:
**=
- Assign value:
- Logical Operators:
- Logical AND:
and
- Logical OR:
or
- Logical NOT:
not
- Logical AND:
- Identity Operators:
is
: ReturnsTrue
if both operands are the same object.is not
: ReturnsTrue
if both operands are not the same object.
- Membership Operators:
in
: ReturnsTrue
if a value is present in a sequence (e.g., string, list, tuple).not in
: ReturnsTrue
if a value is not present in a sequence.
- Bitwise Operators:
- Bitwise AND:
&
- Bitwise OR:
|
- Bitwise XOR:
^
- Bitwise NOT (Complement):
~
- Left Shift:
<<
- Right Shift:
>>
- Bitwise AND:
- Unary Operators:
- Unary plus:
+
- Unary minus:
-
- Unary plus:
- Ternary Operator:
x if condition else y
: Returnsx
if the condition isTrue
, otherwisey
.
Here’s a comprehensive explanation of all common operators in Python with coding examples:
1. Arithmetic Operators:
- Perform mathematical operations on numeric values.
Operator | Description | Example |
---|---|---|
+ | Addition | x = 5 + 3 (Output: x = 8) |
- | Subtraction | y = 10 - 2 (Output: y = 8) |
* | Multiplication | z = 4 * 6 (Output: z = 24) |
/ | Division (results in a float) | a = 12 / 3 (Output: a = 4.0) |
// | Floor division (whole number quotient) | b = 11 // 3 (Output: b = 3) |
% | Modulo (remainder after division) | c = 15 % 4 (Output: c = 3) |
** | Exponentiation (x raised to the power of y) | d = 2 ** 3 (Output: d = 8) |
2. Comparison Operators:
- Evaluate conditions and return boolean values (True or False).
Operator | Description | Example |
---|---|---|
== | Equal to | x == 5 (Output: True if x is 5) |
!= | Not equal to | y != 10 (Output: True if y is not 10) |
> | Greater than | z > 2 (Output: True if z is greater than 2) |
< | Less than | a < 8 (Output: True if a is less than 8) |
>= | Greater than or equal to | b >= 4 (Output: True if b is 4 or greater) |
<= | Less than or equal to | c <= 9 (Output: True if c is 9 or less) |
3. Assignment Operators:
- Assign values to variables.
Operator | Description | Example |
---|---|---|
= | Simple assignment | x = 10 (x now holds the value 10) |
+= | Add and assign | y += 5 (y is incremented by 5) |
-= | Subtract and assign | z -= 3 (z is decremented by 3) |
*= | Multiply and assign | a *= 2 (a is multiplied by 2) |
/= | Divide and assign (results in a float) | b /= 4 (b is divided by 4) |
//= | Floor division and assign | c //= 7 (c is divided by 7 with whole number quotient assignment) |
%= | Modulo and assign | d %= 3 (d is assigned the remainder after dividing by 3) |
**= | Exponentiation and assign | e **= 2 (e is assigned e raised to the power of 2) |
4. Logical Operators:
- Combine conditional statements.
Operator | Description | Example |
---|---|---|
and | Returns True if both conditions are True | x > 0 and y < 10 (True if both hold) |
or | Returns True if at least one condition is True | a == 5 or b != 3 (True if either holds) |
not | Negates a boolean value | not (z <= 7) (True if z is greater than 7) |
5. Membership Operators:
- Check if a value is present in a sequence (list, tuple, string).
Operator | Description | Example |
---|---|---|
in | Checks if a |
Order of operations
When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the rules:
- Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first,
2 * (3-1)
is 4, and(1+1)**(5-2)
is 8. You can also use parentheses to make an expression easier to read, as in(minute * 100) / 60
, even if it doesn’t change the result. - Exponentiation has the next highest precedence, so
2**1+1
is 3, not 4, and3*1**3
is 3, not 27. - Multiplication and Division have the same precedence, which is higher than Addition and Subtraction, which also have the same precedence. So
2*3-1
is 5, not 4, and6+4/2
is 8, not 5. - Operators with the same precedence are evaluated from left to right. So the expression
5-3-1
is 1, not 3, because the5-3
happens first and then1
is subtracted from 2.
When in doubt, always put parentheses in your expressions to make sure the computations are performed in the order you intend.
Below is a comprehensive Python program that demonstrates the use of various operators including arithmetic, comparison, logical, bitwise, assignment, membership, and identity operators. This example aims to cover each type of operator in a meaningful context to illustrate their usage.
# Arithmetic Operators
a = 10
b = 5
addition = a + b # Addition
subtraction = a - b # Subtraction
multiplication = a * b # Multiplication
division = a / b # Division
floor_division = a // b # Floor Division
modulus = a % b # Modulus
exponentiation = a ** b # Exponentiation
print("Arithmetic Operators:")
print(f"Addition: {addition}")
print(f"Subtraction: {subtraction}")
print(f"Multiplication: {multiplication}")
print(f"Division: {division}")
print(f"Floor Division: {floor_division}")
print(f"Modulus: {modulus}")
print(f"Exponentiation: {exponentiation}")
# Comparison Operators
equal_to = (a == b) # Equal to
not_equal_to = (a != b) # Not equal to
greater_than = (a > b) # Greater than
less_than = (a < b) # Less than
greater_than_or_equal_to = (a >= b) # Greater than or equal to
less_than_or_equal_to = (a <= b) # Less than or equal to
print("nComparison Operators:")
print(f"Equal to: {equal_to}")
print(f"Not equal to: {not_equal_to}")
print(f"Greater than: {greater_than}")
print(f"Less than: {less_than}")
print(f"Greater than or equal to: {greater_than_or_equal_to}")
print(f"Less than or equal to: {less_than_or_equal_to}")
# Logical Operators
logical_and = (a > 0 and b > 0) # Logical AND
logical_or = (a > 0 or b < 0) # Logical OR
logical_not = not(a > 0) # Logical NOT
print("nLogical Operators:")
print(f"Logical AND: {logical_and}")
print(f"Logical OR: {logical_or}")
print(f"Logical NOT: {logical_not}")
# Bitwise Operators
bitwise_and = a & b # AND
bitwise_or = a | b # OR
bitwise_xor = a ^ b # XOR
bitwise_not = ~a # NOT
left_shift = a << 1 # Left Shift
right_shift = a >> 1 # Right Shift
print("nBitwise Operators:")
print(f"Bitwise AND: {bitwise_and}")
print(f"Bitwise OR: {bitwise_or}")
print(f"Bitwise XOR: {bitwise_xor}")
print(f"Bitwise NOT: {bitwise_not}")
print(f"Left Shift: {left_shift}")
print(f"Right Shift: {right_shift}")
# Assignment Operators
c = 10
c += 5 # Add and assign
c -= 3 # Subtract and assign
c *= 2 # Multiply and assign
c /= 4 # Divide and assign
c //= 2 # Floor divide and assign
c %= 3 # Modulus and assign
c **= 2 # Exponent and assign
c &= 1 # Bitwise AND and assign
c |= 2 # Bitwise OR and assign
c ^= 3 # Bitwise XOR and assign
c <<= 1 # Left shift and assign
c >>= 1 # Right shift and assign
print("nAssignment Operators:")
print(f"Final value of c: {c}")
# Membership Operators
fruits = ["apple", "banana", "cherry"]
in_list = "banana" in fruits # In
not_in_list = "grape" not in fruits # Not in
print("nMembership Operators:")
print(f"'banana' in fruits: {in_list}")
print(f"'grape' not in fruits: {not_in_list}")
# Identity Operators
x = [1, 2, 3]
y = x
z = x[:]
is_same = (x is y) # Is
is_not_same = (x is not z) # Is not
print("nIdentity Operators:")
print(f"x is y: {is_same}")
print(f"x is not z: {is_not_same}")
# Putting it all together in a simple example
print("nPutting it all together:")
# Arithmetic operation
result = (a + b) * 2
# Comparison
if result >= 30:
print("Result is greater than or equal to 30")
# Logical operation
if result > 0 and result % 2 == 0:
print("Result is a positive even number")
# Bitwise operation
bitwise_result = result & 1 # Checking if result is odd
# Membership operation
numbers = [result, bitwise_result, a, b]
if 10 in numbers:
print("10 is in the numbers list")
# Identity operation
if numbers is not x:
print("numbers list is not the same object as x list")
This program covers various Python operators and demonstrates how they can be used individually and combined in a more complex example. Each section is labeled to show which type of operator is being used and how it operates on the given data.
Leave a Reply