0% found this document useful (0 votes)
3 views21 pages

Python Operators Typeconversion

Uploaded by

minnigunta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views21 pages

Python Operators Typeconversion

Uploaded by

minnigunta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Operators in Python

• Operators are special symbols in Python that carry out arithmetic or logical computation.
The value that the operator operates on is called the operand.

• Arithmetic operators

• Relational operators or Comparison operators

• Logical operators

• Assignment operators

• Bitwise operators

• Special operators

• Identity operators

• Membership operators

[Link] operators

• Arithmetic operators are used to perform mathematical operations like addition,


subtraction, multiplication, etc.

Operator Meaning Example

+ Add two operands or unary plus x + y+ 2

Subtract right operand from the left


- x - y- 2
or unary minus

* Multiply two operands x*y

Divide left operand by the right one


/ x/y
(always results into float)

Modulus - remainder of the division of


% x % y (remainder of x/y)
left operand by the right

Floor division - division that results


// into whole number adjusted to the x // y
left in the number line

1
Exponent - left operand raised to the
** x**y (x to the power y)
power of right

Example Program
a=30
b=20
print("a+b= ",(a+b))
print("a-b= ",(a-b))
print("a*b= ",(a*b))
print("a/b= ",(a/b))
print("a%b= ",(a%b))
print("a//b= ",(a//b))
print("4**3= ",(4**3))

Output

2
[Link] Operators or Comparison operators
Comparison operators are used to compare values. It returns either True or False according to the
condition

Operator Meaning Example

Greater than - True if left


> operand is greater than the x>y
right

Less than - True if left operand


< x<y
is less than the right

Equal to - True if both


== x == y
operands are equal

Not equal to - True if operands


!= x != y
are not equal

Greater than or equal to - True


>= if left operand is greater than x >= y
or equal to the right

Less than or equal to - True if


<= left operand is less than or x <= y
equal to the right

3
Example Program

a=30

b=20

print("a<b : ",(a<b))

print("a>b : ",(a>b))

print("10<=9: ",(10<=9))

print("a>=b : ",(a>=b))

print("a==b : ",(a==b))

print("a!=b : ",(a!=b))

Output:

[Link] operators

Operator Meaning Example

And True if both the operands are true x and y

4
True if either of the operands is
Or x or y
true

True if operand is false


Not not x
(complements the operand)

Example Program

a,b,c=10,20,30

print("a<b and a<c : ",(a<b and a<c))

print("a<b or a>c : ",(a<b or a>c))

print("10<=9 and 5>=6: ",(10<=9 and 5>=6))

print("a>b and b>c : ",(a>b and b>c))

print("a==b or a!=b : ",(a==b or a!=b))

print("not(a<b) : ",(not(a<b)))

Output:

5
[Link] operators
• Assignment operators are used in Python to assign values to variables.
• a = 5 is a simple assignment operator that assigns the value 5 on the
right to the variable a on the left.
• There are various compound operators in Python like a += 5 that adds to
the variable and later assigns the same. It is equivalent to a = a + 5.

Operator Example Equivalent to

= x=5 x=5

+= x += 5 x=x+5

-= x -= 5 x=x-5

*= x *= 5 x=x*5

/= x /= 5 x=x/5

%= x %= 5 x=x%5

//= x //= 5 x = x // 5

**= x **= 5 x = x ** 5

Example program
a=30
b=20
a+=b
print("a+=b : ",(a))

6
a-=b
print("b-=a : ",(b))
a*=b
print("a*=b: ",(a))
b/=a
print("b/=a : ",(b))
b//=a
print("b//=a : ",(b))
a**=2
print("a**=2 : ",(a))

7
[Link] operators
• Bitwise operators act on operands as if they were strings of binary
digits. They operate bit by bit, hence the name.
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Left Shift
>> Right Shift
~ Bitwise Complement

• Bitwise AND (&) –


• This operator is a binary operator, denoted by ‘&’. It returns bit by bit
AND of input values, i.e, if both bits are 1, it gives 1, else it gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise AND Operation of 5 and 7
0101
& 0111
________
0101 = 5 (In decimal)
• Bitwise OR (|) –
• This operator is a binary operator, denoted by ‘|’. It returns bit by bit OR
of input values, i.e, if either of the bits is 1, it gives 1, else it gives 0.

For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7


0101
0111
-----------
0111 = 7 (In decimal)

8
Bitwise XOR (^) –
This operator is a binary operator, denoted by ‘^’. It returns bit by bit
XOR of input values, i.e, if corresponding bits are different, it gives 1,
else it gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise XOR Operation of 5 and 7


0101
^ 0111
________
0010 = 2 (In decimal)
Bitwise Complement (~) –
This operator is a unary operator, denoted by ‘~’. It returns the one’s
complement representation of the input value, i.e, with all bits inverted,
which means it makes every 0 to 1, and every 1 to 0.
For example,
a = 10 = 1010 (In Binary)

Bitwise Compliment Operation of 10 is -11

28 27 26 25 24 23 22 21 20
128 64 32 16 8 4 2 1
1010 0 0 0 0 0 1 0 1 0
~10 1 1 1 1 1 0 1 0 1
1’s 1 0 0 0 0 1 0 1 0
complement
2’s +1
complement
1 0 0 0 0 1 0 1 1
-11

Bitwise Left Shift Operator (<<)


Left shift operator shifts the bits of the number towards left a specified number of
positions. The symbol for this operator is <<. When you write x<<n, the meaning is
to shift the bits of x towards left n specified positions.

Example
If x=10, then calculate x<<2 value.

9
Shifting the value of x towards the left two positions will make the leftmost 2 bits to
be lost. The value of x is 10. The binary representation of 10 is 00001010. The
procedure to do left shift explained in the following example:

Observe the above example, after shifting the bits to the left the binary
number 00001010 (in decimal 10) becomes 00101000 (in decimal 40).

Bitwise Right Shift Operator


The Right Shift Operator shifts the bits of the number towards right a specified n
number of positions. Right shift operator represented by the symbol >>, read as
double greater than. When you write x>>n, the meaning is to shift the
bits x towards the right n specified positions.

>> shifts the bits towards the right and also preserve the sign bit, which is the
leftmost bit. The leftmost bit represents the sign of the number. The sign
bit 0 represents a positive number, and 1 represents a negative number. So
after performing >> on a positive number, we get a positive value in the result
also. When we perform >> on a negative number, again we get a negative
value.

Example
If x=10, then calculate x>>2 value.

Shifting the value of x towards the right two positions will make the rightmost 2 bits
to be lost. The value of x is 10. The binary representation of 10 is 00001010. The
procedure to do right shift explained in the following example:

Observe the above example, after shifting the bits to the right the binary
number 00001010 (in decimal 10) becomes 00000010 (in decimal 2).

Example program

a=20

b=30

print("a & b : ",(a & b))

print("a | b : ",(a|b))

print("a ^ b : ",(a^b))

print("a << 2 : ",(a<<2))

print("b >> 2 : ",(b>>2))

print(" ~a : ",(~a))

10
[Link] operators
• Python language offers some special types of operators like the identity
operator or the membership operator. They are described below with
examples.
• Identity operators
• is and is not are the identity operators in Python. They are used to check
if two values (or variables) are located on the same part of the memory.
Two variables that are equal does not imply that they are identical.

Operator Meaning Example

True if the operands


Is are identical (refer to x is True
the same object)

True if the operands


are not identical (do
is not x is not True
not refer to the same
object)

11
Example Program
a=100
b=100
c=50
print("a is b : ",(a is b))
print("b is not c : ",(b is not c))

x=10
y=x
print("x is y : ",(x is y))
print("x is not y : ",(x is not y))

12
Membership operators
• in and not in are the membership operators in Python. They are used to
test whether a value or variable is found in a sequence (string, list, tuple,
set and dictionary).
In a dictionary we can only test for presence of key, not the value.

Operator Meaning Example

True if
value/variable is
In 5 in x
found in the
sequence

13
True if
value/variable is
not in 5 not in x
not found in the
sequence

s="python is very easy to learn"


print(" 'very' in s : ",('very' in s))
print(" 'the' not in s ",('the' not in s))

Type Conversion
• The process of converting the value of one data type (integer, string,
float, etc.) to another data type is called type conversion. Python has
two types of type conversion.
• Implicit Type Conversion

14
• Explicit Type Conversion
• Implicit Type Conversion
• In Implicit type conversion, Python automatically converts one data type
to another data type. This process doesn't need any user involvement.
• Let's see an example where Python promotes the conversion of the
lower data type (integer) to the higher data type (float) to avoid data
loss.
• Example 1: Converting integer to float
a=10
b=10.5
c=a+b
print("datatype of a:",type(a))
print("datatype of b:",type(b))
print("Value of c:",c)
print("datatype of c:",type(c))

Example 2: Addition of string(higher) data type and integer(lower)


datatype
15
num_int = 123
num_str = "456"
print("Data type of num_int:",type(num_int))
print("Data type of num_str:",type(num_str))
print(num_int+num_str)

In the above program,


We add two variables num_int and num_str.
As we can see from the output, we got TypeError. Python is not able to use
Implicit Conversion in such conditions.
However, Python has a solution for these types of situations which is known
as Explicit Conversion.
Explicit Type Conversion
• In Explicit Type Conversion, users convert the data type of an object to
required data type. We use the predefined functions like int(), float(),
str(), etc to perform explicit type conversion.
• This type of conversion is also called typecasting because the user casts
(changes) the data type of the objects.

16
• Syntax :
• <required_datatype>(expression)
Example 3: Addition of string and integer using explicit conversion
num_int = 123
num_str = "456"

print("Data type of num_int:",type(num_int))


print("Data type of num_str before Type Casting:",type(num_str))

num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))

num_sum = num_int + num_str

print("Sum of num_int and num_str:",num_sum)


print("Data type of the sum:",type(num_sum))

17
int()
• int() : to convert other types to int
• float to int conversion
int(10.986)//output :10
• compex to int is not possible
• complex nos are not converted to int if we try it will give error
• bool to int
int(True) // output 1
int(False)// output 0
• str to int is possible
float()
• float()
• [Link] --->float
• float(10)// output 10.0
• [Link] to float not possible
• [Link] to float
• Float(True)// output 1.0
• Float(False)// output 0.0
str to float
• float(‘10’)// output 10.0
float(‘10.235’) // output 10.235

Complex()
• 1)Int to compex
• Complex(10)
10+0j

18
• Complex(10,20)
10+20j
• Complex(True)
1+0j
• Complex(False)
0+0j
• Complex(‘10’)
10+0j
• Complex(‘10.5’)
10.5+0j
• Complex(10.5,20.6)
10.5+20.6j
bool()
• 1 int to bool
• bool(10)
True
• Argument 0 false non zero true
• 2 float to bool
• bool(0.0)
False
• bool(0.1)
True
• [Link]
• bool(0+0j)
False
• bool(1+0j)

19
True
• 4 str
• Empty string returns false
• Any string returns true
• Str()
• Str(10)
‘10’
• Str(0b1111)
‘15’
• Str(10.5)
‘10.5’
• Str(True)
‘True’
• str(False)
‘False’
typecasting Int Float Complex bool Str
argument argument argument argument argument

int Yes Yes no Yes yes


float Yes Yes no Yes yes
complex Yes Yes yes Yes yes
bool Yes Yes yes Yes yes
str Yes Yes yes Yes yes
Key Points to Remember
• Type Conversion is the conversion of object from one data type to
another data type.
• Implicit Type Conversion is automatically performed by the Python
interpreter.
• Python avoids the loss of data in Implicit Type Conversion.

20
• Explicit Type Conversion is also called Type Casting, the data types of
objects are converted using predefined functions by the user.
• In Type Casting, loss of data may occur as we enforce the object to a
specific data type.

21

You might also like