0% found this document useful (0 votes)
2 views

PYTHON PROGRAMMING (1)

Python is an interpreted, high-level programming language created by Guido van Rossum in the early 90s, known for its simplicity and versatility across various platforms. It features dynamic typing, extensive libraries, and supports both object-oriented and procedural programming paradigms, making it suitable for a wide range of applications. However, Python has limitations such as slower execution speed and higher memory consumption compared to languages like C or C++.

Uploaded by

sixokic135
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

PYTHON PROGRAMMING (1)

Python is an interpreted, high-level programming language created by Guido van Rossum in the early 90s, known for its simplicity and versatility across various platforms. It features dynamic typing, extensive libraries, and supports both object-oriented and procedural programming paradigms, making it suitable for a wide range of applications. However, Python has limitations such as slower execution speed and higher memory consumption compared to languages like C or C++.

Uploaded by

sixokic135
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

PYTHON PROGRAMMING

Python Introduction
• An interpreted , interactive, dynamically typed, object-
oriented ,cross platform, high level and open source
programming language.
• Created in early 90's by Guido von Rossum at Stichting
Mathematisch Centrum in the Netherlands.
• The name comes from the Monty Python .
• There is a big community of Python programmers, with
conferences and magazines:
http://pycon.org/
• Web site: www.python.org.
• Useful as a scripting language
• script: A small program meant for one-time use
Targeted towards small to medium sized projects.
Used by:

• Google, Yahoo!, Youtube

• Many Linux distributions

• Games and apps (e.g. Eve Online)


Features of Python
• Interactive: one can launch a Python console and run
instructions directly it.
• Portable: available on most existing systems. It only
requires a C compiler to be ported to any new
platform.
• Structure: functions, classes, modules.
• It is easy to embed Python with C and C++.
• The user can write their own code in C or C++ and
compile it as Python modules or functions. That makes
Python extensible.
• Usual applications: scripts including CGI scripts, GUIs,
scientific computing.
• Many existing libraries for all sort of purposes.
Syntax Rules
• The syntax is designed to be simplified as compared to
other languages like C/C++.
• Every compound instruction ends with ":"
• There are no blocks of code; blocks are implicitly
created by indentation.
• Expressions: usual arithmetic operators, named logic
operators: and, or, not.
• Assignments use the = sign but they don't have to end
with ";"
• Comments start with # as in shell scripting.
• Variables are declared by assigning them a value and
they are local to the block where they appear first.
Technical Strength Of Python
1. Easy to Learn: Python is very easy to learn and it does not have any
complex syntax and rules as followed by another language. You can
learn Python very easily if you don't have any coding experience. it is
very user-friendly.
2. Free to Use: Python is free to use and available to download from
its official website. The source code of Python is available for the
public under GPL(General Purpose License) in which you can download
it, modify it, use it, distribute it. You are totally free to do whatever you
want to do with python.
3. Portable: Portability is the main strength of python. Users can run
python programs on various platforms. Suppose you wrote a program
in windows and now you want to run this program on Linux or Mac
Operating system, You can easily run your programs on (Windows,
Mac, Linux, Raspberry Pi, etc.). You can say Python is a platform-
independent programming language.
4. Interpreted: Python is interpreted language which means it does
not require any kind of compiler to run the program. Python converts
its code into bytecode which gives instant results. Python is
interpreted means that its code is executed line by line which makes it
easier to debug.
5. Extensible: It is a very major strength of Python. First, understand
the meaning of extensible in Python that it is developed in a way that
allows the addition of new capabilities and functionality. it does let you
interface Python with libraries written in other languages. (mainly C or
C++).
6. Extensive Libraries: When you download Python it comes with a
large number of libraries that can be used for a specific purpose. You
can download additional libraries according to your need or project
demands. With the help of these libraries, you don't need to write the
complete code just use these libraries and job done with a small
number of instructions. Python provides libraries for web browsers,
image manipulation, databases, email and for many other purposes.
7. Embeddable: One of the best features of Python is that
it is also embeddable. For example, you can embed
youtube video code into your HTML code. Similarly, you
can embed Python code in other programming language
like C++. With this feature, Python gives you the power to
add its code like as a script in your code in a different
language.
8. Object-Oriented: Python can be used as an object-
oriented language in which data structure and functions
are combined in a single unit. Python supports both
object-oriented and procedure-oriented approach in the
development. The object-oriented approach deals with
the interaction between the objects on the other hand
procedure-oriented approach deals with functions only.
9. GUI Programming: Python provides many
solutions to develop a Graphical User Interface
(GUI). Python shipped with a toolkit named tkinter
which is widely used for GUI developments. By
using Python with tkinter you can create GUI
applications very fast and easy.
10. Database Connectivity: Python supports all the
database required for the development of various
projects. Programmers can pick the best suitable
database for their projects. Some examples of
database which is supported by python are MySQL,
PostgreSQL, Microsoft SQL Server, Informix,
Interbase, Oracle and etc.
Weaknesses of Python
1. Speed: Python is interpreted and execute code line by line which
keeps it slower as compared to C or C++. If speed is not the major
concern in the project then you are welcome to use Python.
2. Weak for Mobile Development: Python is the best language for
server-side coding. But when we talk in terms of mobile development
Python is not very good. This is the major reason that you will rarely
see mobile applications developed using Python.
3. Memory Consumption: Python has a very flexible structure for data.
If you have a memory limitation in your project then Python may not
be a good idea to use. Memory consumption is on the higher side.
4. Database Access Layer Issues: Python has issues with database
access layers which restricts it to use in a big company.
5. Run-Time Errors: Python may give you run time errors which lead to
disappointment at the end. Python is dynamically typed language and
you don't need to mention data type in programs which may end up
with run time errors.
PYTHON INTERPRETER
• An Interpreter is a program that converts the
code a developer writes into an intermediate
language, called the byte code. It converts the
code line by line, one at a time. It translates
till the end and stops at that line where an
error occurs, if any, making the debugging
process easy.
• Python and Java are two examples of the
interpreted programming languages.
How it Works
• The program gets converted into an intermediate code,
called bytecode. This is also binary but is not
understood by the processor.
• Python Interpreter, stored in the memory as a
collection of instructions in binary form, does the
above conversion. These instructions can be thought of
as a combination of a compiler and a Python Virtual
Machine (PVM).
• The compiler converts the source code, the “Hello,
World!” program, into the byte code, which is
platform-independent and understood by the PVM.
• PVM reads the byte code and executes it on the
hardware, the job of a processor.
Tokens

• A token is the smallest individual unit or the


basic building blocks in a python program. All
statements and instructions in a program are
built with tokens. The various tokens in
python are .
• Keywords
• Identifiers
• Literals or Values
• Operators
• Punctuators: These are the symbols that used
in Python to organize the structures,
statements, and expressions. Some of the
Punctuators are: [ ] { } ( ) @ -
= += *= //= **== = , etc.
Literals in Python

• Literals are a type of notation used in source code


to represent a fixed value. They can also be
defined as raw values or data that are given in
variables or constants.
• Literals are numbers, strings, characters that
appear directly into the program.
78 #integer literal
23.45 #floating point literal
‘a’ #character literal
“hello” #string literal
• Numeric Literals-
• Integer Literal:
– Both positive and negative numbers, including 0 are allowed. There must be
no fractional parts.
– Ex : 100 , -200 , 300 etc.
• Float Literal:
– These are real numbers with integer and fractional components.
– Ex : 45.5 , 28.4 etc.
• Binary Literal:
– Numbers are represented in binary form.
– For example, 1010 is binary literal for 10
• Octal Literal:
– Numbers are represented in octal form.
• Hexadecimal Literal:
– Numbers are represented in Hexadecimal form.
• Complex Literal:
– Complex numbers are represented by this type.
– For example 6+ 3i ,4+2i etc.
• Boolean Literals
True and False are Boolean literals.
• String literals
A string literal is made by enclosing a text(a
set of characters) in single(”), double(“”), or
triple(“”) quotes. We can write multi-line strings or
show in the desired way by using triple quotes.
• Special literals
There is one special literal in Python (None). A
null variable is described by the word ‘none.’ When
‘None’ is contrasted to something other than
another ‘None,’ it returns false.
• Escape characters
• \ : Newline continuation
• \\ : Display a single \
• \’ : Display a single quote
• \” : Display a double quote
• \b : Backspace
• \n : New Line
• \t : Horizontal Tab
• \v : Vertical Tab
• \r : Enter
Keywords in Python
• Keywords are reserved words with fixed
meaning to them. keywords can not be used
as identifiers or variables
and as assert break

class continue def del

elif else except False

finally for from global

if import in is

lambda None nonlocal not

or pass raise return

True try while with

yield
• Printing all the keywords with the help of
kwlist
import keyword
# printing all keywords at once using "kwlist()"
print("The list of keywords is : ")
print(keyword.kwlist)
Python Character Set
• A character set is a set of valid characters
acceptable by a programming language in
scripting. In this case, we are talking about the
Python programming language. So, the Python
character set is a valid set of characters
recognized by the Python language. These are
the characters we can use during writing a
script in Python. Python supports all ASCII /
Unicode characters that include:
• Alphabets: All capital (A-Z) and small (a-z)
alphabets.
• Digits: All digits 0-9.
• Special Symbols: Python supports all kind of
special symbols like, ” ‘ l ; : ! ~ @ # $ % ^ ` & * ( ) _
+–={}[]\.
• White Spaces: White spaces like tab space, blank
space, newline, and carriage return.
• Other: All ASCII and UNICODE characters are
supported by Python that constitutes the Python
character set.
Identifiers in Python
• An identifier is a name given to entities like class, functions,
variables, etc. It helps to differentiate one entity from
another.
Rules for writing identifiers
• Identifiers can be a combination of letters in lowercase (a
to z) or uppercase (A to Z) or digits (0 to 9) or an
underscore _. Names
like myClass, var_1 and print_this_to_screen, all are valid
example.
• An identifier cannot start with a digit. 1variable is invalid,
but variable1 is a valid name.
• Keywords cannot be used as identifiers.
• We cannot use special symbols like !, @, #, $, % etc. in
our identifier.
• An identifier can be of any length.
• Python is a case-sensitive language. This
means, Variable and variable are not the same.
• Always give the identifiers a name that makes sense.
While c = 10 is a valid name, writing count = 10 would
make more sense, and it would be easier to figure out
what it represents when you look at your code after a
long gap.
• Multiple words can be separated using an underscore,
like this_is_a_long_variable
Python Statement
• Instructions that a Python interpreter can execute are called
statements. For example, a = 1 is an assignment
statement. if statement, for statement, while statement, etc. are
other kinds of statements which will be discussed later.
Multi-line statement
• In Python, the end of a statement is marked by a newline character.
But we can make a statement extend over multiple lines with the
line continuation character (\). For example:
• a=1+2+3+\
4+5+6+\
7+8+9
This is an explicit line continuation.
• In Python, line continuation is implied inside
parentheses ( ), brackets [ ], and braces { }. For
instance, we can implement the above multi-line
statement as:
• a = (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9)
• Here, the surrounding parentheses ( ) do the line
continuation implicitly. Same is the case with [ ] and { }.
For example:
• colors = ['red', 'blue', 'green']We can also put multiple
statements in a single line using semicolons, as follows:
• a = 1; b = 2; c = 3
Python Indentation
• Most of the programming languages like C, C++,
and Java use braces { } to define a block of code.
Python, however, uses indentation.
• A code block (body of a function, loop, etc.) starts
with indentation and ends with the first uninde
nted line. The amount of indentation is up to you,
but it must be consistent throughout that block.
• Generally, four whitespaces are used for
indentation and are preferred over tabs.
• Python Comments
• Comments are very important while writing a program.
They describe what is going on inside a program, so
that a person looking at the source code does not have
a hard time figuring it out.
• You might forget the key details of the program you
just wrote in a month's time. So taking the time to
explain these concepts in the form of comments is
always fruitful.
• In Python, we use the hash (#) symbol to start writing a
comment.
• It extends up to the newline character. Comments are
for programmers to better understand a program.
Python Interpreter ignores comments.
• Multiline Comments
We can use “”” for the multi line comments.
Python Built-in Data Types
The data types defined in Python are given
below.
• Numbers
• Sequence Type
• Boolean
• Set
• Dictionary
• Number stores numeric values. The integer,
float, and complex values belong to a Python
Numbers data-type. Python provides
the type() function to know the data-type of
the variable. Similarly,
the isinstance() function is used to check an
object belongs to a particular class.
• Python creates Number objects when a
number is assigned to a variable.
a=5
print("The type of a", type(a))
The type of a <class 'int'>

b = 40.5
print("The type of b", type(b))
The type of b <class 'float'>

c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))
#isinstance(object,type)
The type of c <class 'complex'>
c is complex number: True
3 types of Numeric data
• Int - Integer value can be any length such as
integers 10, 2, 29, -20, -150 etc. Python has no
restriction on the length of an integer. Its value
belongs to int
• Float - Float is used to store floating-point
numbers like 1.9, 9.902, 15.2, etc. It is accurate
upto 15 decimal points.
• complex - A complex number contains an
ordered pair, i.e., x + iy where x and y denote the
real and imaginary parts, respectively. The
complex numbers like 2.14j, 2.0 + 2.3j, etc.
Sequence Type

• In Python, sequence is the ordered collection


of similar or different data types. Sequences
allows to store multiple values in an organized
and efficient fashion. There are several
sequence types in Python –
• String
• List
• Tuple
1) String
• In Python, Strings are arrays of bytes representing
Unicode characters. A string is a collection of one
or more characters put in a single quote, double-
quote or triple quote. In python there is no
character data type, a character is a string of
length one. It is represented by str class.

• Creating String
• Strings in Python can be created using single
quotes or double quotes or even triple quotes.
Accessing elements of String
• In Python, individual characters of a String can
be accessed by using the method of Indexing.
indexing starts with 0 index, first element will
store at oth position Indexing allows negative
address references to access characters from
the back of the String, e.g. -1 refers to the last
character, -2 refers to the second last
character and so on.
2) List
• Lists are just like the arrays, declared in other
languages which is a ordered collection of
data. It is very flexible as the items in a list do
not need to be of the same type.

Creating List
• Lists in Python can be created by just placing
the sequence inside the square brackets[].
1-List = [‘hellothere']
print("\nList with the use of String: ")
print(List)
o/p-List with the use of String: [‘hellothere’]

2-List = [“hello", “how", “doing"]


print("\nList containing multiple values\n: ")
print(List[0])
print(List[2])
List containing multiple values: hellodoing
List = [[‘hello', ‘there'], [‘hi']]
print("\nMulti-Dimensional List: ")
print(List)
Multi-Dimensional List: [[‘hello', ‘there'], [‘hi']]
• List = [“hi", “how", “doing"]
print("Accessing element using negative
indexing")

# print the last element of list


print(List[-1])
# print the third last element of list
print(List[-3])
3) Tuple
• Just like list, tuple is also an ordered collection of Python objects.
The only difference between tuple and list is that tuples are
immutable i.e. tuples cannot be modified after it is created. It is
represented by tuple class.

Creating Tuple
• In Python, tuples are created by placing a sequence of values
separated by ‘comma’ with or without the use of parentheses for
grouping of the data sequence. Tuples can contain any number of
elements and of any datatype (like strings, integers, list, etc.).
• Note: Tuples can also be created with a single element, but it is a
bit tricky. Having one element in the parentheses is not sufficient,
there must be a trailing ‘comma’ to make it a tuple.
• Tuple1 = ()
print("Initial empty Tuple: ")
print (Tuple1)
Initial empty Tuple: ()

• # Creating a Tuple with the use of Strings


Tuple1 = (‘hello', ‘hi')
print("\nTuple with the use of String: ")
print(Tuple1)
Tuple with the use of String: (‘hello', ‘hi')
• # Creating a Tuple with the use of list
• list1 = [1, 2, 4, 5, 6]
• print("\nTuple using List: ")
• print(tuple(list1))
• Tuple using List: (1, 2, 4, 5, 6)
• # Creating a Tuple with the
• # use of built-in function
• Tuple1 = tuple(‘hello’)
• print("\nTuple with the use of function: ")
• print(Tuple1)
• Tuple with the use of function: (‘h‘, 'e', ‘l', ‘l', ‘o')
• tuple1 = tuple([1, 2, 3, 4, 5])
# Accessing element using indexing
print("First element of tuple")
print(tuple1[0])

• # Accessing element from last negative indexing


print("\nLast element of tuple")
print(tuple1[-1])
print("\nThird last element of tuple")
print(tuple1[-3])
• # Creating a Tuple with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', ‘basic’)
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)
o/p-Tuple with nested tuples: ((0, 1, 2, 3),
('python', ‘basic'))
Int function-
The int function converts a string or a floating
point number into integer
>>>Int(13.56)
13
>>>int(‘123’)
123
• Float Function-
A float function converts astring into a floating
point number
>>>float(‘10.23’)
10.23
Str Function-
This function is used to convert a number into a
string
>>>str(13.7)
‘13.7’
• Boolean Data Type-
The boolean data type is represented in python as type bool.it
can take two values True and False. internally true is for 1 and
false is for 0.
>>>type(True) or type(False)
<class ‘bool’> <class ‘bool’>
The Boolean type is used to compare two values->>>5==4
False
>>>5=5
True
>>>3<7
True
SETS
• A set is an unordered collection of unique elements
without duplicates. A set is mutable. Hence we can
easily add or remove elements from a set. The set data
structure in python is used to support mathematical
set operations. Set items are unordered, unchangeable,
and do not allow duplicate values.
Creating Sets-
A programmer can create a set by enclosing the elements
inside a pair of curly brackets{}.The elements inside a set
can be separated using commas. We can create set by in
built function set() or we can create from an existing list
or tuple
• >>>S1=set() # creating an empty set
>>>S1
Set()

>>>S1={10,20,30,40} #set of 4 elements


>>>S1
{10,20,30,40}

>>>S2=[1,2,3,2,5] #create list


>>>S3=set(S2) #converting list into set
>>>S3
{1,2,3,5} #removes duplicates
>>>S4=(1,2,3,4) #creating tuple
>>>S5=set(S4) #convert tuple to set
>>>S5
{1,2,3,4}
• Python set operations-
union,
intersection
difference
symmetric difference
>>>S1={1,2,3,4}
>>>S2={2,4,5,6}
>>>S1.union(S2)
{1,2,3,4,5,6}
>>>S1|S2
{1,2,3,4,5}
>>>S1.intersection(S2)
{3,4}
>>>S1 &S2
{3,4}
>>>S1.difference(S2)
{1,2}
>>>S1-S2
{1,2}
>>>S1.symmetric_difference(S2)
{1,2,5,6}
>>>S1^S2
{1,2,5,6}
Strings
• Python string is the collection of the characters
surrounded by single quotes, double quotes, or triple
quotes. The computer does not understand the
characters; internally, it stores manipulated character
as the combination of the 0's and 1's.
• Each character is encoded in the ASCII or Unicode
character. So we can say that Python strings are also
called the collection of Unicode characters.
• In Python, strings can be created by enclosing the
character or the sequence of characters in the quotes.
Python allows us to use single quotes, double quotes,
or triple quotes to create the string.
str1 = 'Hello Python'
print(str1)
#Using double quotes
str2 = "Hello Python"
print(str2)
#Using triple quotes
str3 = '''''Triple quotes are generally used for
represent the multiline or
docstring'''
Strings indexing and splitting
Reassigning Strings
• Updating the content of the strings is as easy
as assigning it to a new string. The string
object doesn't support item assignment i.e., A
string can only be replaced with new string
since its content cannot be partially replaced.
Strings are immutable in Python.
str = "HELLO"
str[0] = "h" #will not work
Str = “hello” # will work
Deleting the String- del str
• String Concatenation
To concatenate, or combine, two strings you can use
the + operator.
Example
• Merge variable a with variable b into variable c:
• a = "Hello"
b = "World"
c=a+b
print(c)
• To add a space between them, add a " ":
a = "Hello"
b = "World"
c=a+""+b
print(c)
.1 \newline It ignores the new line. print("Python1 \
Python2 \
Python3")Output:
Python1 Python2 Python3
2. \\ Backslash print("\\")Output:
\
3. \' Single Quotes print('\'')Output:
'
4. \\'' Double Quotes print("\"")Output:
"
5 \b ASCII Backspace(BS) print("Hello \b World")Output:
Hello World
6 \n ASCII Linefeed print("Hello \n World!")Output:
Hello
World!
7 \r ASCII Carriege Return(CR) print("Hello \r World!")Output:
World!
8 \t ASCII Horizontal Tab print("Hello \t World!")Output:Hello
World!
9. \v ASCII Vertical Tab print("Hello \v World!")Output:Hello
World!
Functions of string
• capitalize( ) function
The capitalize() function returns a string where the
first character is the upper case.
• lower( ) function
The lower() function returns a string where all the
characters in a given string are lower case
• title( ) function
The title() function returns a string where the first
character in every word of the string is an upper
case. It is just like a header, or a title.
• upper( ) function
The upper() function returns a string where all
the characters in a given string are in the upper
case
• casefold( ) function
The casefold() function returns a string where
all the characters are lower case.
• count( ) function
The count() function finds the number of times
a specified value(given by the user) appears in
the given string
• string = 'abc and abd'
• print(string.capitalize())

• string = "Hi How Are You"


• print(string.lower())

• string = "this is an example of title "


• print(string.title())

• string = "Analytics Vidhya is the Largest Data Science Community"


• print(string.casefold())

• string = "change this to upper case"


• print(string.upper())

• string = "how do you do"


• print(string.count("do"))
Slicing a String

• If S is a string, the expression S [ start : stop :


step ] returns the portion of the string from
index start to index stop, at a step size step.
• S = 'ABCDEFGHI'
print(S[2:7]) # o/pCDEFG
• S = 'ABCDEFGHI'
print(S[-7:-2]) # o/p- CDEFG
• S = 'ABCDEFGHI‘
print(S[2:-5]) # CD
• Specify Step of the Slicing
You can specify the step of the slicing
using step parameter. The step parameter is
optional and by default 1.
• # Return every 2nd item between position 2
to 7 S = 'ABCDEFGHI‘
• print(S[2:7:2]) # CEG
• # Returns every 2nd item between position 6
to 1 in reverse order
S = 'ABCDEFGHI‘
print(S[6:1:-2]) # GEC
• Slice at Beginning & End
Omitting the start index starts the slice from the
index 0. Meaning, S[:stop] is equivalent
to S[0:stop]
# Slice first three characters from the string
S = 'ABCDEFGHI'
print(S[:3]) # ABC
• Whereas, omitting the stop index extends the
slice to the end of the string.
Meaning, S[start:] is equivalent
to S[start:len(S)]
# Slice last three characters from the string
S = 'ABCDEFGHI'
print(S[6:]) # GHI
Reverse a String-
• S = 'ABCDEFGHI' print(S[::-1]) # IHGFEDCBA
Taking Input in Python
• In Python, Using the input() function, we take
input from a user, and using the print() function,
we display output on the screen. Using
the input() function, users can give any
information to the application in the strings or
numbers
• input(prompt): To accept input from a user.
• print(): To display output on the console/screen.
• format.
name = input("Enter your Name: ")
age = input("Enter age: ")
organization = input("Enter organization name: ")
# Display all values on screen
print("\n")
print("Printing your Details")
print("Name", "Age", "Organization")
print(name, age, organization)
Operators in Python

• Python language supports the following types of


operators.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators a=30 b=10
Arithmetic Operators
Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 40

- Subtraction Subtracts right hand operand from left hand operand. a – b = -20

* Multiplication Multiplies values on either side of the operator a * b = 300

/ Division Divides left hand operand by right hand operand a/b = 3

% Modulus Divides left hand operand by right hand operand and returns remainder a%b=0

** Exponent Performs exponential (power) calculation on operators a**b =30 to the power 10

// Floor Division - The division of operands where the result is the quotient in 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0
which the digits after the decimal point are removed. But if one of the
operands is negative, the result is floored, i.e., rounded away from zero
(towards negative infinity) −
Comparison Operators
Operator Description Example

== If the values of two operands are equal, then the (a == b) is not true.
condition becomes true.

!= If values of two operands are not equal, then condition (a != b) is true.


becomes true.

<> If values of two operands are not equal, then condition (a <> b) is true. This is similar to != operator.
becomes true.

> If the value of left operand is greater than the value of (a > b) is not true.
right operand, then condition becomes true.

< If the value of left operand is less than the value of right (a < b) is true.
operand, then condition becomes true.

>= If the value of left operand is greater than or equal to the (a >= b) is not true.
value of right operand, then condition becomes true.

<= If the value of left operand is less than or equal to the (a <= b) is true.
value of right operand, then condition becomes true.
Assignment Operators
= Assigns values from right side operands to left side operand
c = a + b assigns value of a + b into c

+= Add AND It adds right operand to the left operand and assign the result to left
operand
c += a is equivalent to c = c + a

-= Subtract AND It subtracts right operand from the left operand and assign the result
to left operand
c -= a is equivalent to c = c - a

*= Multiply AND It multiplies right operand with the left operand and assign the result
to left operand
c *= a is equivalent to c = c * a

/= Divide AND It divides left operand with the right operand and assign the result to
left operand
c /= a is equivalent to c = c / a

%= Modulus AND It takes modulus using two operands and assign the result to left
operand
c %= a is equivalent to c = c % a

**= Exponent AND Performs exponential (power) calculation on operators and assign
value to the left operand

c **= a is equivalent to c = c ** a

//= Floor Division It performs floor division on operators and assign value to the left
operand
c //= a is equivalent to c = c // a
Bitwise Operators
Operator Description Example
a=60 b=13

& Binary AND Operator copies a bit to the result if it exists in


both operands (a & b) (means 0000 1100)

| Binary OR It copies a bit if it exists in either operand.


(a | b) = 61 (means 0011 1101)

^ Binary XOR It copies the bit if it is set in one operand but


not both. (a ^ b) = 49 (means 0011 0001)

~ Binary Ones
Complement (~a ) = -61 (means 1100 0011 in 2's
It is unary and has the effect of 'flipping' bits. complement form due to a signed binary
number.

<< Binary Left The left operands value is moved left by the
Shift number of bits specified by the right operand.
a << 2 = 240 (means 1111 0000)

>> Binary Right The left operands value is moved right by the
Shift number of bits specified by the right operand.
a >> 2 = 15 (means 0000 1111)
Logical Operators

Operat Description Example


or

and If both the operands are true (a and b) is true.


Logical then true.
AND

or True if either of the operands (a or b) is true.


Logical is true.
OR

not Used to reverse the logical Not(a and b) is false.


Logical state of its operand.
NOT
Membership Operators

Operat Description Example


or

in Evaluates to true if it finds a


variable in the specified x in y, here in results in a 1 if
sequence and false otherwise. x is a member of sequence
y.

not in Evaluates to true if it does not x not in y, here not in results


finds a variable in the in a 1 if x is not a member of
specified sequence and false sequence y.
otherwise.
Identity Operators
Operat Description Example
or

is Evaluates to true if the


variables on either side of the
operator point to the same x is y, here is results in 1 if
object and false otherwise. id(x) equals id(y).

is not Evaluates to false if the


variables on either side of the
x is not y, here is not results
operator point to the same
in 1 if id(x) is not equal to
object and true otherwise.
id(y).
1
PRECEDENCE
**
Exponentiation (raise to the power)

2 ~+-
Complement, unary plus and minus (method names for the last two are +@ and -@)

3 * / % //
Multiply, divide, modulo and floor division

4 +-
Addition and subtraction

5 >> <<
Right and left bitwise shift

6 &
Bitwise 'AND'

7 ^|
Bitwise exclusive `OR' and regular `OR'

8 <= < > >=


Comparison operators

9 <> == !=
Equality operators

10 = %= /= //= -= += *= **=
Assignment operators

11 is is not
Identity operators

12 in not in
Membership operators

13 not or and
Logical operators

You might also like