Posts

Showing posts from 2018

The dir Function

dir()      The built-in dir() lists names from modules. It returns a sorted list of strings.      Let's import regular expression module:- >>> import re >>> dir(re) ['DEBUG', 'DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'S', 'Scanner', 'T', 'TEMPLATE', 'U', 'UNICODE', 'VERBOSE', 'X', '_MAXCACHE', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__version__', '_alphanum', '_cache', '_cache_repl', '_compile', '_compile_repl', '_expand', '_pattern_type', '_pickle', '_subx', 'compile', 'copy_reg', 'error', 'escape', 'findall', 'finditer', 'match', 'purge', 'search', 'split', ...

Python Modules

Modules      A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Let's understand this by taking example,      We will write module for fibonacci Series. def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print b, a, b = b, a+b def fib2(n): # return Fibonacci series up to n result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return result      You can import this like:- import fibo Use like this >>> fibo.fib(1000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 >>> fibo.fib2(100) [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]      A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. Or you can import specific method o...

Python Dictionaries

Dictionaries      A dictionary is unordered set of key:value pairs, with unique keys enclosed within {} brackets.      It can be initialized as d1 = {} d2 = dict() d3 = dict(key1=value1, key2=value2,…,keyN=valueM) d4 = dict(some_iterable) d5=dict(mapping_object) There are following methods dictionary object has:- dict.clear()      Removes all items from the dictionary and return None. dict.copy()      Returns shallow copy of dictionary. dict.fromkeys(k [,v])      Creates new dictionary with keys from k and optionally taking values equal to v, and v Defaults to None. dict.get(k, d)      Returns value from dictionary whose key equal to k, else returns d, and d Defaults to None. dict.has_key(k)      Returns true if dictionary has key k else False. NOTE: It is Removed From 3.x Version of Python dict.items()  ...

Sets in Python

Sets      A set is unordred collection of items with no duplicate. It can be used to eliminating duplicates or membership testing. Set also supports union, intersection, difference and symmetric difference. Set can be initialized using set().      Set can be initialized using set(). set1 = set() Set has following methods set.add(element)      Add element to set. If element already present nothing happens. set.clear()      Remove all elements and clear the set. set.copy()      Returns shallow copy set. set.difference(another_set[s])      Returns the difference of two or mor e sets as new set. set.difference_update(another_set)      Remove all elements of another from this set. set.discard(element)      Remove an element from set if is a member. set.intersection(another_set[s])   ...

Python Tuples

Tuple      This data structure of python is immutable like array. We can't update it after initialization.      Tuple is initialized using tuple class or (). tuple1 = tuple() tuple2 = () tuple3 = value1, value2,...,valueN Below are some methods of tuple object tuple.count(value)      Returns number of time value appears in tuple. tuple.index(value, [start, [stop]])      Returns first index of value or raises ValueError if value not present. It optionally take two more parameters start and stop and searches value in between start and stop. Lets Understand this by taking Example >>> t=tuple() >>> t () >>> t = (19, 3, 7, 5, 2, 8) >>>  t (19, 3, 7, 5, 2, 8) >>> 19 in t True >>> t[3:5] (5, 2) >>> len(t) 6 >>> t.count(3) 1 >>>  t.index(3) 1 Keep Following, For More....

Python List

List      List is data structure in python more like array in c or java. But in python list is mutable.      List is initialized in python using list class or just []. list1 = [] list2 = list() Below are some methods of list object list.append(item)      Add an Item to end of the list. list.count(item)      Returns number of time item appears in the list. list.extend(anotherList)      Extend the list by appending all the items from the given list. list.index(item, [start], [end])      Returns the first index of value. If specified optional arguments start or end, the item is searched within start and end. Raises ValueError if item not present. list.insert(index, item)      Insert an item at a given position, the element is inserted before the index. list.pop([index])      Remove an item from the ...

Defining Funtions And The range() Function

Defining Functions      We can define function by using def keyword, the function definition written by using def keyword with function name followed by parameters enclosed by simple parenthesis or can be blank. The next statement is at next line with indent. It can have docstring. Example:      Lets write function for checking number is prime or not. >>> def check_prime(num): ...  is_prime = True ...  for index in range(2, num): ...  if num % index == 0: ...  is_prime = False ...  break ...  index += 1 ...  if is_prime: ...  print "Given Number is Prime" ...  else: ...  print "Given Number is Not Prime" ... >>> check_prime(9) Given Number is Prime >>> check_prime(8) Given Number is Not Prime      Function parameters can have Default Argument, Variable Number ...

break, continue, pass Statements

break Statement     break can used to break the loops like for, while Example >>> for i in range(10): ...        if i%2 == 0: ...          break ...  continue Statement     continue can be used take control to starting of loop Example >>> for i in range(10): ...        if i%2 != 0: ...          continue ... pass Statement     pass can be used when statement require but without action, like we base class that provides base for inheriting class Example >>> def foo(): ...        pass

Loops From Python

     In Python, There are loops like for and while, Let's See them in detail. for Loop      The for statement from python iterates over any sequence it may be string or list. Syntax: for iterator in sequence: statement1 statement2 ... Example: >>> a = 3 >>> for char in 'python': ...  print char ...  p y t h o n while Loop      The while statement from python is used to check condition and then iterate if condition evaluates True. Syntax: while condition: statement1 statement2 ... Example:      Let's we will write function that calculates Fibonacci series. >>>def fibo(limit): ...  a, b = 0, 1 ...  while a < limit: ...  print a, ...  a, b = b, a + b ... >>>fibo(10) 0 1 1 2 3 5 8      Get in touch for more fun,...

Control Flows From Python

     As Other Languages Python also has control flow Statements. They are as follows:- if Statement      It used to check condition according to it control program flow. Syntax: if condition: statement1 statement2 ... if..else Statement      It is used control flow according to condition, If condition evaluates to True, It will execute if block, else block otherwise. Syntax: if condition: statement1 statement2 ... else: statement1 statement2 ... Example: >>> a = 3 >>> b = 9 >>> if b > a: ...  print "B is Max" ... else: ...  print "A is Max" ...  B is Max if..elif..else Statement      Python Doesn't supports switch...case like C or Java, it is replaced with if - elif - else. It first checks if condition if it evaluates true it execu...