### Operators, Precedence and Expression Evaluation

Operators are special symbols which represents computation. They are applied on operand(s), which can be values(constants) or variables. Same operator can behave differently on different data types. Operators when applied on operands form an expression Operators are categorized as

Arithmetic
Relational
Logical
Assignment.

Mathematical/Arithmetic Operators

 Symbol Description Example 1 Example 2 + Addition >>>55+45 100 >>> “Good” + “Morning” GoodMorning - Subtraction >>>55-45 10 >>>30-80 -50 * Multiplication >>>55*45 2475 >>> “Good” * 3 GoodGoodGood / Division >>>17/5 3 >>>17/5.0 3.4 >>> 17.0/5 3.4 >>>28/3 9 % Remainder/ Modulo >>>17%5 2 >>> 23%2 1 ** Exponentiation >>>2**3 8 >>>16**.5 4.0 >>>2**8 256 // Integer Division >>>7.0//2 3.0 >>>3/ / 2 1

Relational Operators

 Symbol Description Example 1 Example 2 < Less than >>>7<10 True >>>'Goodbye'< 'Hello' True > Greater than >>>7>5 True >>>'Goodbye'> 'Hello' False <= less than equal to >>> 2<=5 True >>>”Hello”<= “Goodbye” False >= greater than equal to >>>10>=10 True >>>‟Hello‟>= “Goodbye” True ! =, <> not equal to >>>10!=11 True >>>‟Hello”!= “HELLO” True == equal to >>>10==10 True >>>”Hello” == “Hello” True

Note: two values that are of different data type will never be equal to each other.

Logical Operators

 Symbol Description or If any one of the operand is true, then the condition becomes true. and If both the operands are true, then the condition becomes true. not Reverses the state of operand/condition.

Assignment Operators
Assignment Operator combines the effect of arithmetic and assignment operator

 Symbol Description Example Explanation = Assigned values from right side operands to left variable >>>x=12 >>>y=‟greetings‟ x=12 += added and assign back the result to left operand >>>x+=2 x=x+2 x=14 -= subtracted and assign back the result to left operand x-=2 x will become 10 *= multiplied and assign back the result to left operand x*=2 x will become 24 /= divided and assign back the result to left operand x/=2 x will become 6 %= taken modulus using two operands and assign the result to left operand x%=2 x will become 0 **= performed exponential (power) calculation on operators and assign value to the left operand x**=2 x will become 144 //= performed floor division on operators and assign value to the left operand x / /= 2 x will become 6

Note:
1. Same operator may perform a different function depending on the data type of
the value to which it is applied.
Eg: print “python”*3  will print pythonpythonpython
print 2*3  will print 6.
2. Division operator  “/ behaves differently on integer and float values
Eg; print 3/2 will print 1
print 3.0/2 will print 1.5

Expressions

Expressions are combinations of values ( constants) variables and operators.
Eg: 2+ x * y
math.pi * r ** 2

An expression in which different data types are used is called mixed type expression.
Eg: 3.5/2+(6.4-2)

When mixed type expressions are evaluated, Python promotes the result of lower data type to higher data type( i.e. to float in the above example). This automatic type conversion is known as implicit type casting or coercion. For the mathematical operators, if either operand is a float, the other is automatically converted to a float.
Eg: >>>1/2               >>>1.0/2
0                      0.5

We can also convert one data type into another using explicit type conversion. Python provides built in functions to convert one type to another.
Eg: >>>1/2               >>>float(1)/2
0                      0.5

int function can convert string and float to integers
>>> int(3.99999)
3
>>> int(-2.3)
-2
>>> int("32")
32

The float function converts integers and strings to floating-point numbers:
>>> float(32)
32.0
>>> float("3.14159")
3.14159
Finally, the str function converts to type string:
>>> str(32)
’32’
>>> str(3.14149)
’3.14149’

Note: It may seem odd that Python distinguishes the integer value 1 from the floating point value 1.0. They may represent the same number, but they belong to different types. The reason is that they are represented differently inside the computer.

Operator precedence

When we have an expression consisting of several operators how does Python decide the order of operations? It is done based on precedence of operator. Higher precedence operator is worked on before lower precedence operator.

Operator associativity determines the order of evaluation when they are of same precedence and are not grouped by parenthesis. Parenthesis has high precedence.

An operator may be Left-associative or Right –associative. In left associative, the operator falling on left side will be evaluated first, while in right assosiative operator falling on right will be evaluated first.

Note: In python “= and “** are Right Associative.

Precedence of operator - Listed from high precedence to low precedence.

Operator                                           Description
**                                                         Exponentiation (raise to the power)
+ , -                                                     Unary plus and minus
* , /, %, //                                         Multiply, divide, modulo and floor division
+ , -                                                     Addition and subtraction
<, <=, >, >=                                       Comparison operators
==, !=                                                  Equality operators
% =, / =, // = , -=,+=,*=                 Assignment operators
not and or                                          Logical operators

Note: Remember precedence of operators is applied to find out which sub expression
should be evaluated first.
Examples:
>>>2+3**2
11
here 3**2 will be evaluated first because it is having high precedence. So 2+9=11 will be the result.

>>>2**3**2
512
Here 3**2 will be evaluated first because the associativity is from right to left. So 2**9=512 will be the result.

>>>2+3/2*4**2
18

Here the sub expression 4**2 will be evaluated first because ** having high precedence. So the expression becomes 2+3/2*16. Now we have two operators / and * having same precedence. The associativity is from left to right so division will be done first. The expression become 2 + 1 * 16 after integer division. Now we have two operators + and * .But * is having high precedence so multiplication will be done first followed by the addition and the final result become 18.

### Strings in Python

Strings are compound data type made of sequence of characters. Hence from the string, the individual charters can also be directly accessed. Strings are created by using single quotes or double quotes or triple quotes.
Example: >>>s1="Python Programming" >>>s2='Python Programs' >>>s3="""Python is a powerful Programming language"""
This will create a string object s1, s2 and s3 using different forms.
Individual characters can be accessed using different subscripts( +ve or –ve) with the string object.
Example >>>s="Python" >>>s ‘P’ >>>s ‘t’ >>>s ‘n’ >>>s[-1] ‘n’ >>>s[-3] ‘h’ >>>s[-6] ‘P’
We can also slice a string. Segment of a string is called a slice.
>>>s[1:3] ‘yt’
If the first index is not mentioned, the slicing will start from 0. >>>s[:3] ‘Pyt’
>>>s[2:6] ‘thon’
If the last index is not mentioned, the slicing will go till the end o…

### Files in Python , Exception handling

While a program is running, its data is in main memory. When the program ends, or the computer shuts down, data in memory disappears. To store data permanently, you have to put it in a file. Files are usually stored on a secondary storage device(hard disk, pen drive, DVD,CD etc). When there are a large number of files, they are often organized into directories (also called “folders”). Each file is identified by a unique name, or a combination of a file name and a directory name. By reading and writing files, programs can exchange information with each other and generate printable formats like PDF. Working with files is a lot like working with books. To use a book, you have to open it. When you’re done, you have to close it. While the book is open, you can either write in it or read from it. In either case, you know where you are in the book. Most of the time, you read the whole book in its natural order, but you can also skip around. All of this applies to files as well. To open a fil…

### Classes and Objects in Python

Python is an object-oriented programming language, which means that it provides features that support object-oriented programming. The basic components of object oriented programming are classes and objects. A Class is a blue print to create an object. It provides the definition of basic attributes and functions of objects. Object is a running instance of the class having the identity(name), properties( values) and behaviors(functions). The Object oriented program thus consist of object definitions (classes) and most of the computations and functions are mentioned as operations on the object. Each object definition corresponds to some object or concept in the real world, and the functions that operate on these object correspond to the ways real-world objects interact. We have learned objects of string, list, tuple etc…and used the properties and functionalities of these objects which are built into the Python. Now we are going to create our own(user defined) objects. The class provides basic…