Python Syntax – Main Points

by | Apr 11, 2024 | Python | 0 comments


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, ageAge, and AGE are considered different variables.

2. Best Practices:

  • Descriptive: Choose names that clearly reflect the variable’s purpose. For example, customer_name is better than x.
  • Lowercase with underscores: The most common convention is to use lowercase letters separated by underscores (e.g., total_costis_admin).
  • Avoid reserved words: Don’t use words that have special meanings in Python (like iffordef). These are called keywords and cannot be used as variable names.

3. Examples:

  • Good: user_inputcalculation_resultin_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_keynum_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:

  1. Arithmetic Operators:
    • Addition: +
    • Subtraction: -
    • Multiplication: *
    • Division: /
    • Floor Division (integer division): //
    • Modulus (remainder): %
    • Exponentiation: **
  2. Comparison Operators:
    • Equal to: ==
    • Not equal to: !=
    • Greater than: >
    • Less than: <
    • Greater than or equal to: >=
    • Less than or equal to: <=
  3. 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: **=
  4. Logical Operators:
    • Logical AND: and
    • Logical OR: or
    • Logical NOT: not
  5. Identity Operators:
    • is: Returns True if both operands are the same object.
    • is not: Returns True if both operands are not the same object.
  6. Membership Operators:
    • in: Returns True if a value is present in a sequence (e.g., string, list, tuple).
    • not in: Returns True if a value is not present in a sequence.
  7. Bitwise Operators:
    • Bitwise AND: &
    • Bitwise OR: |
    • Bitwise XOR: ^
    • Bitwise NOT (Complement): ~
    • Left Shift: <<
    • Right Shift: >>
  8. Unary Operators:
    • Unary plus: +
    • Unary minus: -
  9. Ternary Operator:
    • x if condition else y: Returns x if the condition is True, otherwise y.

Here’s a comprehensive explanation of all common operators in Python with coding examples:

1. Arithmetic Operators:

  • Perform mathematical operations on numeric values.
OperatorDescriptionExample
+Additionx = 5 + 3 (Output: x = 8)
-Subtractiony = 10 - 2 (Output: y = 8)
*Multiplicationz = 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).
OperatorDescriptionExample
==Equal tox == 5 (Output: True if x is 5)
!=Not equal toy != 10 (Output: True if y is not 10)
>Greater thanz > 2 (Output: True if z is greater than 2)
<Less thana < 8 (Output: True if a is less than 8)
>=Greater than or equal tob >= 4 (Output: True if b is 4 or greater)
<=Less than or equal toc <= 9 (Output: True if c is 9 or less)

3. Assignment Operators:

  • Assign values to variables.
OperatorDescriptionExample
=Simple assignmentx = 10 (x now holds the value 10)
+=Add and assigny += 5 (y is incremented by 5)
-=Subtract and assignz -= 3 (z is decremented by 3)
*=Multiply and assigna *= 2 (a is multiplied by 2)
/=Divide and assign (results in a float)b /= 4 (b is divided by 4)
//=Floor division and assignc //= 7 (c is divided by 7 with whole number quotient assignment)
%=Modulo and assignd %= 3 (d is assigned the remainder after dividing by 3)
**=Exponentiation and assigne **= 2 (e is assigned e raised to the power of 2)

4. Logical Operators:

  • Combine conditional statements.
OperatorDescriptionExample
andReturns True if both conditions are Truex > 0 and y < 10 (True if both hold)
orReturns True if at least one condition is Truea == 5 or b != 3 (True if either holds)
notNegates a boolean valuenot (z <= 7) (True if z is greater than 7)

5. Membership Operators:

  • Check if a value is present in a sequence (list, tuple, string).
OperatorDescriptionExample
inChecks 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, and 3*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, and 6+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 the 5-3 happens first and then 1 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.

Written By HintsToday Team

undefined

Related Posts

Python Project Alert:- Dynamic list of variables Creation

Let us go through the Project requirement:- 1.Let us create One or Multiple dynamic lists of variables and save it in dictionary or Array or other datastructre for further repeating use in python. Variable names are in form of dynamic names for example Month_202401 to...

read more

Data Structures in Python: Linked Lists

Linked lists are a fundamental linear data structure where elements (nodes) are not stored contiguously in memory. Each node contains data and a reference (pointer) to the next node in the list, forming a chain-like structure. This dynamic allocation offers advantages...

read more

Python Dictionary in detail

What is Dictionary in Python? First of All it is not sequential like Lists. It is a non-sequential, unordered, redundant and mutable collection as key:value pairs. Keys are always unique but values need not be unique. You use the key to access the corresponding value....

read more

Python Strings Interview Questions

Python Programming Strings Interview Questions Write a Python program to remove a Specific character from string? Here's a Python program to remove a specific character from a string: def remove_char(text, char): """ Removes a specific character from a string. Args:...

read more

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *