Python Syntax And Token



Part 1: What is python syntax?

Syntax is the rule that define how the code is to be written and execution.

Part 1.1: Key Rules

  • Python is case-sensitive language that means name ≠ Name.
  • Python use Indentation (Spaces) instant of braces {} unlike other programming language to define Blocks.
  • Statements usually Ends with newline, No semicolon required unlike other language.
  • Because of those python code is easy to read, write and understand to the human.
    This feature will allow to easily modify the code according to need of the programmer.


    Part 2: What is Token in Python??

    A token in Python is the smallest individual unit of a program that has meaning to the Python interpreter. Tokens are the basic Building Block of code.They are Five types of the Tokens in Python programming language.

    Part 2.1: Keywords

    • Keywords are case-sensitive.
    • Keywords are reserved words that have predefine fixed meaning.
    • Keywords are reserved, that’s why we cannot use those words in name of variable, class, Function, or any other identifier.
    • There is no import requirement of any libraries. Their always available in python environment.

    They’re not formally divided into“Official Types,” but we can group them by how they’re used in the language.

    Group Name
    Types
    Control Flow Keywords if, elif, else, for, while, break, continue, pass
    Function & Class Definition Keywords def, class, return, yield, lambd
    Logical & Boolean Keywords and, or, not, True, False, None
    Import & Module Keywords import, from, as
    Membership & Identity Keyword in, not in,is, is not
    Variable Scope Keywords static, this, public, private, protected, var
    Loop & Exception Control Keywords break, continue, pass, finally
    Exception Handling Keywords try, except, finally, raise, assert
    Miscellaneous Keywords del,with,yield

    Part 2.2: Identifiers

    It is a name that define by programmer to identify the variable, class, function or any other objects. It is case-sensitive so, Variable or variable or variable there all are different identifiers.

    Part 2.2.1: They are some rule for identifiers

    • It is combination of Uppercase, lowercase, digits, and underscore.
       NAME   ✔️vaild
       name    ✔️vaild
       name1    ✔️vaild
       first_name  ✔️vaild
       _name    ✔️vaild
       _NamE1   ✔️vaild

    • It cannot be start with number or digit.
       1name  ❌ Invaild
       name1  ✔️vaild

    • It can be start with character or underscore.
       name    ✔️vaild
       _name   ✔️vaild
       1_name  ❌ Invaild

    • It cannot be use any reserved keyword.
       string  ❌ Invaild
       def   ❌ Invaild
       and   ❌ Invaild
       if    ❌ Invaild
       not    ❌ Invaild

    • It cannot use any special character.
       @Name  ❌ Invaild
       &First  ❌ Invaild
       First%  ❌ Invaild

    Part 2.2.2: Where to use Identifier in programming

    1. Variable Name
    2. Example :user_name = "Aman"
            total_score = 95
            is_logged_in = True

    3. Function Name
    4. when we create
          def greet():
          print("Hello, world!")

      When we call
          greet()

    5. Class Name
    6. When we create
           class StudentProfile:
           def __init__(self, name, age):
           self.name = name
           self.age = age

    7. Module Name
    8. When we create
          File Name math_utils.py

      When we call in pyhton:
           import math_utils
           result = math_utils.calculate_total(100, 18)

    Part 2.2.3: Valid v/s Invaild Identifier

    Valid
    Invalid
    name1name
    First_nameFirst-name
    Student1Student 1
    classNameclass


    Part 2.3: Literals

    A literal is a raw value assigned to a variable or used directly in an expression. Those values can not be change during the execution
    For Example :
      Statment A: X=10  Explantion :X is assign by 10
      Statment B: print(10)  Explantion :Here result print directly value 10
      Statment C: X=10
      print(X+2) Explantion :X is assign by 10 and addition by directly value 2.

    Part 2.3.1 Types of Literals

    1. Numeric literals
    2. Integers10, -5, 0, -10X = 10
      Floats3.14, -0.001X = 3.14
      Complex2 + 3jX = 2 + 3j

    3. String literals
    4. Single Quotes'hello'message = 'Hello World'
      Double quotes"world"name = "Alice"
      Triple quotes'''text''' or """text""""""This is
      a multi-line string"""

    5. Boolean literals
    6. Trueis_active = True
      Falseis_closed = False

    7. Collection literals
    8. List[1, 2, 3]numbers = [1, 2, 3, 4]
      Tuple(1, 2, 3)coordinates = (10, 20)
      Dictionary{"a": 1, "b": 2}person = {"name": "Aman", "age": 20}
    9. Special literal
    10.   None (represents absence of value)

    Part 2.4: Operators

    An operator is a symbol that performs an operation on values (operands).

    Types of operators in Python
    1. Arithmetic operators
      Addition +
      Subtraction -
      Multiplication *
      Division /
      Floor Division //
      Modulus %
      Exponentiation **

    2. Relational or Comparison Operators
      Equal To "=="
      Not equal To "!="
      Less Than "<"
      Greater than ">"
      Less than or Equal To "<="
      Greater than or Equal To ">="

    3. Logical Operators
      AND and
      OR or
      NOT not

    4. Assignment operators
      Assign the value =
      Addition and assign +=
      Subtraction and assign -=
      Multiplication and assign *=
      Division and assign /=
      Floor division and assign //=
      Modulus and assign %=
      Exponentiation and Assign **=

    Part 2.5: Delimiters

    • They don’t perform calculations like operators.
    • They define the boundaries of a statement.
    • They define the structure like starting and ending blocks.
    • They separate elements like item in list.
    • To make a code readable and organized delimiters are used.
    NameMeaningExample
    Parentheses ( ) Is used for grouping expressions, function calls(commonly used) Statement A : print("Hello")
    Statement B : x = (2 + 3) * 5
    Square Brackets [ ] Is used for lists and indexing(commonly used) Statement A : numbers = [1, 2, 3, 4]
    print(numbers[0])
    Curly Braces { } Is used for dictionaries and sets(commonly used) Statement A : student = {"name": "Rahul", "age": 20}
    Statement B : unique_numbers = {1, 2, 3}
    Comma , Is used to separate values(commonly used) Statement A : a, b, c = 1, 2, 3
    print(a, b, c)
    Colon : Is used to start a block of code(loops, functions, conditions)(commonly used) Statement A :
    if True:
      print("Hello")
    Dot . Is used to access methods or properties(commonly used) Statement A : name = "python"
    print(name.upper())
    Equal = Is used for assignment(commonly used) Statement A : x = 10
    Semicolon ; Is used to write multiple statements in one line(not commonly used) Statement A : a = 5; b = 10; print(a + b)
    At Symbol @ Is used for decorators (not commonly used) Statement A :
    def my_decorator(func):
      return func

    @my_decorator
    def greet():
      print("Hello")


    Part 3 : Quick Summary

  • We call keyword as a “vocabulary” of a python programming language.
  • Identifiers = names of variables, functions, classes, etc.
  • Identifier Cannot be Python keywords.
  • Identifier Should be meaningful and Readable.
  • Operator is a Symbols to perform operation
  • Delimiters define boundaries and structure of a program.