Sunday, 19 November 2017

Python basics


Python Identifiers

Identifier is the name given to entities like class, functions, variables etc. in Python. It helps differentiating one entity from another.

Rules for writing identifiers

  1. 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 myClassvar_1 and print_this_to_screen, all are valid example.
  2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
  3. Keywords cannot be used as identifiers.
 global=1(incorrect variable decalration)
4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.
5.Identifier can be of any length.
Python is a case-sensitive language. This means, Variable and variable are not the same. Always name identifiers that make sense.Multiple words can be separated using an underscore, this_is_a_long_variable.
We can also use camel-case style of writing, i.e., capitalize every first letter of the word except the initial word without any spaces. For example: camelCaseExample

Python Statement

Instructions that a Python interpreter can execute are called statements. For example, a = 1is 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, 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
This is 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)
Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case with [ ] and { }. For example:
colors=['red',
'blue',
'yellow']

Python Comments::

Comments are very important while writing a program. It describes what's going on inside a program so that a person looking at the source code does not have a hard time figuring it out. In Python, we use the hash (#) symbol to start writing a comment.

#decalre variable x
x='hello python'

Multi-line comments

If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the beginning of each line. For example:
#this basics of
# python multiline 
#description
Another way of doing this is to use triple quotes, either ''' or """.
""" how comment code in python """

Python Variables:

A variable is a location in memory used to store some data (value).They are given unique names to differentiate between different memory locations. In Python, we simply assign a value to a variable and it will exist. We don't even have to declare the type of the variable. This is handled internally according to the type of value we assign to the variable.Every variable in Python is an object.
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to the variables, you can store integers, decimals or characters in these variables.Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable.
x = 123    # integer
x = 123L   # long integer
x = 3.14    # double float
x = "hello"    # string
x = [0,1,2]    # list
x = (0,1,2)    # tuple
x = open(‘hello.py’, ‘r’)  # file
Multiple Assignment:
Python allows you to assign a single value to several variables simultaneously.
eg:x=y=z=3

You can also assign multiple objects to multiple variables.
ex:a,b,c,d=1,2,3,'python'

Python Data types:There are various data types in Python

Numbers:here are three distinct numeric types: integersfloating point numbers, and complex numbers

integer numbers: Declare both +ve and -ve value sot variables:
eg:x=123,y=-34
Floating numbers:(floating point real values):
ex: f=0.1,abc=14.9,d=-12.09
complex nubmers:A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are real numbers and j is the imaginary unit.
ex: a=1+2j

We can use the type() function to know which class a variable or a value belongs to and the isinstance() function to check if an object belongs to a particular class.

a = 5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j

print(a, "is complex number?", isinstance(1+2j,complex))


Strings : Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows either pair of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 to the end.you can access its elements using index.
To remove string from pyhton: del nameofVariable

The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator.

  List: List is an ordered sequence of items. It is one of the most used datatype in Python and is very flexible. All the items in a list do not need to be of the same type.
Declaring a list is pretty straight forward. Items separated by commas are enclosed within brackets [ ].A list contains items separated by commas and enclosed within square brackets ([]).Lists are mutable.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.

You can also add new items at the end of the list, by using the append() method ,len(),etc available in python api (refer python web site https://docs.python.org/3/tutorial/introduction.html#lists).

Tuple: Tuple is created by placing all the items (elements) inside a parentheses (), separated by comma. The parentheses are optional but is a good practice to write it.
The difference between the tuple and list is that we cannot change the elements of a tuple once it is assigned whereas in a list, elements can be changed.
Tuples are immutable which means you cannot update or change the values of tuple elements.

ex: t=12345,54321,'hello!' # bad pratice (but out put should showing with      paranthesis)
   t=(12345,54321,'hello!') # goodpratice
Indexing :We can use the index operator [] to access an item in a tuple where the index starts from 0.The index must be an integer, so we cannot use float or other types. This will result into TypeError.
Negativeindex:Python allows negative indexing for its sequences.The index of -1 refers to the last item, -2 to the second last item and so on.
Slicing :We can access a range of items in a tuple by using the slicing operator - colon ":".
We can use + operator to combine two tuples. This is also called concatenation.We can also repeat the elements in a tuple for a given number of times using the * operator.Both + and * operations result into a new tuple.
# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4, 5, 6))
# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)
 Delete tuple:deleting a tuple entirely is possible using the keyword del.
my_tuple = ('p','r','o','g','r','a','m','i','z')
del my_tuple


all()Return True if all elements of the tuple are true (or if the tuple is empty).
any()Return True if any element of the tuple is true. If the tuple is empty, return False.
enumerate()Return an enumerate object. It contains the index and value of all the items of tuple as pairs.
len()Return the length (the number of items) in the tuple.
max()Return the largest item in the tuple.
min()Return the smallest item in the tuple
sorted()Take elements in the tuple and return a new sorted list (does not sort the tuple itself).
sum()Retrun the sum of all elements in the tuple.
tuple()Convert an iterable (list, string, set, dictionary) to a tuple.

Dictionary: Use {} curly brackets to construct the dictionary, and [] square brackets to index it. Separate the key and value with colons : and with commas , between each pair. Keys must be quoted As with lists we can print out the dictionary by printing the reference to it.A dictionary maps a set of objects (keys) to another set of objects (values).
A Python dictionary is a mapping of unique keys to values.
To explicitly remove an entire dictionary, just use the del statement.
Properties of Dictionary Keys
There are two important points while using dictionary keys
  • More than one entry per key is not allowed ( no duplicate key is allowed)
  • The values in the dictionary can be of any type while the keys must be immutable like numbers, tuples or strings.
  • Dictionary keys are case sensitive- Same key name but with the different case are treated as different keys in Python dictionaries.
Copying dictionary:
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
Boys = {'Tim': 18,'Charlie':12,'Robert':25}
Girls = {'Tiffany':22}
studentX=Boys.copy()
studentY=Girls.copy()
print( studentX)
print( studentY)

Updating Dictionary:

You can also update a dictionary by adding a new entry or a key-value pair to an existing entry or by deleting an existing entry. Here in the example we will add another name "Sarah" to our existing dictionary.
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
Dict.update({"Sarah":9})
print (Dict)
Delete Keys from the dictionary:
Python dictionary gives you the liberty to delete any element from the dictionary list. Suppose you don't want the name Charlie in the list, so you can delete the key element by following code.
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
del Dict ['Charlie']
print (Dict)
Dictionary are mutable. We can add new items or change the value of existing items using assignment operator.
Set :A set is created by placing all the items (elements) inside curly braces {}, separated by comma or by using the built-in function set().
You can get the number of elements in the set using the function len.
# set of integers
my_set = {1, 2, 3}
print(my_set)
# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)

 Operations with elements

You can get the number of elements in the set using the function len.
You can also iterate over all the elements of the set (in an undefined order!) using the loop for:
primes = {2, 3, 5, 7, 11}
for num in primes:
    print(num)
You can check whether an element belongs to a set using the keyword in: expressions like a in A return a value of type bool. Similarly there's the opposite operation not in. To add an element to the set there is the method add:A = {1, 2, 3}
print(1 in A, 4 not in A)
A.add(4)
A | B
A.union(B)
Returns a set which is the union of sets A and B.
A |= B
A.update(B)
Adds all elements of array B to the set A.
A & B
A.intersection(B)
Returns a set which is the intersection of sets A and B.
A &= B
A.intersection_update(B)
Leaves in the set A only items that belong to the set B.
A - B
A.difference(B)
Returns the set difference of A and B (the elements included in A, but not included in B).
A -= B
A.difference_update(B)
Removes all elements of B from the set A.
A ^ B
A.symmetric_difference(B)
Returns the symmetric difference of sets A and B (the elements belonging to either A or B, but not to both sets simultaneously).
A ^= B
A.symmetric_difference_update(B)
Writes in A the symmetric difference of sets A and B.
A <= B
A.issubset(B)
Returns true if A is a subset of B.
A >= B
A.issuperset(B)
Returns true if B is a subset of A.
A < B
Equivalent to A <= B and A != B
A > B
Equivalent to A >= B and A != B



No comments:

Post a Comment