Skip to content

Instantly share code, notes, and snippets.

@sirusdas
Created March 5, 2018 05:56
Show Gist options
  • Save sirusdas/1b6dfc37e22574e458268cc2469d8f4b to your computer and use it in GitHub Desktop.
Save sirusdas/1b6dfc37e22574e458268cc2469d8f4b to your computer and use it in GitHub Desktop.
A list of few useful python commands

#Find power

  >>> pow(2,3)
  8

#Find max

  >>> max(2**11,409-9,1024*0)
  400

#import a file and use its functions using python terminal

  >>> from test import *
  >>> print_10_numbers()
NOTE: "test" is a python file that has print_10_numbers() method defined in it.
      The below will output the 10 numbers from 1-10.

#print statement

  >>> print " A ",
  >>> print "true"  if(a==b) else "false"
NOTE: Comma (,) in the end denotes that the next print will append.

#Pass function as an argument

  >>>print doto(7, f)
NOTE: Here "doto and f" both are functions. The code structure will be
  def f(x):
      return x*x

  def g(x):
      return x%x

  def doto(value, func):
      return func(value)

#Triple quoted strings

  >>>print '''"Ooo Yes", She exclaimed, "That's what an event horizon looks like!"'''
              OR
  >>> """'Hari's friend said, 
  ... "Hari seems very happy today!"'"""
NOTE: You can use either ' or " quotes and inside it you can use both single and double quotes. 
      The triple dots(...) are used to continue on next line.

#Unit testing

  >>>python file_name.py -v
NOTE: The above code will perform unit testing but provided you have the required format given below
  def is_divisible_by_2_or_5(n):
  """
      >>> is_divisible_by_2_or_5(8)
      True
  """
  return True

  if __name__ == '__main__':
      import doctest
      doctest.testmod()
        If we run it now, there will be no output, which indicates that the test passed. Note again that the doctest string must be placed immediately

after the function definition header in order to run.

        To see more detailed out put, call the script with the -v command line option

#Dictionary

  Eg: >>> Dict = {'suresh': 1, 'Sirus': 2} // Initialize a dictionary
      >>> del Dict['Sirus'] // Delete an element from a dictionary
      >>> Dict['Sirus'] // Show the value associated with the element. Here the output will be 2
      >>> Dict.clear() // Clear elements from a dictionary
      >>> Dict.keys() // Displays all the keys in the dictionary. Here the output will be dict_keys(['Suresh', 'Sirus'])
      >>> Dict.values // Displays all the values.
      >>> Dict2={"Sure":4,"Siru":5,"Tut":6}
      >>> Dict.update(Dict2) // Merge Dict with Dict2. Here the output will be {'Suresh': 1, 'Sirus': 2, 'Sure': 4, 'Siru': 5, 'Tut': 6}
      
    >>>print Dict.keys() // Will print all the keys

    >>>Dict['OMG']= 'Why' // Add an element into dictionary and update.

#Tuple( Similar to Dictionary but without options of delete or append) but you can re-initialize it with new set. Its more like an array with fixed values.

  Eg: >>> tup = ("suresh",1, "sirus",2)
      >>> tup[0] //output: 'suresh'
      >>> tup[1:3] //Slicing operation and output: (1, 'sirus')

#List

  >>> x=[1,'avs',2,3,4,'xyz']
  >>> x.remove('avs')
  >>> x.append('avs')

#For Loop

  >>> x= ('a','b','c','d')
  >>> for i in x:
  ... print i

#Enumerate( Works like for loop)

  >>> x= 'this is a string'
  >>> for index,value in enumerate(x):
  ... if c == 's': print 'index {} is an s'.format(index)

#else(Can be used with for, while or if loops)

#is

  >>> x,y = [5],[5]
  >>> x==y
  True
  >>> x is y
  False
NOTE: This is because every variable is given a specific id to identify it. For every list a different id is given. But below code is also true
  >>> x,y = 5,5
  >>> x==y
  True
  >>> x is y
  >>> True
//Since their id's where same as they had same value.

#boolean operation

  >>> x,y = 'one','two'
  >>> x<y
  True

#list

  >>> list = [1,2,3,4,5,6,7,8,9,10]
  >>> list[0]
  1

  >>> list[0:5]
  1 2 3 4 5

  >>> list[0:10:2]
  1 3 5 7 9

  >>> list[0:10:2] = (99,99,99,99,99)
  >>> list
  [99,2,99,4,99,6,99,8,99,10]

  >>> list[:] = range(100)
  //Will display a list of number from 0-100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment