Posts

Showing posts from May, 2018

Python - Current Working Directory(pwd equivalent) and Script Location

To get the Present working directory use the below import os pwd = os . getcwd () ------------------------------------------------------------------------------------------- To get the full path to the directory a Python file is contained in, write following in the file: import os script_dir_path = os . path . dirname ( os . path . realpath ( __file__ )) (Note that above won't work if you've already used  os.chdir()  to change your current working directory since the value of the  __file__   is relative to the current working directory and is not changed by a os.chdir()  call.) --------------------------------------------------------------------------------------- Documentation references for the modules, constants, and functions used above: The  os  and  os.path  modules. The  __file__   os.path.realpath(path)  (returns  "the canonical path of the specified filename, eliminating any symbol...

Python - How to Take Input From User - Scanner Class equvivalent

x = int ( input ( "Please enter an integer: " ))

Python - How to Iterate over a list object

Traceback (most recent call last):   File "<pyshell#24>", line 1, in <module>     for i in range(a): TypeError: 'list' object cannot be interpreted as an integer >>>  To iterate over the indices of a sequence i.e. List, you can combine  range()  and  len()  as follows:  >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)): print(i,a[i]) 0 Mary 1 had 2 a 3 little 4 lamb however, it is convenient to use the function, enumerate() see  Looping Techniques .

Python - Lists

Lists are mutable 3.1.4. Lists Python knows a number of  compound  data types, used to group together other values. The most versatile is the  list , which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type. >>> squares = [ 1 , 4 , 9 , 16 , 25 ] >>> squares [1, 4, 9, 16, 25] Like strings (and all other built-in  sequence  type), lists can be indexed and sliced: >>> squares [ 0 ] # indexing returns the item 1 >>> squares [ - 1 ] 25 >>> squares [ - 3 :] # slicing returns a new list [9, 16, 25] All slice operations return a new list containing the requested elements. This means that the following slice returns a new (shallow) copy of the list: >>> squares [:] [1, 4, 9, 16, 25] Lists also supports operations like concatenation: >...

Python - Strings

Strings are immutable - once created cannot be changed - in the background every declaration creates pyStringObject In the interactive interpreter, the output string is enclosed in quotes and special characters are escaped with backslashes. While this might sometimes look different from the input (the enclosing quotes could change), the two strings are equivalent. The string is enclosed in double quotes if the string contains a single quote and no double quotes, otherwise it is enclosed in single quotes. The  print  statement produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters: String literals can span multiple lines. One way is using triple-quotes:  """..."""  or  '''...''' . End of lines are automatically included in the string, but it’s possible to prevent this by adding a  \  at the end of the line. The following example: If you don’t want characters prefac...

Python - Function - Default values of Arguments

Default Argument Values The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example: def ask_ok ( prompt , retries = 4 , reminder = 'Please try again!' ): while True : ok = input ( prompt ) if ok in ( 'y' , 'ye' , 'yes' ): return True if ok in ( 'n' , 'no' , 'nop' , 'nope' ): return False retries = retries - 1 if retries < 0 : raise ValueError ( 'invalid user response' ) print ( reminder ) This function can be called in several ways: giving only the mandatory argument:  ask_ok('Do   you   really   want   to   quit?') giving one of the optional arguments:  ask_ok('OK   to   overwrite   the   file?',   2) or even giving all arguments:  as...

Python - Defining Functions

Defining Functions We can create a function that writes the Fibonacci series to an arbitrary boundary: >>> >>> def fib ( n ): # write Fibonacci series up to n ... """Print a Fibonacci series up to n.""" ... a , b = 0 , 1 ... while a < n : ... print ( a , end = ' ' ) ... a , b = b , a + b ... print () ... >>> # Now call the function we just defined: ... fib ( 2000 ) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 The keyword  def  introduces a function  definition . It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line, and must be indented. The first statement of the function body can optionally be a string literal; this string literal is the function’s documentation string, or  docstring . (More about docstrings can be found in the ...

Python - Control Flow Statement - For Loop - Range Function

for  Statement The  for  statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s  for  statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example  >>> >>> # Measure some strings: ... words = [ 'cat' , 'window' , 'defenestrate' ] >>> for w in words : ... print ( w , len ( w )) ... cat 3 window 6 defenestrate 12 If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient: >>> >...