Complete Python Masterclass | Zero To Hero

Complete Python Masterclass | Zero To Hero 


Python learn daily my practice


https://learning.ccbp.in/

https://www.geeksforgeeks.org/getting-started-with-python-programming/?ref=lbp

for video link

https://www.youtube.com/watch?v=OLPbd-7Pp_8&list=PLqM7alHXFySHLJWu_Euw7pdI4ec1hHTLI


online paint app

https://kleki.com/


https://www.udemy.com/course/comprehensive-python-programming-bootcamp-masterclass/learn/lecture/26321672#overview

30/09/2024

-----------------------------------------------------------------------------------------------------------------------------

install 

1) Anaconda 

2) Jupyter Note book 



In begining Start server for Jupyter Note book

how to open anaconda navigator in mac terminal jupyter notebook server on how to do open 


method -1:

Go to Your Apps menu  select and open "Anaconda " app

now terminal open automatically server on .

auto matically  a new web page open local host server begining now




method -2:

step 1-> press short cut

-> command + space bar press

search in "terminal ", Hit Enter Button.

To activate and use the Conda environment located at /Users/mac/Documents/vs code projects/myenv and start a Jupyter Notebook server, follow these steps:

1. Activate Your Conda Environment

  1. Open Terminal:

    • Press Command + Space, type Terminal, and press Enter.
  2. Activate the Environment:

    • Use the following command to activate the environment located in your specific path:


step 1-> press short cut

-> command + space bar press

search in terminal text 

open terminal 

copy paste the below path in the terminal 

--------------------------------------------------------------------------------------------

"

conda activate /Users/mac/Documents/vs\ code\ projects/myenv

"

--------------------------------------------------------------------------------------------

Hit Enter button

step 2-> copy paste the below path in the terminal 

--------------------------------------------------------------------------------------------

"jupyter notebook"

--------------------------------------------------------------------------------------------

hit -> Enter 

Now new web page opening on chrome browser 
jupyter note book local host 8888
--------------------------------------------------------------------------------------------
http://localhost:8888/tree?
--------------------------------------------------------------------------------------------

2. Start Jupyter Notebook Server

Once the environment is activated, you can start the Jupyter Notebook server:

  1. Run Jupyter Notebook:
    • After activating the environment, start the Jupyter Notebook server by typing:

--------------------------------------------------------------------------------------------

"jupyter notebook"

--------------------------------------------------------------------------------------------
This will open a browser window with the Jupyter interface. If it doesn't open automatically, copy the URL shown in the terminal and paste it into your browser.



To stop the server 

step 1 - >open terminal 

step 2 ->press  Ctrl + c in terminal

showing text like this in terminal 

Shut down this Jupyter server (y/[n])? 


select "y" -> hit "Enter"


Shutdown confirmed


Shutting down 10 extensions


To open Anaconda Navigator and launch a Jupyter Notebook server on your Mac using the terminal, follow these steps:

1. Open Anaconda Navigator

  1. Open Terminal:

    • Press Command + Space, type Terminal, and hit Enter to open the terminal.



  1. Launch Anaconda Navigator:

    • In the terminal, type the following command and hit Enter:

"anaconda-navigator"

paste this text in terminal

    • This will open the graphical interface for Anaconda Navigator.

2. Launch Jupyter Notebook Server from the Terminal

  1. Activate the Anaconda environment (optional):

    • If you want to use a specific environment, first activate it. Replace myenv with your environment name: 
    • conda activate myenv "
  2.  paste this text in terminal


Start Jupyter Notebook:

  • To start Jupyter Notebook directly from the terminal without using Anaconda Navigator, type the following command and hit Enter:
"jupyter notebook"
  1.  paste this text in terminal
    • This will launch the Jupyter Notebook server, and a new browser window will open with the Jupyter interface.

    If the browser doesn’t open automatically, copy the link provided in the terminal and paste it into your browser.

3. Access Jupyter Notebooks

  • Once the Jupyter server is running, you can create new notebooks, open existing ones, and start coding in Python.

1

2








3






















variables






variables

Table of Content


print("Hello World! I Don't Give a Bug")


# sample comment 
# This is Python Comment
name = "geeksforgeeks"
print(name) 

#print function

print("Hello World")

o/p:Hello World



పైథాన్‌లోని కీవర్డ్‌లు రిజర్వ్ చేయబడిన పదాలు, వీటిని వేరియబుల్ పేరు, ఫంక్షన్ పేరు లేదా ఏదైనా ఇతర ఐడెంటిఫైయర్‌గా ఉపయోగించలేరు.


Python Variable

https://www.youtube.com/watch?v=LKFrQXaoSMQ

  • A Python variable name must start with a letter or the underscore character.
  • A Python variable name cannot start with a number.
  • A Python variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
  • Variable in Python names are case-sensitive (name, Name, and NAME are three different variables).
  • The reserved words(keywords) in Python cannot be used to name the variable in Python.
Variable 

To Assign the value to a variable

"="--> this symbol called as "Assignment"
x=20 
Variable name = Value of variable 

print(x)
o/p =20

Memory location of address

address of x
--------------------
x=20
print(x)
id(x)

o/p = 20


address of x
--------------------
y = "Hello World"
print(y
)
id(y)

o/p = Hello World
Rules of Variable in python
Rules of Variable
variable is case-sensitive
ChatGPT1.

1. Variable Naming Rules (Syntax)

These rules are enforced by Python and must be followed:

  • Must begin with a letter or an underscore (_):

    • Valid examples: my_var, _variable, name, a1
    • Invalid: 1var, -myvar
  • Subsequent characters can be letters, digits, or underscores:

    • Valid examples: var1, my_var2, a_b_c3
    • Invalid: my-var, my var
  • Cannot use Python keywords as variable names:

    • Example of keywords: if, else, while, for, True, False, None, etc.
    • Invalid: if = 5 (since if is a reserved keyword in Python)
  • Case-sensitive:

    • Variables like myVar, MyVar, and myvar are all treated as different variables.

2. Best Practices (PEP 8 Guidelines)

  • Use descriptive names:

    • Variable names should be meaningful and describe the purpose of the variable.
    • Example: Use total_price instead of tp.
  • Use snake_case for variable names:

    • Variables should be written in all lowercase, with words separated by underscores (_).
    • Example: my_variable_name
  • Avoid single-letter variable names, except for small loop counters or simple usages:

    • Example: i, j, x (commonly used in loops), but avoid using names like a, b without context.
  • Constants:

    • For variables that are meant to remain unchanged, use all uppercase letters and separate words with underscores.
    • Example: PI = 3.14159, MAX_SIZE = 100
  • Avoid using variable names starting with double underscores (__), as these are reserved for special methods and name mangling.

    • Example: __init__, __str__
  • Don’t overwrite built-in names:

    • Avoid naming your variables with names that match Python built-ins like list, str, dict, int.
    • Invalid: list = [1, 2, 3] (this overwrites the built-in list() function)

Rules of Variable

a = 2
b = 5
c = a + b
print (c)
o/p:7



_var = 89
var =  100
var38238gu=67.9

a-zA-Z = 200

Avar = 250
AvaR = 300

Var = 350
VAR = 400

myVar = 
my_var =

3var = 450-----_> invalid (cannot  assign to operator)
var_2 = 500
var - 2 = 550 --> invalid (cannot  assign to operator)

"-" this like minus symble 

Avar = 20
Avar - 5 
o/p = 20 - 5 = 15


my var = 600. ---> invalid
var 4 = 610 ---> invalid  (its not allowed inavlid syntax error)

var_4 = 620
print(var_4)
o/p =620



sagar=10
print(sagar)
o/p:10

_sagar = 11
print(_sagar)
o/p: 11

11 sagar=12
print(11 sagar)

o/p:

Cell In[17], line 1
    11 sagar=12
       ^
SyntaxError: invalid syntax


11sagar = 13
print(11sagar)

o/p:

 Cell In[19], line 1
    11sagar = 13
     ^
SyntaxError: invalid decimal literal


Sagar =14
print(Sagar)
o/p:14

SAGAR = 15
print(SAGAR)

O/P: 15


16 = "SAGAR"
print(16)

o/p:  

 Cell In[27], line 1
    16 = "SAGAR"
    ^
SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?

-------------------------------------------------------------------------------------------------
Variables in Python 
Variables need not be declared first in python. They can be used directly. Variables in python are case-sensitive as most of the other programming languages.

MORE EXAMPLES

total_price = 1
my_variable_name = 2
i = 3
i
PI = 4
MAX_SIZE = 5

__init__
#starting of variable double underscore is invalid o/p showing

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[17], line 1
----> 1 __init__

NameError: name '__init__' is not defined


---------------------------------------------------------------------------
sagar__ = 6

__SAGAR = 7

__Sagar = 8
__sagar__ = 9
__init__  = 10
__str__ = 11

# Avoid naming your variables with names that match Python built-ins like

list = 12
str = 13
disct = 14

#Rules of Variables
sagar = 15

Sagar = 16
SagaR = 17
SAGAR = 18
sAgAr = 19


vidya sagar = 20 #space between the variable is invalid 0/p

  Cell In[43], line 1
    vidya sagar = 20
          ^
SyntaxError: invalid syntax

---------------------------------------------------------------------------

vidyasagar = 21

vidya_sagar = 22

#minus is a assignmet operatos so it is not valid it is invalid for inbetween the variable.

vidya-sagar = 23 
Cell In[49], line 1
    vidya-sagar = 23
    ^
SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?

-------------------------------------------------
5vidyasagar = 24 #variable front number not valid showing error

Cell In[51], line 1
    5vidyasagar = 24
    ^
SyntaxError: invalid decimal literal

-------------------------------------------------
vidyasagar5 = 25
vidya6sagar = 26
vidya_7_sagar = 27

-------------------------------------------------


7 vidya_sagar = 28 #space not valid

 Cell In[59], line 1
    7 vidya_sagar = 28
      ^
SyntaxError: invalid syntax




-------------------------------------------------

vidyasagar 8 = 29

 Cell In[5], line 1
    vidyasagar 8 = 29
               ^
SyntaxError: invalid syntax

-------------------------------------------------
VidyasagaR 9 = 30

Cell In[7], line 1
    VidyasagaR 9 = 30
               ^
SyntaxError: invalid syntax

-------------------------------------------------

VIDYASAGAR 11 = 31

 Cell In[9], line 1
    VIDYASAGAR 11 = 31
               ^
SyntaxError: invalid syntax

-------------------------------------------------







-------------------------------------------------



-------------------------------------------------





-------------------------------------------------



-----------------------------------------------




----------

Data Types

https://www.youtube.com/watch?v=yUrYouDQZL8

Python supports various data types, including integers, floats, strings, lists, tuples, dictionaries, and more.


#PYTHON DATA TYPES

# Numeric

# Sequence Type

# Boolean

# Set

# Dictionary



# Numeric

  # Integers

  # Float 

  # Complex Numbers



# Sequence Type

  # String

  # List

  # Tuple



# Boolean

  # True

  # False

  # T or F



# Set

  # set() #function


  # In Python, Set is an "unordered collection of data types" that is iterable, mutable, and has no duplicate elements. 

  # The order of elements in a set is undefined though it may consist of various elements.

  # Creating Sets

  # Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the sequence inside curly braces, separated by a ‘comma’. 

  # The type of elements in a set need not be the same, various mixed-up data type values can also be passed to the set. 




# Dictionary

  # Dictionary in Python is an "unordered collection of data values",

  # used to store data values like a map, which unlike other Data Types that hold only single value as an element,

  # Dictionary holds key:value pair. Key-value is provided in the dictionary

  # to make it more optimized. Each key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’.


  # Creating Dictionary

  # In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces, separated by ‘comma’.

  # Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable. 

  # Dictionary can also be created by the built-in function dict(). 

  # An empty dictionary can be created by just placing it to curly braces{}.

  # Note - Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly. 






  • Integers: Whole numbers without decimals.
  • Floats: Numbers with decimals.
  • Strings: Text enclosed in single or double quotes.
  • Lists: Ordered collections of items.
  • Tuples: Immutable collections of items.
  • Dictionaries: Key-value pairs.


What is Python Data Types?


To define the values ​​of various data types of Python and check their data types we use the type() function Consider the following examples.

This code assigns variable ‘x’ different values of various Python data types. It covers 

string 

integer 

float 

complex 

list 

tuple 

range 

dictionary 

set 

frozenset 

boolean 

bytes 

bytearray 

memoryview 

and the special value ‘None’ successively. 

Each assignment replaces the previous value, making ‘x’ take on the data type and value of the most recent assignment.


x = "Hello World"

x = 50

x = 60.5

x = 3j

x = ["geeks", "for", "geeks"]

x = ("geeks", "for", "geeks")

x = range(10)

x = {"name": "Suraj", "age": 24}

x = {"geeks", "for", "geeks"}

x = frozenset({"geeks", "for", "geeks"})

x = True

x = b"Geeks"

x = bytearray(4)

x = memoryview(bytes(6))

x = None

1. Numeric Data Types in Python

2. Sequence Data Types in Python

Accessing elements of String

List Data Type

Python Access List Items

Tuple Data Type

Access Tuple Items


3. Boolean Data Type in Python

4. Set Data Type in Python

Create a Set in Python

Access Set Items

5. Dictionary Data Type in Python

Create a Dictionary in Python

Accessing Key-value in Dictionary

Python Data Type Exercise Questions


https://www.geeksforgeeks.org/python-data-types/
-----------------------------------------------------------------------------------------------------------

Indentation

Python uses indentation to define blocks of code, such as loops and functions. Use four spaces for indentation. Incorrect indentation can lead to syntax errors.

if x > 10:
print("x is greater than 10")
else:
print("x is less than or equal to 10")


----------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------


Python Operators

In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators.

OPERATORS: These are the special symbols. Eg- + , * , /, etc.

OPERAND: It is the value on which the operator is applied.

Operators



Python supports various operators, including arithmetic, comparison, logical, and assignment operators.

11/10/24

  • 1) Arithmetic operators+-*/%** (exponentiation), // (floor division).
  • 5) Comparison operators==!=<><=>=.
  • 4) Logical operatorsandornot.
  • 2) Assignment operators=+=-=*=/=%=**=//=.
  • 3) Bitwise operators&|^~<<>>.
  • Strings: Strings can be enclosed in single or double quotes. You can use the + operator to concatenate strings.
greeting = "Hello"
name = "John"
message = greeting + ", " + name + "!"
print(message) # Output: Hello, John!


Lightbox


Control Flow

Python supports various control flow structures, such as if-else statements, loops, and more.

  • If-else statement
    if x > 10:
    print("x is greater than 10")
    else:
    print("x is less than or equal to 10")
  • For Loops
    for var in iterable:    # statements
  • While Loop
    while expression:
    statement(s)

Functions

Functions are blocks of code that perform a specific task. You can define your own functions using the def keyword.

def greet(name):
print(f"Hello, {name}!")
greet("GeeksforGeeks") # Output: Hello, GeeksforGeeks!


1) Arithmetic operators
2) Assignment operators
3) Bitwise operators
4) Logical operators
5) Comparison operators
6) Identity Operator
7) Membership Operator

----------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------

1) Python Arthmetic Operators

https://www.youtube.com/watch?v=od-tR72Y9lk 

Python provides several arithmetic operators to perform common mathematical operations. Here is a list of Python's arithmetic operators and their usage:






PRECEDENCE:

  • P - Parentheses
  • E - Exponentiation
  • M - Multiplication     (Multiplication and division have the same precedence)
  • D - Division
  • A - Addition     (Addition and subtraction have the same precedence)
  • S - Subtraction

The modulus operator helps us extract the last digit/s of a number. For example:

  • x % 10 -> yields the last digit
  • x % 100 -> yield last two digits






1. Addition (+)

Adds two numbers.

a = 10
b = 5
result = a + b  # result is 15

Ex:1

#addition
a = 1
b = 2
c = a+b 
print(c)
o/p = 3

2. Subtraction (-)

Subtracts the second number from the first.

a = 10

b = 5

result = a - b  # result is 5

Ex:1

#Subtraction (-)

a = 500

b = 250

c = a-b 

print(c)

o/p = 250


3. Multiplication (*)

The asterisk (*) symbol in Python serves multiple purposes depending on the context in which it is used. Here’s an overview of its different uses.

Multiplies two numbers.

python

a = 10

b = 5

result = a * b # result is 50

EX:1

#Multiplication (*)

a = 10

b = 10

c = a*b 

print(c)

o/p = 200

4. Division (/)

Divides the first number by the second and returns a float (even if both operands are integers).

it is single division operator its give floating value as an output

The parts of a division operator

dividend, divisor, quotient, and remainder: 


a = 11

b = 2

c = a / b

c = 5.5 it is a floating value


పాయింట్ తర్వాత వచ్చే వాల్యూ అనేది ఫ్లోటింగ్ అవుతుంది  లేదా మారుతుంది 


Topic video link :  https://www.youtube.com/watch?v=od-tR72Y9lk

ex: 1

a = 10

b = 5

result = a / b # result is 2.0


ex:

a = 10

b = 3

result = a / b # result is 3.3333333333333335

o/p: 3.3333333333333335 ----> it is floating value 











12/7 =1.7

EX :1

#Division (/)
a = 100
b = 2
c = a/b 
print(c)

o/p = 50.0



 3/1 = 3.0
 3//1 = 1

5. Floor Division (//)

Performs integer division and returns the largest possible integer (rounds down).

python

a = 10

b = 3

result = a // b # result is 3

Ex:1

12//7 = 1 

7//3 = 2


Ex:2

#Floor Division (//)

a = 300

b = 2

c = a//b 

print(c)

o/p = 150

Example for usage of #Floor Division (//) and # Division(float) 

purpose For Loop:


#EX:1

a = 10

b = 3

for i in range(1,10):

    print(i)

o/p:

1

2

3

4

5

6

7

8

9


#EX:2

a = 10

b = 3

print(a/b)

o/p: 3.3333333333333335


#Ex:3

a = 10

b = 3 

for i in range(1,a/b): # లూప్ అనేది 1 నుండి 3.33333 వరకు రిపీట్ అవ్వాలి అన్నాను  

     print(i)

o/p:

లూప్  రిపీట్ అవ్వలేదు టైపు ఎర్రర్ వచ్చింది 

3.33333 టైమ్స్  లూప్ రిపీట్ అవ్వదు -- ఫ్లోట్ వేల్యూ 

3 టైమ్స్ మాత్రమే అవుతుంది  --- ఇంటిజెర్  వేల్యూ 


'ఫ్లోట్' ఆబ్జెక్ట్‌ను పూర్ణాంకంగా అర్థం చేసుకోలేము


#EX:4

a = 10

b = 3

print(a//b)

o/p: 3 ----> integer (పూర్ణాంకంగా) a//b = 3


#EX:5 #double division operator (a//b)

a = 10

b = 3

for i in range(1,a//b):  # 1 2 

    print(i)

o/p:

1

2


----------------------------------------------------

12 / 5 = 2.4

12 // 5 = 2




-------------------------------------------------------------------------------

సింగిల్ డివిజన్ ఆపరేటర్ అనేది ఫ్లోట్ వేల్యూ కోసం ఉపయోగిస్తారు . 

డబుల్ డివిజన్ ఆపరేటర్ అనేది కంప్లీట్ ఇంటిజెర్ వేల్యూ కోసం ఉపయోగిస్తారు . 

-------------------------------------------------------------------------------

6. Modulus (%)




Returns the remainder when the first number is divided by the second.

modulus anedi 
మొదటి సంఖ్యను రెండవ సంఖ్యతో భాగించినప్పుడు మిగిలిన మొత్తాన్ని (remainder value)అందిస్తుంది.

a = 10

b = 3

result = a % b # result is 1

a = 12

b = 5

a % b = 2


7. Exponentiation (**) or power

Raises the first number to the power of the second number.


in Python, exponentiation is represented by the ** operator. 

For example, 2 ** 3 equals 8, which means 2 raised to the power of 3. You can also use the built-in pow() function for exponentiation, like pow(2, 3), which achieves the same result.

Ex:1

a = 2

b = 3

result = a ** b 

 # result is 8 (2^3)






Explanation:

2 * 2 * 2 = 8  #c = 4 ** 3 = 8

7 * 7 = 49  #c = 7 ** 2 = 49

4 * 4 * 4 * 4 * 4 = 1024 # c = 4 ** 5

10 * 10 * 10 = 1000 # c = 10 ** 3 = 1000

Ex:2

a = 2

b = 3

result = pow(a, b)    #pow(2,3)

# result is 8 (2^3)


7 ** 2 = 49

3 ** 2  = 9

10 ** 3 = 1000


-------------------------------------------------------------------------------


Python Arithmetic operators


a = 10

b = 3

add = a + b # 13

subtract = a - b # 7

multiply = a * b # 30

divide = a / b # 3.3333...

floor_divide = a // b # 3

modulus = a % b # 1

exponent = a ** b # 1000 (10^3)


-------------------------------------------------------------------------------

14/10/24
2) Assignment operators


=
+=
-=
*=
/=
%=
//=
**=
&=
|=
^=
>>=
<<=
-------------------------------------------------------------------------------


In Python, assignment operators are used to assign values to variables. They can also be used for operations like addition, subtraction, multiplication, and division while assigning the result to the variable.



Here’s a breakdown of the most commonly used assignment operators in Python:

1. Basic Assignment Operator (=)

This assigns the value on the right to the variable on the left.

x = 5
# x is now 5


var = 8
var

o/p : 8

2. Add and Assign (+=)

This adds the right operand to the left operand and assigns the result to the left operand.


x = 5
x += 3
# x is now 8

var = 8
var = var + 6
print(var)

o/p: 8 + 6 =14


var = 14
var += 8
print(var)

o/p: 22


3. Subtract and Assign (-=)

This subtracts the right operand from the left operand and assigns the result to the left operand.


x = 10
x -= 4
# x is now 6


var = 22
var -= 8
print(var)

o/p: 14

4. Multiply and Assign (*=)

This multiplies the left operand by the right operand and assigns the result to the left operand.


x = 7
x *= 2
# x is now 14


var = 14
var = var * 2
print(var)

#var = 14 * 2
    var = 28
o/p: 28




var = 14
var *= 2
print(var)
o/p: 28


5. Divide and Assign (/=)

This divides the left operand by the right operand and assigns the result to the left operand. The result is a floating-point number.


x = 20
x /= 4
# x is now 5.0








var = 28
var /= 2
print(var)

o/P: 14.0

6. Modulus and Assign (%=)

This finds the remainder of division between the left and right operands and assigns the result to the left operand.


x = 10

x %= 3

# x is now 1





x = 6
x % 4
print(x)
o/p: 2


x %= 4
print(x)


o/p: 

#Modulus is shows remainder value 



7. Floor Division and Assign (//=)

This performs floor division (integer division) between the left and right operands and assigns the result to the left operand.


x = 15

x //= 4

# x is now 3 (because 15 // 4 is 3)








x = 9
x //= 4
print (x)

o/p: 2---> quotient. 
       1 -----> remainder


8. Exponentiation and Assign (**=)

This raises the left operand to the power of the right operand and assigns the result to the left operand.


x = 2

x **= 3

# x is now 8 (because 2^3 is 8)


9. Bitwise AND and Assign (&=)

This performs a bitwise AND operation between the left and right operands and assigns the result to the left operand.


x = 5  # (101 in binary)
x &= 3  # (011 in binary)
# x is now 1 (because 101 & 011 is 001)



10. Bitwise OR and Assign (|=)

This performs a bitwise OR operation between the left and right operands and assigns the result to the left operand.


x = 5  # (101 in binary)
x |= 3  # (011 in binary)
# x is now 7 (because 101 | 011 is 111)


11. Bitwise XOR and Assign (^=)

This performs a bitwise XOR operation between the left and right operands and assigns the result to the left operand.

x = 5  # (101 in binary)
x ^= 3  # (011 in binary)
# x is now 6 (because 101 ^ 011 is 110)



12. Bitwise Left Shift and Assign (<<=)

This shifts the bits of the left operand to the left by the number of positions specified by the right operand and assigns the result to the left operand.


x = 5  # (101 in binary)

x <<= 1

# x is now 10 (because 101 becomes 1010, which is 10)



13. Bitwise Right Shift and Assign (>>=)

This shifts the bits of the left operand to the right by the number of positions specified by the right operand and assigns the result to the left operand.


x = 5  # (101 in binary)
x >>= 1
# x is now 2 (because 101 becomes 10, which is 2)



Example of Multiple Assignment Operators:

You can chain assignment operators for concise code:


x = 5
x += 2  # Now x is 7
x *= 3  # Now x is 21
x -= 4  # Now x is 17
x /= 2  # Now x is 8.5








-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
3) Bitwise operators

Table-1

Decimal 16 8 4 2 1 Binary
00000000000
10000100001
20001000010
30001100011
40010000100
50010100101
60011000110
70011100111
80100001000
90100101001
100101001010
110101101011
120110001100
130110101101
140111001110
150111101111
161000010000
171000110001
181001010010
191001110011
201010010100
211010110101
221011010110
231011110111
241100011000
251100111001
261101011010
271101111011
281110011100
291110111101
301111011110
311111111111
3210000100000


బైనరీ కోడ్ కనుక్కోవడం ఎలాగా 






Bitwise Operators

Bitwise operators act on bits and perform the bit-by-bit operations. 

These are used to operate on binary numbers.


Table-2

Bitwise Operators in Programming: Descriptions and Syntax

Operator Description Syntax
& Bitwise AND x & y
| Bitwise OR x | y
~ Bitwise NOT (COMPLIMENT) ~x
^ Bitwise XOR x ^ y
>> Bitwise right shift x >> y
<< Bitwise left shift x << y

Truth Tables 

Explain Bitwise Operators Clearly and Simple

https://www.youtube.com/watch?v=XbjQ-heGd58

Bitwise operators work directly on the binary (bit-level) representation of numbers. They are useful when you want to manipulate individual bits of integers. Here's a simple breakdown of the main bitwise operators:


1. Bitwise AND (&)

  • Action: Compares each bit of two numbers. The result is 1 if both bits are 1, otherwise 0.
  • Example:
    • 5 & 3 → 101 & 011 = 001 (binary) → result: 1

2. Bitwise OR (|)

  • Action: Compares each bit of two numbers. The result is 1 if either bit is 1.
  • Example:
    • 5 | 3 → 101 | 011 = 111 (binary) → result: 7

3. Bitwise NOT (~)

  • eAction: Flips each bit of the number (i.e., turns 1 to 0 and vice versa).
  • Example:
    • ~5 → ~(101) = ...11111010 (binary) → result: -6 (in 2's complement)

4. Bitwise XOR (^)

  • Action: Compares each bit of two numbers. The result is 1 if the bits are different, and 0 if they are the same.
  • Example:
    • 5 ^ 3 → 101 ^ 011 = 110 (binary) → result: 6

5. Bitwise Right Shift (>>)

  • Action: Shifts the bits of the number to the right by the specified number of positions, filling with 0s.
  • Example:
    • 8 >> 2 → 1000 >> 2 = 0010 (binary) → result: 2

6. Bitwise Left Shift (<<)

  • Action: Shifts the bits of the number to the left by the specified number of positions, filling with 0s.
  • Example:
    • 3 << 2 → 0011 << 2 = 1100 (binary) → result: 12
Table-3
Truth Tables 



Bitwise Operators: Summary Table

Operator Description Example Result
& Bitwise AND 5 & 3 1
| Bitwise OR 5 | 3 7
~ Bitwise NOT ~5 -6
^ Bitwise XOR 5 ^ 3 6
>> Bitwise Right Shift 8 >> 2 2
<< Bitwise Left Shift 3 << 2 12


Truth Tables for Bitwise Operators

1. Bitwise AND (&)

A B A & B
0 0 0
0 1 0
1 0 0
1 1 1

2. Bitwise OR (|)

A B A | B
0 0 0
0 1 1
1 0 1
1 1 1

3. Bitwise NOT (~)

A ~A
0 1
1 0

4. Bitwise XOR (^)

A B A ^ B
0 0 0
0 1 1
1 0 1
1 1 0

5. Bitwise Right Shift (>>)

A A >> 1 A >> 2
0 0 0
1 0 0
2 1 0
3 1 0
4 2 1
5 2 1
6 3 1
7 3 1
8 4 2

6. Bitwise Left Shift (<<)

A A << 1 A << 2
0 0 0
1 2 4
2 4 8
3 6 12
4 8 16
5 10 20
6 12 24
7 14 28
8 16 32


Practice Examples- AND Operation

Link: https://www.youtube.com/watch?v=XbjQ-heGd58

a = 5
b = 4
print(a & b)

o/p: 4

Explanation: 

Binary Representation of Decimal Values
Truth tables

Binary Representation of Decimal Values


Decimal 16 8 4 2 1 Binary
5 0 0 1 0 1 00101
4 0 0 1 0 0 00100



Practice Examples- OR Operation
Ex:1

x = 5
y = 6
print(x | y)
#OR Operation
o/p: 7

Ex:2

r = 5
r | = 6
print (r)

o/p: 7




Practice Examples- XOR Operation
Ex:1
x = 8
y = 9
print(x ^ y)
o/p: 1

#XOR Operation


Ex 2:
t = 8
t ^= 9
print(t)

o/p: 1




Not operation
---------------------------------------------

Right Shift Operation
---------------------------------------------

Left Shift Operation
---------------------------------------------
how to uderstand leftshift operator in python

The left shift operator (<<) in Python shifts the bits of a number to the left by a specified number of positions. Each shift to the left effectively doubles the number, which is equivalent to multiplying by 2 for each shift position.

How Left Shift Works

  • When you apply the left shift operator, the binary representation of the number shifts to the left by a given number of bits.
  • For each left shift, a 0 is added to the right, which increases the number's value.
  • The left shift operation does not change the sign of the number; it only moves its bits to the left.

Example

Let's take an example with a small integer:

Step 1: Start with a Number

Suppose we have the number 5. In binary, 5 is: 5  ->  0b00000101

Step 2: Apply Left Shift

If we apply a left shift of 2 positions, the operation would look like this in Python:

result = 5 << 2
print(result)  # Output will be 20


Step 3: Breakdown of the Operation

  1. Binary Shift:
    • 5 in binary is 00000101.
    • Shifting it 2 positions to the left: 00010100.
  2. Binary to Decimal:
    • 00010100 in binary equals 20 in decimal.

Each shift to the left doubles the value:

  • 5×22=5×4=205 \times 2^2 = 5 \times 4 = 20

Formula for Left Shift

If a << b, it is equivalent to:

-------------------

a * (2 ** b)


-------------------

where a is the initial number, and b is the number of positions shifted.

Another Example

For clarity, let's try another example:

-------------------

num = 3       # Binary: 00000011

shifted = num << 1  # Shift left by 1

print(shifted)  # Output will be 6


-------------------

Explanation:

  • Binary of 3 is 00000011.
  • Shifting 3 left by 1 bit gives 00000110, which is 6 in decimal.

Summary

  • Syntax: number << positions
  • Effect: Moves bits to the left by positions, adding 0s to the right.
  • Usage: Useful in low-level programming, binary manipulation, and when calculating powers of 2 quickly.

This can be particularly helpful for memory-efficient operations where only specific bits of data are needed. Let me know if you'd like to go deeper into bitwise manipulation in Python!


front side or left side values are moved to back or right side to add this cause number will change as o/p 

Yes, in a left shift operation (<<), values on the left side of the binary representation are "pushed out" and are effectively discarded, while new 0s are added on the right side. This change in bit positions causes the overall value of the number to increase (usually by powers of 2). Here’s a clearer look:




Why Left Shift Changes the Number

In binary, each position represents an increasing power of 2, from right to left:

  • The far-right bit represents 202^0,
  • The next bit to the left represents 212^1, then 222^2, and so on.

When a left shift happens:

  1. All bits are shifted left, moving to a position representing a higher power of 2.
  2. 0s fill in from the right to complete the number length.
  3. Bits on the far left side that "shift out" are lost, permanently altering the value.


Example in Action

Let’s say we have a number 5, which is 0b00000101 in binary.

Left Shift Example

-------------------

number = 5           # Binary: 00000101
shifted = number << 1  # Shift left by 1
print(shifted)         # Output: 10


-------------------

Step-by-Step Explanation:

  • Original: 5 in binary is 00000101.
  • Shift Left by 1: This moves each bit one position to the left, resulting in 00001010.
  • New Value: 00001010 in binary is 10 in decimal.

Why This Happens

The left shift has "pushed" each bit one place higher, essentially doubling the value:

  • Shifting left once (<< 1) doubles the number.
  • Shifting left twice (<< 2) quadruples it, and so on.

This shifting effect is why left shifts cause the output number to be different from the input. Would you like a visual breakdown or further practice examples?


00101 this is 16,8,4,2,1 Binary bit but your given to me 00000101 which binary bit



The notation 00000101 represents an 8-bit binary representation, where each 0 or 1 is a "bit." This notation uses 8 bits in total to represent the number 5 in binary.

Explanation of 00000101 as an 8-Bit Binary

Each position in the 8-bit binary sequence represents a power of 2:

  • From right to left, the positions represent: 20,21,22,23,24,25,26,272^0, 2^1, 2^2, 2^3, 2^4, 2^5, 2^6, 2^7.

So, the binary 00000101 is broken down as follows:

------------------------------------------------------------------------

Position:    7    6    5    4    3    2    1    0
                    0    0    0    0    0    1    0    1

------------------------------------------------------------------------
 

When we calculate the values:

  • 22=42^2 = 4
  • 20=12^0 = 1

So, adding up these values: 4+1=54 + 1 = 5.

Understanding the Minimal Representation

When you see 00000101, it’s just an 8-bit way of representing the same value as 101 (the 3-bit minimal representation for 5).

For most examples, we often use the minimum number of bits necessary, but adding extra 0s on the left doesn’t change the value. So whether it’s represented as 101, 00000101, or even 0000000000000101 (16 bits), it’s still the same number, 5, in binary form.


https://www.youtube.com/watch?v=XbjQ-heGd58


https://www.youtube.com/watch?v=W7UwsfU6Tbg


బిట్ విస్ లెఫ్ట్ షిఫ్ట్ ఆపరేటర్  ఏమి చేస్తుంది అంటే 

ఒక ఇంటిజెర్ లో వున్నా బిట్స్ ని లెఫ్ట్ కి షిఫ్ట్ చేస్తుంది . మరియు షిఫ్ట్ ఐన దగ్గర 

ఖాళీ స్థానము లో జీరో తో తో ఫిల్ చేస్తుంది. 

  • Syntax: number << positions
  • OPERAND 1 << OPERAND 2

 









BIT

5<<2 

O/P = 20 
5 = 0000010 -> BINARY NUMBER

ఈ బైనరీ నంబర్ లో ప్రతి బిట్ two  టైమ్స్ లెఫ్ట్ కి షిఫ్ట్ అవుతుంది ;


బిట్ వైస్ లెఫ్ట్ షిఫ్ట్ ఆపరేటర్ ని ఇంకో విదంగా వాడతారు. 
ఒక నెంబర్ ని two పవర్ తో multiply చేయడానికి  ఈ  లెఫ్ట్ ఆపరేటర్ ని వాడతాము ;




-------------------------------------------------------------------------------------------------------------------
2 = 00010
3 =  00011
12 = 01100
14 = 01110

12<<2  = 48

01100 << 2




Example -2:

14<<3 = 112

1110 << 3 

int ('1110000', 2) = 112

3  టైమ్స్  లెఫ్ట్ కి షిఫ్ట్ అయ్యింది 

The operation 14 << 3 represents a bitwise left shift of the binary number for 14 by 3 positions.

Here's how it works step-by-step:

Step 1: Convert 14 to Binary

The decimal number 14 in binary is:

14 = 1110 (in binary)

Step 2: Apply the Left Shift

The left shift operator (<<) shifts all bits in the binary representation to the left by the specified number of positions. For 14 << 3, we shift the bits in 1110 three positions to the left, and we fill the empty positions with 0s on the right.

Starting with 1110:

1110 << 3 = 1110000

Step 3: Convert the Result to Decimal

Now, 1110000 in binary is equal to:


1×64 + 1×32 + 1×16 = 112 (in decimal)

Final Answer

So, 14 << 3 gives 112.

Explanation

A left shift by n bits is equivalent to multiplying the number by 2^n. Here:

  • 14 * 2^3 = 14 * 8 = 112


-------------------------------------------------------------------------------------------------------------------
Explanation :

int('1110000', 2)=112 how to 

The expression int('1110000', 2) converts the binary string '1110000' into its decimal equivalent. Let's break down how this conversion works:

Step-by-Step Conversion

The binary number '1110000' represents each position as a power of 2, from right to left:

1×26+1×25+1×24+0×23+0×22+0×21+0×201 \times 2^6 + 1 \times 2^5 + 1 \times 2^4 + 0 \times 2^3 + 0 \times 2^2 + 0 \times 2^1 + 0 \times 2^0

Calculating each term:

  • 1×26= 64
  • 1×25
  • 1×24
  • 0×23
  • 0×22=
  • 0×21=0
  • 0×20=

Adding these values together:

64+32+16+0+0+0+0=11264 + 32 + 16 + 0 + 0 + 0 + 0 = 112

Final Result

So, int('1110000', 2) evaluates to 112 in decimal.

-------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------

Bitwise Right Shift (>>)

ఇది ఇంటిజెర్ లో వున్నా బిట్స్ ని రైట్ కి షిఫ్ట్ చేస్తుంది. 
అండ్ షిఫ్ట్ ఐన ఖాళీ ప్లేస్ లో "జీరో "ని ఫిల్ చేస్తుంది.  ఇంటిజెర్ పాజిటివ్ ఐతే ఇలాగ జరుగుతుంది. 
ఒక వేళా ఇంటిజెర్ నెగేటివ్ ఐతే ఖాళీ ప్లేస్ లో "1" ని ఫిల్ చేస్తుంది చేస్తుంది,
Intiger Negative method
Intiger Positive method

-------------------------------------------------------------------------------------------------------------------

రైట్ షిఫ్ట్  ఆపరేటర్ ,Intiger Positive method
-------------------------------------------------------------------------------------------------------------------
Example:

48>>2 = 12

To understand why 48 >> 2 = 12, we need to break down what the ">>" operator means.

The >> symbol is called the right shift operator in programming. When you apply x >> y, it shifts the bits of x to the right by y positions. Each right shift divides the number by 2.

Let's see this in steps:

  1. Convert 48 to binary:

    • 48 in binary is 110000.
  2. Right shift by 2 positions:

    • When we shift 110000 two places to the right, we remove the last two bits:
    • 110000 becomes 1100.
  3. Convert 1100 back to decimal:

    • 1100 in binary is 12 in decimal.

So, 48 >> 2 shifts the bits two places to the right, effectively dividing 48 by 222^2 (or 4), giving the result 12.

In Summary:

  • 48 >> 2 shifts the bits of 48 right by 2 places.
  • This is equivalent to dividing 48 by 4.
  • The result is 12.

-------------------------------------------------------------------------------------------------------------------Example:2
-------------------------------------------------------------------------------------------------------------------
4 >> = 1 = 2
int ('010',2)
అవుట్ ఫుట్ = 2


k = 4
k >>=1
print (k )
అవుట్ ఫుట్ = 2
 

Example:

To calculate 5 >> 2, let's break it down.

Explanation of >> (Right Shift) Operator

The >> operator shifts the bits of a number to the right by a specified number of positions. Each right shift divides the number by 22.

Steps to Calculate 5 >> 2

  1. Convert 5 to Binary:

    • 5 in binary is 101.
  2. Right Shift by 2 Positions:

    • Shifting 101 two places to the right removes the last two bits:
    • 101 becomes 1.
  3. Convert 1 Back to Decimal:

    • 1 in binary is simply 1 in decimal.

So, 5 >> 2 results in 1.

In Summary

  • 5 >> 2 shifts the bits of 5 right by 2 positions, which is equivalent to dividing 5 by 222^2 (or 4).
  • The result is 1.

-------------------------------------------------------------------------------------------------------------------
ex:
5>>1



7>>2





------------------------------------------------------------------------------------------------------------------- Intiger Negative method
-------------------------------------------------------------------------------------------------------------------
Example:
-6>>1


పాజిటివ్ నెంబర్ (+ve 6) బైనరీ కోడ్ ని నేగిటివ్ నెంబర్ (-6) బైనరీ కోడ్ లోకి ఎలాగా మార్చాలి 

To represent -6 in binary, we use two's complement notation. Here are the steps to find the two's complement representation of -6 in an 8-bit binary form:

Steps to Represent -6 in Binary (Two's Complement)

  1. Find the Binary Representation of Positive 6:

    • Positive 6 in binary (using 8 bits) is: 0000 0110.
  2. Invert the Bits:

    • Invert all the bits (change 0s to 1s and 1s to 0s) of 0000 0110:
    • Result: 1111 1001.
    • పాజిటివ్ నెంబర్  బైనరీ కోడ్ లో వున్నా జీరో'స్ (0) అన్ని కూడా వన్ 'స్ (1)అవుతాయి.  
  3. Add 1 to the Inverted Bits:

    • Add 1 to 1111 1001:
    • 1111 1001 + 1 = 1111 1010.

So, -6 in 8-bit binary (two's complement) is 1111 1010.

In summary:

  • Positive 6 in 8-bit binary: 0000 0110
  • Negative 6 in 8-bit binary (two's complement): 1111 1010




4) Logical operators
5) Comparison operators






# To find two variable equal or not we can find with "==" symbol
a = 10 
b = 10
c = 5

print(a == b)
print(b == c)
print(c == a)
print(c == b)

o/p:

True
False
False
False

# "!=" this symbol is not equals

# two variable equl kadu ani cheppalante not equals ni use chestaru. 
a = 10 
b = 10
c = 5

print(a != b)
print(b != c)
print(c != a)
print(c != b)

o/p:

False
True
True
True

#less than , greater than , lessthan are equals to,  greater than are equals to.

a = 10 
b = 10
c = 5

print(a > b)
print(b > c)
print(c > a)



print(a < b)
print(b < b)
print(c < a)



print(a <= b )
print(b <= c)
print(c <= a)



print(a >= b)
print(b >= c)
print(c >= a)

o/p:
False
True
False
False
False
True
True
False
True
True
True
False


6)  membership Operator- https://www.youtube.com/watch?v=MHl0Jj15crA

7) Identity Operator- -https://www.youtube.com/watch?v=BG3lg589HRE



-------------------------------------------------------------------------------
PYthon Membership Operator

-------------------------------------------------------------------------------
PYthon Membership Operator
----Python IN Operator
---Python NOT IN Operator


-------------------------------------------------------------------------------

Ex:
str = "Jerry"




-------------------------------------------------------------------------------


Python IN Operator
The in operator is used to check if a character/substring/element exists in a sequence or not. Evaluate to True if it finds the specified element in a sequence otherwise False.

Example 1: Checking 'g' in string since Python is case-sensitive, returns False
'g' in 'GeeksforGeeks' 
>>False

Example 2: Checking 'Geeks' in list of strings
'Geeks' in ['Geeks', 'For','Geeks']   
>>True

Example 3: Checking 3 in keys of dictionary
dict1={1:'Geeks',2:'For',3:'Geeks'}    
3 in dict1
>>True

Example 1: In this code we have initialized a list, string, set, dictionary and a tuple. Then we use membership in operator to check if the element occurs in the corresponding sequences or not.

python code:

--------------------------------------------------------------------
# initialized some sequences
list1 = [1, 2, 3, 4, 5]
str1 = "Hello World"
set1 = {1, 2, 3, 4, 5}
dict1 = {1: "Geeks", 2:"for", 3:"geeks"}
tup1 = (1, 2, 3, 4, 5)

# using membership 'in' operator
# checking an integer in a list
print(2 in list1)

# checking a character in a string
print('O' in str1)

# checking an integer in aset
print(6 in set1)

# checking for a key in a dictionary
print(3 in dict1)

# checking for an integer in a tuple
print(9 in tup1)

-------------------------------------------------------------------------------
Output:

True
False
False
True
False


-------------------------------------------------------------------------------

Example 2: Let us see the another example, but this time without using the ‘in’ operator:


python code:

--------------------------------------------------------------------
#  Define a function() that takes two lists
def overlapping(list1, list2):

    c = 0
    d = 0
    for i in list1:
        c += 1
    for i in list2:
        d += 1
    for i in range(0, c):
        for j in range(0, d):
            if(list1[i] == list2[j]):
                return 1
    return 0


list1 = [1, 2, 3, 4, 5]
list2 = [6, 2, 8, 9]
if(overlapping(list1, list2)):
    print("overlapping")
else:
    print("not overlapping")

-------------------------------------------------------------------------------
Output:

overlapping

-------------------------------------------------------------------------------
Time Complexity:

The execution speed of the ‘in’ operator depends on the target object’s type.

List: O(n), it becomes slower as the number of elements increases.
Sets: O(1), it does not depend on the number of elements.
For dictionaries, the keys in the dictionary are unique values like set. So the execution is same as the set. Whereas the dictionary values can be repeated as in a list. So the execution of ‘in’ for values() is same as lists.

Python NOT IN Operator
The ‘not in’ Python operator evaluates to true if it does not find the variable in the specified sequence and false otherwise.

Example: In this code we have initialized a list, string, set, dictionary and a tuple. Then we use membership ‘not in’ operator to check if the element occurs in the corresponding sequences or not.



python code:

--------------------------------------------------------------------
# initialized some sequences
list1 = [1, 2, 3, 4, 5]
str1 = "Hello World"
set1 = {1, 2, 3, 4, 5}
dict1 = {1: "Geeks", 2:"for", 3:"geeks"}
tup1 = (1, 2, 3, 4, 5)

# using membership 'not in' operator
# checking an integer in a list
print(2 not in list1)

# checking a character in a string
print('O' not in str1)

# checking an integer in aset
print(6 not in set1)

# checking for a key in a dictionary
print(3 not in dict1)

# checking for an integer in a tuple
print(9 not in tup1)

-------------------------------------------------------------------------------

Output:
False
True
True
False
True

-------------------------------------------------------------------------------

The operators.contains() Method
An alternative to Membership ‘in’ operator is the contains() function. This function is part of the Operator module in Python. The function take two arguments, the first is the sequence and the second is the value that is to be checked.


Syntax: operator.contains(sequence, value)


Example: In this code we have initialized a list, string, set, dictionary and a tuple. Then we use operator module’s contain() function to check if the element occurs in the corresponding sequences or not.

python code:

--------------------------------------------------------------------------------

# import module
import operator

# using operator.contain()
# checking an integer in a list
print(operator.contains([1, 2, 3, 4, 5], 2))

# checking a character in a string
print(operator.contains("Hello World", 'O'))

# checking an integer in aset
print(operator.contains({1, 2, 3, 4, 5}, 6))

# checking for a key in a dictionary
print(operator.contains({1: "Geeks", 2:"for", 3:"geeks"}, 3))

# checking for an integer in a tuple
print(operator.contains((1, 2, 3, 4, 5), 9))


-------------------------------------------------------------------------------

Output:


True
False
False
True
False
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
Python Identity Operators
https://www.youtube.com/watch?v=wO43soA1Nvg


-------------------------------------------------------------------------------








-------------------------------------------------------------------------------

Python Identity Operators
-------------------------------------------------------------------------------
https://www.youtube.com/watch?v=BG3lg589HRE
a =  5
b = 5 

print ( a is b) = True
print (a == b) = True
print(id (a)) = 4495189560
print (id (b)) = 4495189560











Identity  Operator
True:
------
a  and  b మెమరీ లాకేషన్ అడ్రస్  same  or object id or memory "locations of both  objects are same "thats why it is returning True.

False:
------
if it will returns false both objects of memory address or locations are "not in same"
thats why it will returns false is called identity  operator.


పైథాన్ ప్రోగ్రామింగ్ లాంగ్వేజ్ పూర్తిగా ఆబ్జెక్ట్ ఓరియెంటెడ్ ప్రోగ్రామింగ్ లాంగ్వేజ్, ప్రతిదీ "వస్తువులు"గా పరిగణించబడుతుంది.

ప్రతి వస్తువు దాని మెమరీ చిరునామాను కలిగి ఉంది, మీరు "యూనిక్ ఆబ్జెక్ట్ ఐడి" అని చెప్పవచ్చు.

id (a)
id (b)

output : 4495189560
a  and  b మెమరీ లాకేషన్ అడ్రస్  same 
memory manager in Python re-uses the objects instead of creating new objects for the same data with the the same datatype.

identity operator compares the memory or address object id 

ఆబ్జెక్ట్ ఐడి అంటే, ఆ మెమరీ చిరునామా తప్ప మరొకటి కాదు

పైథాన్‌లోని మెమరీ మేనేజర్ అదే డేటాటైప్‌తో ఒకే డేటా కోసం కొత్త ఆబ్జెక్ట్‌లను సృష్టించే బదులు ఆబ్జెక్ట్‌లను మళ్లీ ఉపయోగిస్తుంది.

గుర్తింపు ఆపరేటర్ మెమరీ చిరునామాను సరిపోల్చుతుంది






-------------------------------------------------------------------------------
Python Identity Operators
---Python IS Operator
---Python IS NOT Operator

The Python Identity Operators are used to compare the objects if both the objects are actually of the same data type and share the same memory location. There are different identity operators such as:



Python IS Operator
The is operator evaluates to True if the variables on either side of the operator point to the same object in the memory and false otherwise.

Example: In this code we take two integers, lists and strings. Then used the ‘is’ operator to check each datatype’s identity.

python code:

--------------------------------------------------------------------------------


# Python program to illustrate the use
# of 'is' identity operator
num1 = 5
num2 = 5

lst1 = [1, 2, 3]
lst2 = [1, 2, 3]
lst3 = lst1

str1 = "hello world"
str2 = "hello world"

# using 'is' identity operator on different datatypes
print(num1 is num2)
print(lst1 is lst2)
print(str1 is str2)
print(str1 is str2)



Output:

We can see here that even though both the lists, i.e., ‘lst1’ and ‘lst2’ have same data, the output is still False. This is because both the lists refers to different objects in the memory. Where as when we assign ‘lst3’ the value of ‘lst1’, it returns True. This is because we are directly giving the reference of ‘lst1’ to ‘lst3’.


True
False
True
True





Python IS NOT Operator
The is not operator evaluates True if both variables on the either side of the operator are not the same object in the memory location otherwise it evaluates False.

Example: In this code we take two integers, lists and strings. Then used the ‘is not’ operator to check each datatype’s identity.


python code:

--------------------------------------------------------------------
# Python program to illustrate the use
# of 'is' identity operator
num1 = 5
num2 = 5

lst1 = [1, 2, 3]
lst2 = [1, 2, 3]
lst3 = lst1

str1 = "hello world"
str2 = "hello world"

# using 'is not' identity operator on different datatypes
print(num1 is not num2)
print(lst1 is not lst2)
print(str1 is not str2)
print(str1 is not str2)

-------------------------------------------------------------------------------

Output:

False
True
False
False
-------------------------------------------------------------------------------

Difference between ‘==’ and ‘is’ Operator
While comparing objects in Pyhton, the users often gets confused between the Equality operator and Identity ‘is’ operator. The equality operator is used to compare the value of two variables, whereas the identities operator is used to compare the memory location of two variables. Let us see the difference with the help of an example.

Example: In this code we have two lists that contains same data. The we used the identity ‘is’ operator and equality ‘==’ operator to compare both the lists.


python code:

--------------------------------------------------------------------
# Python program to illustrate the use
# of 'is' and '==' operators
lst1 = [1, 2, 3]
lst2 = [1, 2, 3]

# using 'is' and '==' operators
print(lst1 is lst2)
print(lst1 == lst2)

-------------------------------------------------------------------------------

Output:

False
True
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------

python code:

--------------------------------------------------------------------

-------------------------------------------------------------------------------




Comments

Popular posts from this blog

how to practice javascripts online

ui/ux road map

Adobe Photoshop 2024 v25.12.0 Cracked for macOS