Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Sunday, February 17, 2019

Python Basics : Operators

The general purpose of a program is to accept data and perform some operations on the data. The data in the program is stored in variables. The symbol that performs an operation on the data is called an operator.

An operator is a symbol that performs an operation. It acts on some variables called operands. For example, if we write
a + b
the operator '+' is acting on two operands 'a' and 'b'.

If an operator acts on a single variable, its called a unary operator If an operator acts on two variables, it is a binary operator etc. We can further classify operators upon their nature as below :

  • Arithmetic operators
  • Assignment operators
  • Unary minus operators
  • Relational operators
  • Logical operators
  • Boolean operators
  • Bitwise operators
  • Membership operators
  • Identity operators

Arithmetic operators

These operators are used to perform basic arithmetic operations like addition, subtraction, division etc. There are seven arithmetic operators available in Python :
  1. Addition operator ( a + b ) : Adds two values 'a' and 'b'
  2. Subtraction operator ( a - b ) : Subtracts 'b' from 'a'
  3. Multiplication operator ( a * b ) : Multiplies two values 'a' and 'b'
  4. Division operator ( a / b ) : Divides 'a' by 'b'
  5. Modulus operator ( a % b ) : Gives remainder of 'a' by 'b' division
  6. Exponent operator ( a ** b ) : Calculates exponential power value of 'a' to the power 'b'
  7. Integer division ( a // b ) : Performs division of 'a' by 'b' and gives only integer quotient.
Where there is an expression with several arithmetic operators, the order of evaluation is done based upon operator precedence in the order shown below :
  1. Parantheses
  2. Exponentiation
  3. Muliplication, Division, Modulus and Floor Divisions
  4. Addition, Subtraction
  5. Assignment operation
Note 1 : The operators with higher precedence will be executed first than of lower precendence.

Note 2 : When evaluating the expression with operators that have the same operator precedence ( for e.g., Multiplication and Division ), the order of evaluation is done from left to right. This is called Associativity. 

Assignment operators

These operators are useful to evaluate the expression on the right side and assign the value to the left side variable. The below are some variations of the assignment operator :

Assignment operator
z = x + y
Stores right side expression value ( i.e., the value of x+y ) into 'z'

Addition assignment operator
z+=x
This expression is similar to z = z + x. Adds 'x' to 'z' and stores the value in 'z'.

Subtraction assignment operator
z-=x
This expression is similar to z = z - x. Subtracts 'x' from 'z' and stores the value in 'z'.

Multiplication assignment operator
z*=x
This expression is similar to  z = z * x. Multiplies 'x' with 'z' and stores the value in 'z'.

Division assignment operator
z/=x
This expression is similar to z = z / x. Divides 'z' by 'x' and stores the value in 'z'.

Modulus assignment operator
z%=x
This expression is similar to z = z % x. Divides 'z' by 'x' and stores the remainder value in 'z'.

Exponentiation assignment operator
z**=x
This expression is similar to z = z ** x. Performs power value and then stores the result into 'z'.

Floor division assignment operator
z//=x
This expression is similar to z = z // x. Performs floor division and then stores the result in 'z'.

Unary Minus Operator

 The unary minus operator is denoted by the symbol minus ( - ) and when this operator is used before a variable, its value is negated.

Relational Operators

Relational operators are used to compare two quantities. The below are the relational operators :

  • Greater than operator ( a > b ) : If 'a' is greater than 'b' returns True, else returns False.
  • Greater than or equal operator ( a >= b ) : If 'a' is greater than or equal to 'b' returns True, else returns False. 
  • Less than operator ( a < b ) : If 'a' is less than 'b' returns True, else returns False.
  • Less than or equal operator ( a <= b ) : If 'a' is less than or equal to 'b' returns True, else returns False.
  • Equals operator ( a == b ) : if 'a' equals 'b' returns True, else returns False.
  • Not equals operator ( a != b ) : if 'a' does not equal 'b' returns True, else returns False.
Relational operators are generally used to construct conditions in if statements.

Logical Operators

Logical operators are useful to construct compound conditions. A compound condition is a combination of more than one simple condition. Each of the simple condition is evaluated to True or False and then the decision is taken to know whether the total condition is True or False. In case of logical operators, False indicates and True indicates any other number.

The below are the logical operators :
  • and ( x and y ) : If x is False, x is returned. Else y is returned.
  • or ( x or y ) : If x is False, y is returned. Else x is returned.
  • not ( not x ) : If x is False, it returns True and vice versa.
Note : When 'and' is used, the total condition will become True only if both conditions are True. When using 'or' if any one condition is True, it will take the total compound condition as True.

Boolean Operators

There are two 'bool' type literals and they are True and False. Boolean operators act upon 'bool' type literals and they provide 'bool' type output.

The below are the boolean operators :
  • and ( x and y ) : Boolean and operator
  • or ( x or y ) : Boolean or operator
  • not ( not x ) : Boolean not operator
Note : Here 'x' and 'y' are boolean values i.e. either True or False.

Bitwise Operators

These operators act on individual bits ( 0 and 1 ) of the operands. The results given by these operators are always in the form of integers.

There are six types of bitwise operators :
  • Bitwise Complement operator ( ~ )
    • This operator gives the complement form of a given number. 
    • The complement form is obtained by changing 0's as 1's and vice versa.
  • Bitwise AND operator ( & )
    • This operator performs AND operation on the individual bits of numbers.
    • By multiplying the input bits, we can obtain the output bits.
  • Bitwise OR operator ( | )
    • This operator performs OR operation on the individual bits of numbers.
    • By adding the input bits, we can obtain the output bits.
  • Bitwise XOR operator ( ^ )
    • This operator performs XOR operation on the bits on numbers.
    • When we have odd number of 1's in the input bits, we can get the output bit as 1.
  • Bitwise Left shift operator ( << )
    • This operator shifts the bits of the number towards left a specified number of positions.
    • If we write x << n, the meaning is to shift the bits of x towards left n positions.
  • Bitwise Right shift operator ( >> )
    • This operator shifts the bits of the number towards right a specified number of positions.
    • If we write x >> n, the meaning is to shift the bits of x towards right n positions.
    • Bitwise right shift operator preserves the sign bit, which is the leftmost bit.

Membership Operators

The membership operators are useful to test for membership in a sequence such as strings, lists, tuples or dictionaries. There are two membership operators :
  • in : This operator returns True if an element is found in the specified sequence, else False is returned.
  • not in : This operator returns True if an element is not found in the sequence, else False is returned.

Identity Operators

These operators compare the memory locations of two objects. The memory location of an object can be seen using the id() function. This function returns an integer number, called the identity number that internally represents the memory location of the object. In Python, everything is considered an object. There are two identity operator :

  • is : The 'is' operator is useful to compare whether two objects are same or not by internally comparing the identity number of the objects. If they are same, True is returned. Else, False is returned.
  • is not : The 'is not' operator returns True if the identity numbers of two objects being compared are not same. Else False is returned.

Thursday, February 14, 2019

Python Basics : Introduction and Data Types

Introduction

Python is a popular, general-purpose high level programming language created by Guido van Rossum and developed by the Python Software Foundation. Python works on different platforms and has a simple syntax similar to english language. Being an interpreted language helps developers in prototyping quickly. It is a flexible language and it can be treated in a procedural, object-oriented or a functional way. Python is easily among the top programming languages according to github language trends.

Data Types in Python

A datatype represents the type of data stored into a variable or memory. The datatypes which are already available in Python language are called Built-in datatypes. The datatypes which can be created by the programmers are called User-defined datatypes.

Built-in datatypes

There are five types of built-in datatypes :

  • None Type
    • In Python, the 'None' datatype represents an object that does not contain any value. 
    • It is used inside a function as a default value of the arguments. Meaning, when calling a function, if no value is passed, then the default value is assumed to be 'None'. 
    • In Boolean expressions, 'None' datatype represents 'False'.
  • Numeric Types
    • The Numeric data type represents numbers and is further classified into the below sub types:
      • int : This datatype represents an integer number. It does not contain any decimal point. In Python, there is no limit for the size of an int datatype.
      • float : The float datatype represents floating point numbers and contains a decimal point.
      • complex : It contains a complex number of the form 'a+bi', where a and b may contain integers or floats.
      • bool : The bool datatype represents boolean values. There are only two boolean values True or False and are internally represented as 1 and 0 respectively.
  • Sequences
    • A sequence represents a group of elements or items.
    • There are six types of sequences in Python :
      • str : In Python, str represents a string datatype. A string is a group of characters.
      • bytes : A byte datatype represents a group of byte numbers just like an array. A byte number is any positive integer from 0 to 255. An important property of byte array is that, we cannot modify or edit any element in the bytes type array. bytes() function is used to convert a list into bytes array.
      • bytearray : The bytearray datatype is similar to bytes datatype except that a bytes type array cannot be modified, whereas a bytearray type array can be modified. bytearray() function is used to convert a list into bytearray datatype.
      • list : A list represents a group of elements just like an array but unlike arrays, lists are capable of storing different types of elements. Lists can also grow dynamically in memory. Lists are represented using square brackets [].
      • tuple : A tuple is like a read-only list. It also contains a group of elements which can be of different type. The elements in a tuple are enclosed in parantheses (). Whereas list elements can be modified, it is not possible to modify the tuple elements.
      • range : The range datatype represents a sequence of numbers and the numbers in the range are not modifiable.  To create a range of numbers we can use the range() function. It is generally used for repeating a loop for a specific number of times.
  • Sets 
    • A set is an unordered collection of elements and the order of the set as entered is not maintained. A set also does not accept duplicate elements. 
    • There are two sub types of sets :
      • set datatype : A set is created by entering the elements separated by commas inside curly braces {}. set() function may also be used to create a set. Since sets are unordered, we cannot retrieve the elements using indexing or slicing operations. The update() method is used to add an element and the remove() method is used to remove a particular element from the set.
      • frozenset datatype : The frozenset datatype is the same as the set datatype except that the elements in a frozenset cannot be modified, hence update() and remove() methods will not work on frozenset datatype. We can create a frozenset by passing a set to frozenset() function.
  • Mappings
    • It represents a group of elements in the form of key value pairs so that when the key is given, we can retrieve the value associated with it. The key value pairs should be separated by a colon (:) and every pair should be separated by a comma (,) and enclosed inside curly brackets {}.
    • We can retrieve the value upon giving the key. For e.g., dict_name[key].
    • We can use keys() and values() method to retrieve only keys and values respectively.
    • We can use the del module to delete a key and the corresponding value. For e.g., del dict_name[key]
Literals in Python

A literal is a constant value that is stored into a variable in a program. In an assignment operation, like
a=10
'a' is the variable into which the constant value '10' is stored. The value '10' is the 'literal' here. Since 10 indicates an integer value, it is called an 'integer literal'.

The following types of literals are there in Python :

  • Numeric literals
    • These literals represent numbers. The different types of numeric literals available in Python are Integer, Float, Hexadecimal, Octal, Binary and Complex.
  • Boolean literals
    • Boolean literals are the True and False values stored into a bool type variable.
  • String literals
    • A group of characters is called a string literal and these literals are enclosed in single quotes (') or double quotes (") or triple quotes (''' or """). In Python, there is no difference between a single and double quoted string.
User defined datatype

The datatypes which are created by the programmers are called 'user-defined' datatypes like array, class or modules.

Constants

A constant is similar to a variable but its value cannot be modified in the course of program execution. In languages like C and Java, defining constants is possible, however, its not possible in Python. We can indicate that a variable is a constant by writing its name in all capital letters, but its value can be modified.

Identifiers and Reserved words

An identifier is a name that is given to a variable or function or class and it can include letters, numbers and underscore character (_). Identifiers should always start with a non-numeric character. Python is a case sensitive programming language and hence identifiers with the same name but different case sensitivity are treated as separate by Python.

Reserved words are the words that are already reserved for some particular purpose in Python language. Examples include and, del, in, continue etc.

Miscellaneous

  • To determine the datatype of a variable or object, we can use the type() function. 
  • Every datatype is treated as an object internally by Python. Every datatype, function, method, class, module, lists, sets, etc are all objects in Python.
  • Python does not have a char datatype to represent individual characters, unlike in programming languages like C or Java. To access individual characters in a string, we have to use the index or the position number.