IDENTFIERS

IDENTFIERS

In Python, identifiers are names given to entities like variables, functions, classes, modules, etc. Here are the rules and conventions for identifiers in Python:

  1. Rules for Identifiers:

  • Must start with a letter (a-z, A-Z) or underscore (_) character.
  • Can be followed by any number of letters, digits (0-9), or underscores (_).
  • Python identifiers are case-sensitive (myVar and myvar are different identifiers).

2. Valid Examples:

  • variable
  • _variable
  • my_variable
  • MY_VAR
  • variable23.


3. Invalid Examples:

  • 2variable (cannot start with a digit)
  • $variable (cannot use special characters like $)
  • my-variable (cannot use hyphens)

4. Python Keywords:

  • Keywords are reserved words that cannot be used as identifiers because they have special meanings in Python (e.g., if, for, while, class, def, etc.).

5. Convention for Identifiers:

  • Use descriptive names to enhance readability (total_score is more descriptive than ts).
  • Use lowercase words separated by underscores for variable and function names (snake_case).
  • Use CamelCase for class names (ClassName).

6. Special Identifiers:

  • Single underscore (_): Used as a temporary or insignificant variable (_, _var).
  • Double underscore (__): Causes name mangling when used in class context (__var).



=============================================================

RESERVED WORDS

In Python, reserved keywords are predefined words that have special meanings and purposes within the language. These keywords cannot be used as identifiers (names for variables, functions, classes, etc.) because they are reserved for specific syntactical and operational purposes. Here is a list of Python's reserved keywords as of the latest versions:

False await else import pass

None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while

assert del global not with

async elif if or yield

These keywords are case-sensitive, meaning False is different from false or FALSE

How Keywords are Used:

  • Control Flow: Keywords like if, else, elif, while, for, break, continue, return are used for control flow and loop constructs.
  • Defining Entities: Keywords like def, class, async, await are used for defining functions, classes, and asynchronous operations.
  • Exception Handling: Keywords try, except, finally, raise are used for handling exceptions and errors.
  • Logical Operations: Keywords and, or, not are used for boolean operations.
  • Miscellaneous: Keywords such as global, nonlocal, assert, pass, yield, lambda, import, from, and with have specific roles related to scope, assertions, iterators, and context management.

Importance of Keywords:

Understanding and respecting these keywords is crucial because attempting to use them as identifiers will result in syntax errors or unexpected behavior in your Python programs. They are fundamental to Python's syntax and provide essential building blocks for creating structured and efficient code.

Version Specifics:

The set of keywords can vary slightly depending on the Python version, although the core set tends to remain stable across most recent versions. Always refer to the official Python documentation or use Python's keyword module to get an updated and accurate list of keywords for your specific Python version.

============================================================

DATA TYPES

n Python, data types represent the type or category of data that variables or values can hold. Python is dynamically typed, meaning you don't need to explicitly declare the data type of a variable when you create it; the interpreter assigns it dynamically based on the value assigned.

Python contains following inbuilt data types.

1) INT

2) Float

3) Complex

4)Bool

5) Str

6) Bytes

7) Bytearray

8) Range

9) List

10) Tuple

11) Set

12) Frozenset

13) Dict

14) None

Note: Pyhton contains several inbuilt functions

1) Type() - To check the type of variable

2)ID() - To get address of object

3) Print()- To print the value

Overall I would say in python everything is object.

Numeric Types:

  • int: Integer values (e.g., 10, -3, 456).
  • float: Floating-point values, represent real numbers (e.g., 3.14, -0.001, 2.0).

Sequence Types:

  • str: String, a sequence of characters (e.g., "hello", 'Python', "123").
  • list: Ordered collection of items, mutable (e.g., [1, 2, 3], ['a', 'b', 'c']).
  • tuple: Ordered collection of items, immutable (e.g., (1, 2, 3), ('a', 'b', 'c')).

Mapping Type:

  • dict: Collection of key-value pairs (e.g., {'name': 'Alice', 'age': 30}).

Set Types:

  • set: Unordered collection of unique items (e.g., {1, 2, 3}, {'a', 'b', 'c'}).
  • frozenset: Immutable set (e.g., frozenset({1, 2, 3}))

Boolean Type:

  • bool: Represents truth values, either True or False.


None Type:

  • NoneType: Represents a lack of value or null value (e.g., None)

Slicing of Strings

n Python, slicing is a technique used to extract a subset of elements from a sequence like strings, lists, tuples, etc.

Syntax:

The syntax for slicing a string s is s[start:end:step]:

  • start: Optional index specifying where to start the slice (default is 0).
  • end: Optional index specifying where to end the slice (default is the end of the string).
  • step: Optional step size for slicing (default is 1).

Key Points:

  • Slicing returns a new string containing elements from the original string from start to end-1.
  • If start is not provided, slicing starts from the beginning of the string.
  • If end is not provided, slicing goes until the end of the string.
  • The step parameter allows skipping characters in the slice



Explanation of Examples:

Explanation of Examples:

  1. Basic Slicing:

s[0:5]: Starts from index 0 and ends at index 5-1=4, giving "Hello".

s[7:]: Starts from index 7 and goes till the end of the string, giving "World!".

s[:5]: Starts from the beginning and ends at index 5-1=4, giving "Hello".

s[:]: Copies the entire string.


Negative Indices:

s[-6:-1]: Starts 6 characters from the end and ends 1 character from the end, giving "World".

s[-6:]: Starts 6 characters from the end and goes till the end, giving "World!".


Step Size:

  • s[::2]: Steps through the string with a step size of 2, giving "Hlo ol!".


Reverse the String:

  • s[::-1]: Reverses the entire string, giving "!dlroW ,olleH".

Notes:

  • Slicing in Python is versatile and powerful, allowing you to manipulate strings and extract substrings efficiently.
  • The start, end, and step parameters can be adjusted to achieve various slicing operations based on your specific needs.
  • Understanding slicing is crucial for manipulating text and data efficiently in Python programming.

Type Conversion:

Python also supports type conversion (or casting) between different data types using functions like int(), float(), str(), list(), tuple(), dict(), set(), etc., allowing you to change the type of a variable or value as needed.

=============================================================


-

Sanjay Kumar Chandel

Co-founder & Chief Operating Officer at CYBERINFOMINES TECHNOLOGY PVT. LTD.

1 个月

Nice docs, It could be more better if we keep some real time use case to explain topic in better ways. Thank you ??

要查看或添加评论,请登录

Hemant D.的更多文章

  • Tableau Pulse :

    Tableau Pulse :

    Tableau Pulse is a feature introduced by Tableau as part of its broader focus on enhancing the data experience for…

  • Pyhton Notes Edition 6:

    Pyhton Notes Edition 6:

    Do you realize that how to generate a sequence number in python? There are several ways to generate a sequence number…

  • How to generate OTP in Python?

    How to generate OTP in Python?

    You can generate a One-Time Password (OTP) in Python using various methods. Here are a few common approaches: 1.

  • Python Notes Edition 3

    Python Notes Edition 3

    Freeware: =>If any software downloaded Freely and that Software comes under Freeware Examples: Python, Java-----…

    1 条评论
  • Python Version

    Python Version

    ==================================================== Python programming language contains 3 Types of version. They are…

  • Python news letter by Weekly

    Python news letter by Weekly

    Dive into the world of Python with our newsletter! Stay updated on the latest trends, tips, and tricks in the Python…

    1 条评论
  • Regulators:

    Regulators:

    I was thinking for a long time that I should write something on regulators in Banking terminology then the next…

  • Generative AI :

    Generative AI :

    The first question comes in mind what is AI (Artificial intelligence)?- AI refers to the stimulation of human…

  • HOW TO AVOID OVERPLOTTING

    HOW TO AVOID OVERPLOTTING

    Overplotting is a common issue in dataviz. When your dataset is large, the dots of your Scatterplot will tend to…

    3 条评论
  • ChatGpt-How to use it with Microsoft Power BI

    ChatGpt-How to use it with Microsoft Power BI

    Open AI has recently announced that it will support third party developers to integrate ChatGPT into their apps and…

    1 条评论

社区洞察

其他会员也浏览了