User Tools

Site Tools


python_notes

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
python_notes [2023/05/19 20:26] – [Reading files] adminpython_notes [2024/01/03 22:15] (current) – [useful links] raju
Line 2: Line 2:
  
 ==== useful links ==== ==== useful links ====
 +  * [[https://tutswiki.com/python/exception-handling/ | exception handling in python]] (tutswiki.com)
 +    * very easy to follow; high information density; well thought out examples
   * [[https://www.programiz.com/python-programming/online-compiler/ | Online python compiler]] (programiz.com)   * [[https://www.programiz.com/python-programming/online-compiler/ | Online python compiler]] (programiz.com)
     * can be useful while doing live coding interviews.     * can be useful while doing live coding interviews.
   * [[https://nedbatchelder.com/text/names.html | Facts and myths about Python names and values]] (nedbatchelder.com) - well explained.   * [[https://nedbatchelder.com/text/names.html | Facts and myths about Python names and values]] (nedbatchelder.com) - well explained.
  
 +==== links to documentation ====
 +
 +  * os.path.basename - https://docs.python.org/3/library/os.path.html#os.path.basename
 +  * continue statement - https://docs.python.org/3/reference/simple_stmts.html#the-continue-statement
 ==== validate inputs ==== ==== validate inputs ====
 Sample snippet: Sample snippet:
Line 115: Line 121:
 </code> </code>
  
 +==== check if something is float ====
 +<code>
 +% python
 +Python 3.11.4 (main, Jul  5 2023, 13:45:01) [GCC 11.2.0] on linux
 +Type "help", "copyright", "credits" or "license" for more information.
 +>>> isinstance(12.0, float)
 +True
 +>>> isinstance(12.0, int)
 +False
 +>>> isinstance(12, float)
 +False
 +</code>
  
 +==== check if something is int ====
 +<code>
 +% python
 +Python 3.11.4 (main, Jul  5 2023, 13:45:01) [GCC 11.2.0] on linux
 +Type "help", "copyright", "credits" or "license" for more information.
 +>>> isinstance(12, int)
 +True
 +>>> isinstance(12, float)
 +False
 +>>> isinstance(12.0, int)
 +False
 +</code>
 +
 +==== Python comparisons ====
 +
 +<code>
 +$ python
 +Python 3.9.17 (main, Jul  5 2023, 20:47:11) [MSC v.1916 64 bit (AMD64)] on win32
 +Type "help", "copyright", "credits" or "license" for more information.
 +>>> 4 == True
 +False
 +>>> 1 == True
 +True
 +</code>
 +
 +==== Chained comparisons ====
 +Q: In Python ''3 < 4 == True'' evaluates to False.
 +
 +<code>
 +$ python
 +Python 3.9.17 (main, Jul  5 2023, 20:47:11) [MSC v.1916 64 bit (AMD64)] on win32
 +Type "help", "copyright", "credits" or "license" for more information.
 +>>> 3 < 4 == True
 +False
 +</code>
 +
 +Why?
 +
 +A: The ''<'' and ''=='' are comparison operators. If a, b, c, …, y, z are expressions and op1, op2, …, opN are comparison operators, then in python, a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.
 +
 +So ''3 < 4 == True'' is equivalent to ''3 < 4 and 4 == True'' which evaluates to ''True and False'' which turns out to be ''False''.
 +
 +Ref:-
 +  * https://docs.python.org/3/reference/expressions.html#comparisons - describes the above rule and also gives a list of comparison operators
 +
 +==== List of comparison operators ====
 +<code>
 +"<" | ">" | "==" | ">=" | "<=" | "!="
 +| "is" ["not"] | ["not"] "in"
 +</code>
 +
 +Ref:- https://docs.python.org/3/reference/expressions.html#comparisons
 ===== tasks ===== ===== tasks =====
   * [[get urls in a url]]   * [[get urls in a url]]
Line 121: Line 191:
  
 ===== difference between ===== ===== difference between =====
 +==== os.getenv vs. os.environ.get ====
 +What is the difference between os.getenv vs os.environ.get?
  
 +None. I prefer to use os.getenv as it is less number of characters to type.
 +
 +To experiment, use [[https://github.com/KamarajuKusumanchi/notebooks/blob/master/python/difference%20between%20os.getenv%20vs.%20os.environ.get.ipynb | difference between os.getenv vs. os.environ.get.ipynb]] (github.com/KamarajuKusumanchi).
 +
 +Sample usage from https://github.com/dpguthrie/yahooquery/blob/master/yahooquery/base.py#LL926C1-L936C1
 +<code>
 +    def __init__(self, **kwargs):
 +        ...
 +        username = os.getenv("YF_USERNAME") or kwargs.get("username")
 +        password = os.getenv("YF_PASSWORD") or kwargs.get("password")
 +        if username and password:
 +            self.login(username, password)
 +</code>
  
 ===== Snippets ===== ===== Snippets =====
Line 193: Line 278:
 ===== Reading files ===== ===== Reading files =====
 ==== read file into a list ==== ==== read file into a list ====
 +Given
 <code> <code>
-$ cat great.txt +$ cat -A great.txt 
-kamaraju +kamaraju$ 
-kamaraj +kamaraj $ 
-kamara +kamara  $ 
-kamar +kamar   $ 
-kama +kama    $ 
-kam +kam     $ 
-ka +ka      $ 
-k+      $
 </code> </code>
 +where the $ denotes the end of line.
 +<code>
 +$ du -b great.txt
 +72      great.txt
  
 +$ wc great.txt
 +  8 72 great.txt
 +</code>
 +
 +To read it
 <code> <code>
-In [2]: file = 'great.txt' +In [3]: 
-   ...: with open(file) as fh: +file = 'great.txt' 
-   ...:     contents = [line.rstrip() for line in fh] +with open(file) as fh: 
-   ...: print(contents) +    contents = [line.rstrip('\n') for line in fh] 
-['kamaraju', 'kamaraj', 'kamara', 'kamar', 'kama', 'kam', 'ka', 'k']+print(contents) 
 +['kamaraju', 'kamaraj ', 'kamara  ', 'kamar   ', 'kama    ', 'kam     ', 'ka      ', '      ']
  
-In [3]: len(contents) +In [4]: 
-Out[3]: 8+len(contents) 
 +Out[4]: 
 +8 
 +</code> 
 + 
 +Ref:- https://stackoverflow.com/questions/15233340/getting-rid-of-n-when-using-readlines 
 + 
 +You can also do it using readlines. 
 + 
 +<code> 
 +In [5]: 
 +file = 'great.txt' 
 +with open(file) as fh: 
 +    lines = fh.readlines() 
 +    lines = [line.rstrip('\n') for line in lines] 
 +print(lines) 
 +['kamaraju', 'kamaraj ', 'kamara  ', 'kamar   ', 'kama    ', 'kam     ', 'ka      ', '      '
 +</code> 
 + 
 +tags | file readlines strip newline 
 + 
 +Another approach is to use read() with splitlines(). 
 + 
 +<code> 
 +In [6]: 
 +file = 'great.txt' 
 +with open(file) as fh: 
 +    lines = fh.read().splitlines() 
 +print(lines) 
 +['kamaraju', 'kamaraj ', 'kamara  ', 'kamar   ', 'kama    ', 'kam     ', 'ka      ', '      '
 +</code> 
 + 
 +===== programming notes ===== 
 +==== which python executable am I running? ==== 
 +<code> 
 +import sys 
 +print(sys.executable) 
 +</code> 
 + 
 +For example 
 + 
 +<code> 
 +$ python 
 +Python 3.11.5 | packaged by Anaconda, Inc. | (main, Sep 11 2023, 13:26:23) [MSC v.1916 64 bit (AMD64)] on win32 
 +Type "help", "copyright", "credits" or "license" for more information. 
 +>>> import sys 
 +>>> print(sys.executable) 
 +C:\Users\kkusuman\AppData\Local\conda\conda\envs\py311\python.exe
 </code> </code>
  
python_notes.1684527999.txt.gz · Last modified: 2023/05/19 20:26 by admin