[go: up one dir, main page]

0% found this document useful (0 votes)
5 views10 pages

Python Operators

The document provides an overview of Python operators, including arithmetic, assignment, comparison, logical, identity, membership, and bitwise operators. It also covers Python's built-in data types, how to get and set data types, type casting, and user input/output methods. Examples are provided for each operator and data type to illustrate their usage in Python programming.

Uploaded by

rajubhaikdking
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)
5 views10 pages

Python Operators

The document provides an overview of Python operators, including arithmetic, assignment, comparison, logical, identity, membership, and bitwise operators. It also covers Python's built-in data types, how to get and set data types, type casting, and user input/output methods. Examples are provided for each operator and data type to illustrate their usage in Python programming.

Uploaded by

rajubhaikdking
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
You are on page 1/ 10

PYTHON OPERATORS

Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical
operations:

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

Python Assignment Operators

Assignment operators are used to assign values to variables:

Dr.P.Kalaivani, AP/Dept. of CS SACAS Page 1


Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x–3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Python Comparison Operators

Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Dr.P.Kalaivani, AP/Dept. of CS SACAS Page 2


Python Logical (Boolean) Operators

Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements x < 5 and x < 10


are true

or Returns True if one of the x < 5 or x < 4


statements is true

not Reverse the result, returns False not(x < 5 and x < 10)
if the result is true

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:

Operator Description Example

is Returns True if both variables are the same x is y


object

is not Returns True if both variables are not the x is not y


same object

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

in Returns True if a sequence with the specified value is x in y


present in the object

Dr.P.Kalaivani, AP/Dept. of CS SACAS Page 3


not in Returns True if a sequence with the specified value is x not in y
not present in the object

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Name Description Example


& AND Sets each bit to 1 if both bits are 1 x&y

| OR Sets each bit to 1 if one of two bits is 1 x|y


^ XOR Sets each bit to 1 if only one of two bits is 1 x^y

~ NOT Inverts all the bits ~x


<< Zero fill left shift Shift left by pushing zeros in from the right x << 2
and let the leftmost bits fall off

>> Signed right shift Shift right by pushing copies of the leftmost bit in x >> 2
from the left, and let the rightmost bits fall off

Operator Precedence

Operator precedence describes the order in which operations are performed.

Example

Parentheses has the highest precedence, meaning that expressions inside parentheses must be
evaluated first:

print((8 + 3) - (6 + 3))
2

The precedence order is described in the table below, starting with the highest precedence at the
top:

Operator Description

() Parentheses

Dr.P.Kalaivani, AP/Dept. of CS SACAS Page 4


** Exponentiation

+x -x ~x Unary plus, unary minus, and bitwise NOT

* / // % Multiplication, division, floor division, and modulus

+ - Addition and subtraction

<< >> Bitwise left and right shifts

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

== != > >= < <= is is not in not Comparisons, identity, and membership operators
in

Not Logical NOT

And AND

Or OR

If two operators have the same precedence, the expression is evaluated from left to right.

Example

Addition + and subtraction - has the same precedence, and therefor we evaluate the expression
from left to right:

print(5 + 4 - 7 + 3)

Dr.P.Kalaivani, AP/Dept. of CS SACAS Page 5


PYTHON DATA TYPES
Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:

Text Type: Str


Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: Dict
Set Types: set, frozenset
Boolean Type: Bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType

Getting the Data Type

You can get the data type of any object by using the type() function:

Example
>>>x = 5
>>>print(type(x))
Output
class<int>

Setting the Data Type

In Python, the data type is set when you assign a value to a variable:

Example Data Type


x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple

Dr.P.Kalaivani, AP/Dept. of CS SACAS Page 6


x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType

Setting the Specific Data Type

If you want to specify the data type, you can use the following constructor functions:

Example Data Type


x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = range(6) range
x = dict(name="John", age=36) dict
x = set(("apple", "banana", "cherry")) set
x = frozenset(("apple", "banana", "cherry")) frozenset

x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType

Dr.P.Kalaivani, AP/Dept. of CS SACAS Page 7


PYTHON CASTING
Specify a Variable Type

There may be times when you want to specify a type on to a variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data types,
including its primitive types.

Casting in python is therefore done using constructor functions:

 int() - constructs an integer number from an integer literal, a float literal (by removing all
decimals), or a string literal (providing the string represents a whole number)
 float() - constructs a float number from an integer literal, a float literal or a string literal
(providing the string represents a float or an integer)
 str() - constructs a string from a wide variety of data types, including strings, integer
literals and float literals

Example

Integers:

x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

Floats:

x = float(1) # x will be 1.0


y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2

Strings:

x = str("s1") # x will be 's1'


y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

PYTHON INPUT / OUTPUT


USER INPUT

Python allows for user input. That means we are able to ask the user for input. The method is a
bit different in Python 3.6 than Python 2.7.

Dr.P.Kalaivani, AP/Dept. of CS SACAS Page 8


 Python 3.6 uses the input() method.
 Python 2.7 uses the raw_input() method.

The following example asks for the username, and when you entered the username, it gets
printed on the screen:

Example
username = input("Enter username:")
print("Username is: " + username)
Output
Enter username:Arun
Username is: Arun

Python stops executing when it comes to the input() function, and continues when the user has
given some input.

PYTHON OUTPUT
Output Variables

 The Python print() function is often used to output variables.

Example
x = "Python is awesome"
print(x)

Output
Python is awesome

 In the print() function, you output multiple variables, separated by a comma:

Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
Output
Python is awesome

 You can also use the + operator to output multiple variables:

Example
x = "Python "
y = "is "

Dr.P.Kalaivani, AP/Dept. of CS SACAS Page 9


z = "awesome"
print(x + y + z)
Output
Pythonisawesome

Notice the space character after "Python " and "is ", without them the result would be
"Pythonisawesome".

 For numbers, the + character works as a mathematical operator:

Example
x=5
y = 10
print(x + y)
Output
15

 In the print() function, when you try to combine a string and a number with
the + operator, Python will give you an error:

Example
x=5
y = "John"
print(x + y)
Output
TypeError: unsupported operand type(s) for +: 'int' and 'str'

The best way to output multiple variables in the print() function is to separate them with
commas, which even support different data types:

Example
x=5
y = "John"
print(x, y)
Output
5 John

Dr.P.Kalaivani, AP/Dept. of CS SACAS Page 10

You might also like