tag:blogger.com,1999:blog-70204112814903436542024-08-28T02:00:31.066-07:00Ken PythonicKenneth Parkerhttp://www.blogger.com/profile/13907305526364974493[email protected]Blogger16125tag:blogger.com,1999:blog-7020411281490343654.post-65250092643801780862019-08-06T11:12:00.003-07:002019-08-06T13:32:27.866-07:00nonlocal keywordThe <b>nonlocal</b> keyword is used to allow an inner function to access variables defined in an outer function. Without using the <b>nonlocal</b> keyword a new variable will be created in the inner function and will have no effect on the outer function's variables.<br /> <br /> The below example demonstrates this by defining two versions of s. The first <b>s</b> is accessible only to the outer function <i>say_hello</i> and the other <b>s</b> is only accessible to the inner function <i>say_it</i>.<br /> <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #008800; font-weight: bold;">def</span> <span style="color: #0066bb; font-weight: bold;">say_hello</span>(): s <span style="color: #333333;">=</span> <span style="background-color: #fff0f0;">"Hello from outer function say_hello"</span> <span style="color: #008800; font-weight: bold;">def</span> <span style="color: #0066bb; font-weight: bold;">say_it</span>(): s <span style="color: #333333;">=</span> <span style="background-color: #fff0f0;">"Hello from inner function say_it"</span> <span style="color: #008800; font-weight: bold;">print</span>(s) <span style="color: #008800; font-weight: bold;">print</span>(s) say_it() say_hello() </pre> </div> <br /> The below code demonstrates how to access the outer function's local variable <b>s</b>. By using the <b>nonlocal</b> keyword,&nbsp;<i>say_hello</i> and <i>say_it</i> are sharing the variable <b>s</b>.<br /> <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #008800; font-weight: bold;">def</span> <span style="color: #0066bb; font-weight: bold;">say_hello</span>(): s <span style="color: #333333;">=</span> <span style="background-color: #fff0f0;">"Hello from outer function say_hello"</span> <span style="color: #008800; font-weight: bold;">def</span> <span style="color: #0066bb; font-weight: bold;">say_it</span>(): nonlocal s s <span style="color: #333333;">=</span> <span style="background-color: #fff0f0;">"Hello from inner function say_it"</span> <span style="color: #008800; font-weight: bold;">print</span>(s) <span style="color: #888888;">#print s before it is modified by say_it</span> say_it() <span style="color: #888888;">#change the value of s</span> <span style="color: #008800; font-weight: bold;">print</span>(s) <span style="color: #888888;">#print the new value after its modified by say_it</span> say_hello() </pre> </div> <br /> The concept is very similar to the usage of the <b>global</b> keyword. The difference is <b>global</b> is used to allow a function access to variables defined as global ( actually module attributes ) while <b>nonlocal</b> allows access to variables defined in outer functions.Kenneth Parkerhttp://www.blogger.com/profile/13907305526364974493[email protected]0tag:blogger.com,1999:blog-7020411281490343654.post-88263043641973286602019-08-05T18:16:00.001-07:002019-08-05T18:18:57.891-07:00Importing Global Variables in PythonGlobal variables in python are actually considered <b>module level variables </b>or <b>module attributes&nbsp;</b>and are not attached to a global namespace. This leads to some confusion when trying to change them from another module.<br /> <br /> Attempting to change them can lead to some quirky behavior. This is one of the few flaws that I see in an otherwise elegant and well implemented programming language.<br /> <br /> To demonstrate a common trap in python module attributes make a new file called <b>hello.py </b>and type the code below:<br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">g_hello <span style="color: #333333;">=</span> <span style="background-color: #fff0f0;">"Hello World"</span> <span style="color: #008800; font-weight: bold;">def</span> <span style="color: #0066bb; font-weight: bold;">print_g_hello</span>(): <span style="color: #008800; font-weight: bold;">print</span>(g_hello) </pre> </div> <span style="font-size: x-small;">hello.py - declaring g_hello global and print_g_hello function</span> <br /> <br /> When you import hello into another python script you will be able to access the variable <i>g_hello</i> and it seems like you can change it but really your changes only take effect within your current script. Changes to <i>g_hello</i> will not effect the value within <b>hello.py </b>or other modules that you import the global with.The below code will demonstrate the problem.<br /> <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #008800; font-weight: bold;">from</span> <span style="color: #0e84b5; font-weight: bold;">hello</span> <span style="color: #008800; font-weight: bold;">import</span> g_hello, print_g_hello <span style="color: #008800; font-weight: bold;">print</span>(g_hello) g_hello <span style="color: #333333;">=</span> <span style="background-color: #fff0f0;">"test"</span> <span style="color: #888888;">#this seems to work but actually does not effect g_hello outside of this script</span> <span style="color: #008800; font-weight: bold;">print</span>(g_hello) <span style="color: #888888;">#using the keyword global still has no effect on the global</span> <span style="color: #888888;">#it is only changed within the context of this script.</span> <span style="color: #008800; font-weight: bold;">def</span> <span style="color: #0066bb; font-weight: bold;">change_hello</span>(): <span style="color: #008800; font-weight: bold;">global</span> g_hello g_hello <span style="color: #333333;">=</span> <span style="background-color: #fff0f0;">"Hello changed!"</span> change_hello() <span style="color: #008800; font-weight: bold;">print</span>(g_hello) <span style="color: #888888;">#again hello changed local to this script</span> print_g_hello() <span style="color: #888888;">#calls a function in hello to print g_hello showing it is unchanged</span> </pre> </div> <span style="font-size: x-small;">test.py - importing g_hello and print_g_hello to demonstrate global scope</span> <br /> <br /> In the above script we import the global using the syntax <i>from hello import g_hello</i>. This seems like the most common sense approach to access a global declared in another python script. However, you will get read-only access to that global variable. If that is all you need, which is usually the case with config scripts, there is no issue.<br /> <br /> Problems arise when you find yourself trying to modify the values. As shown in the above example you will actually end up with two different values depending on how or where the variable is called.<br /> <br /> You can change the variable if you access it using the module name instead of importing the variable separately. This is a little strange as you would expect the import statement to simply serve, like other languages, as an alias. However, importing an entire module will access its attributes directly while importing each attribute individually in fact creates a copy of that attribute that does not modify the module.<br /> <br /> Create a new file called <b>test2.py</b> to demonstrate changing the global variable <i>g_hello</i>.<br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #008800; font-weight: bold;">import</span> <span style="color: #0e84b5; font-weight: bold;">hello</span> <span style="color: #888888;">#import the module so we can access its globals</span> <span style="color: #008800; font-weight: bold;">from</span> <span style="color: #0e84b5; font-weight: bold;">hello</span> <span style="color: #008800; font-weight: bold;">import</span> print_g_hello <span style="color: #888888;">#import the function to test if it has been changed</span> <span style="color: #008800; font-weight: bold;">print</span>(hello<span style="color: #333333;">.</span>g_hello) hello<span style="color: #333333;">.</span>g_hello <span style="color: #333333;">=</span> <span style="background-color: #fff0f0;">"World"</span> <span style="color: #008800; font-weight: bold;">print</span>(hello<span style="color: #333333;">.</span>g_hello) <span style="color: #888888;">#hello is changed</span> print_g_hello() <span style="color: #888888;">#hello is changed within the hello module as well</span> </pre> </div> <span style="font-size: x-small;">test2.py - importing g_hello and print_g_hello to demonstrate changing a global</span> <br /> <br /> This behavior is actually intended by the makers of python to try and curb the problems with global scope. Usage of global variables are frowned upon in most programming circles and module level variables are not any better as they just attach a namespace to a globally scoped variable.<br /> <br /> The most common usage of globals in python is for configuration files. This usage is usually condoned because passing configuration to every module or class in your solution would unnecessarily add to the code and complexity of your code.<br /> <br /> <br />Kenneth Parkerhttp://www.blogger.com/profile/13907305526364974493[email protected]1tag:blogger.com,1999:blog-7020411281490343654.post-56392230382946180072019-07-03T19:04:00.002-07:002019-07-03T19:28:05.526-07:00Python lambdaA lambda function in python allows you to write a reusable expression. Unlike saving the result of an expression in a variable the expression is re-evaluated every time it is used.The simplest lambda function in python takes no arguments and simply returns a literal like the one below:<br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">x <span style="color: #333333;">=</span> <span style="color: #008800; font-weight: bold;">lambda</span> : <span style="color: #0000dd; font-weight: bold;">100</span> <span style="color: #008800; font-weight: bold;">print</span>(x())<span style="color: #666666;"> </span></pre> </div> <i><span style="color: #666666; font-size: x-small;">Notice that when x is declared with the lambda keyword it has to be called by using parenthesis.</span></i> <br /> <br /> The above example isn't anymore useful then just assigning <b>x</b> the value of 100. However, the benefit of using lambdas over variables is they are dynamic. That is they will always evaluate to the expression instead of the last value entered.<br /> <br /> The lambda expression is a little easier for most people to understand because it works like you would expect a + b to behave in a mathematical equation.<br /> <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">a <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">100</span> b <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">1</span> x <span style="color: #333333;">=</span> <span style="color: #008800; font-weight: bold;">lambda</span> : a <span style="color: #333333;">+</span> b <span style="color: #008800; font-weight: bold;">print</span>(x()) a <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">10</span> b <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">10</span> <span style="color: #008800; font-weight: bold;">print</span>(x()) </pre> </div> <b><span style="color: #666666; font-size: x-small;"><i>We don't have to reassign x because a and b are re-evaluated on every call</i></span></b><br /> <b><br /></b> <b>Output:</b><!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #0000dd; font-weight: bold;">101</span> <span style="color: #0000dd; font-weight: bold;">20</span> </pre> </div> <br /> In the above example I don't have to re-assign x like I would with a variable because it always re-evaluates the value of a and b before giving a result. A lambda function in python must return a value. They are intended to evaluate mathematical expressions and calling functions that return a value. However, because many functions return a value but otherwise do not produce a usable value lambdas are often used for non-expression calls. Python's print function, for example, returns None. Because it returns a value it can be used in a lambda as if it where an expression: <br /> <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">print_me <span style="color: #333333;">=</span> <span style="color: #008800; font-weight: bold;">lambda</span> : <span style="color: #008800; font-weight: bold;">print</span>(<span style="background-color: #fff0f0;">"Hello World"</span>) print_me() </pre> </div> <br /> Python lambdas can take zero or more arguments and don't need to be assigned to a variable. They are often passed into functions so that a named function doesn't have to be declared. This is often used when a function takes another function as a parameter.<br /> <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">lst <span style="color: #333333;">=</span> [<span style="color: #0000dd; font-weight: bold;">1</span>, <span style="color: #0000dd; font-weight: bold;">2</span>, <span style="color: #0000dd; font-weight: bold;">2</span>, <span style="color: #0000dd; font-weight: bold;">2</span>] my_map <span style="color: #333333;">=</span> <span style="color: #007020;">map</span>(<span style="color: #008800; font-weight: bold;">lambda</span> x : x <span style="color: #333333;">*</span> <span style="color: #0000dd; font-weight: bold;">2</span>, lst) <span style="color: #008800; font-weight: bold;">print</span>(<span style="color: #007020;">list</span>(my_map)) </pre> </div> <br /> The map function, shown above, is a common use case of a lambda. It applies the expression passed as a lambda to the second argument which is a list of values and applies the expression to the list. Because the above function, x * 2, doesn't have to be named lambda is often referred to as an anonymous function.<br /> <br /> The most common usage of the lambda is for callbacks. Callbacks are often used in User Interface libraries in order to perform an action on click.<br /> <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">MyButton <span style="color: #333333;">=</span> UIButton(<span style="background-color: #fff0f0;">"Click Me"</span>) MyButton<span style="color: #333333;">.</span>OnClick(<span style="color: #008800; font-weight: bold;">lambda</span> sender, state : <span style="color: #008800; font-weight: bold;">print</span>(<span style="background-color: #fff0f0;">"You clicked me!"</span>)) </pre> </div> <br /> There is another way to accomplish the above expression using function definitions. It is a little extra syntax because you have to use the keyword return in order to actually have x() actually return a value. It also has to have a name which makes function definitions not very anonymous.<br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">a <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">10</span> b <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">10</span> <span style="color: #008800; font-weight: bold;">def</span> <span style="color: #0066bb; font-weight: bold;">x</span>(): <span style="color: #008800; font-weight: bold;">return</span> a <span style="color: #333333;">+</span> b <span style="color: #008800; font-weight: bold;">print</span>(x()) </pre> </div> <i><span style="color: #666666; font-size: x-small;">Still very compact but needs a name and a return value</span></i> <br /> <br /> Lambdas allow you to write python code in a <a href="https://docs.python.org/3/howto/functional.html">functional style</a> rather than object oriented or procedural. Python has an advantage over purely functional languages, that make it difficult to do things like save states or perform loops in that you can solve things that make sense with functional features and still write procedural or object oriented code.<br /> <br /> <br /> <i>I use the term procedural programming a little lightly. I think the term is still accurate as to how many programs are written today. However, its usage has dropped in popularity and is often replaced by the term sequential programming. Procedural code is usually&nbsp;in reference to older or "legacy" code.</i><br /> <br /> <br /> <i><span style="color: #666666; font-size: x-small;"><br /></span></i> <i><span style="color: #666666; font-size: x-small;"><br /></span></i>Kenneth Parkerhttp://www.blogger.com/profile/13907305526364974493[email protected]1tag:blogger.com,1999:blog-7020411281490343654.post-67170670722889606452019-07-03T10:48:00.001-07:002019-07-08T02:20:29.738-07:00Example - global keywordYou can declare a global variable in python easily enough but when you try to change it from a function no error is displayed and the old value is still there. <!-- HTML generated using hilite.me --><br /> <br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #888888;">#declare a global variable</span> a <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">23</span> <span style="color: #008800; font-weight: bold;">def</span> <span style="color: #0066bb; font-weight: bold;">print_a_variable</span>(): <span style="color: #008800; font-weight: bold;">print</span>(a) <span style="color: #888888;">#Printing it works just fine</span> <span style="color: #008800; font-weight: bold;">def</span> <span style="color: #0066bb; font-weight: bold;">change_a_variable</span>(): a <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">100000</span> <span style="color: #008800; font-weight: bold;">print</span>(a) <span style="color: #888888;">#seems to work but a is actually a new variable</span> print_a_variable() </pre> <pre style="line-height: 125%; margin: 0;">change_a_variable()</pre> <pre style="line-height: 125%; margin: 0;">print(a)</pre> </div> <a href="https://www.blogger.com/null"><b><br /></b></a> <b>Output:</b><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #0000dd; font-weight: bold;">23</span> <span style="color: #0000dd; font-weight: bold;">100000</span> <span style="color: #0000dd; font-weight: bold;">23</span> </pre> </div> <b><br /></b> If you use the keyword global in your function then the global is no longer read-only.<br /> <b><br /></b> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #888888;">#declare a global variable</span> a <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">23</span> <span style="color: #008800; font-weight: bold;">def</span> <span style="color: #0066bb; font-weight: bold;">print_a_variable</span>(): <span style="color: #888888;">#global a - not needed here because we can have readonly access to globals</span> <span style="color: #008800; font-weight: bold;">print</span>(a) <span style="color: #888888;">#Printing a works just fine</span> <span style="color: #008800; font-weight: bold;">def</span> <span style="color: #0066bb; font-weight: bold;">change_a_variable</span>(): <span style="color: #008800; font-weight: bold;">global</span> a <span style="color: #888888;">#If you want to change the global then it has to be declared here</span> a <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">100000</span> <span style="color: #008800; font-weight: bold;">print</span>(a) <span style="color: #888888;">#a is declared local and doesn't effect the global variable a</span> print_a_variable() change_a_variable() <span style="color: #008800; font-weight: bold;">print</span>(a) <span style="color: #888888;">#a is still 23</span> </pre> </div> <b><br /></b> <b>Output:</b> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #0000dd; font-weight: bold;">23</span> <span style="color: #0000dd; font-weight: bold;">100000</span> <span style="color: #0000dd; font-weight: bold;">100000</span> </pre> </div> Kenneth Parkerhttp://www.blogger.com/profile/13907305526364974493[email protected]0tag:blogger.com,1999:blog-7020411281490343654.post-25768080689604360482019-06-30T10:11:00.001-07:002019-07-02T23:18:01.845-07:00The for in Loop In PythonOne of the strongest features, in my opinion, that Python has is its ability to work with sequences. Sequences are ranges, lists, tuples, sets and dictionaries. I think that pythons elegance in working with these sequences is due to the design decision not to include extra syntax.<br /> <div> <br /></div> <div> Most languages have two for statements...the for loop and the <b>for in </b>loop. Python only uses the <b>for in</b> loop and has a built in function called <i>range</i> (xrange in python 2.7) to do basic indexing.<br /> <br /></div> <div> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #008800; font-weight: bold;">for</span> i <span style="color: black; font-weight: bold;">in</span> <span style="color: #007020;">range</span>(<span style="color: #0000dd; font-weight: bold;">10</span>): <span style="color: #007020;">print</span>(i) </pre> </div> </div> <span style="color: #666666; font-size: x-small;"><i>Because python uses zero indexes the above example prints 0-9 and not 1-10. Ranges actually stop at count-1.</i></span><br /> <br /> It's tempting to use the above form of the for loop to iterate or cycle through all indexes of a list as the below example shows but there are better ways to accomplish the same task.<br /> <br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">lst <span style="color: #333333;">=</span> [<span style="color: #0000dd; font-weight: bold;">0</span>,<span style="color: #0000dd; font-weight: bold;">1</span>,<span style="color: #0000dd; font-weight: bold;">2</span>,<span style="color: #0000dd; font-weight: bold;">3</span>,<span style="color: #0000dd; font-weight: bold;">4</span>,<span style="color: #0000dd; font-weight: bold;">5</span>,<span style="color: #0000dd; font-weight: bold;">6</span>,<span style="color: #0000dd; font-weight: bold;">7</span>,<span style="color: #0000dd; font-weight: bold;">8</span>,<span style="color: #0000dd; font-weight: bold;">9</span>] <span style="color: #008800; font-weight: bold;">for</span> i <span style="color: black; font-weight: bold;">in</span> <span style="color: #007020;">range</span>(<span style="color: #007020;">len</span>(<span style="color: #0000dd; font-weight: bold;">10</span>)): <span style="color: #007020;">print</span>(i) </pre> </div> <i><span style="color: #666666; font-size: x-small;">This is not the most pythonic or cleanest way to loop through a list.</span></i> <br /> <i><span style="color: #666666; font-size: x-small;"><br /></span></i> <br /> Counting indexes and passing the length to the range function is just a little too much work and is really unnecessary because you can accomplish the same thing by passing the list directly into the <b>for in </b>loop.<br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #008800; font-weight: bold;">for</span> value <span style="color: black; font-weight: bold;">in</span> [<span style="color: #0000dd; font-weight: bold;">0</span>,<span style="color: #0000dd; font-weight: bold;">1</span>,<span style="color: #0000dd; font-weight: bold;">2</span>,<span style="color: #0000dd; font-weight: bold;">3</span>,<span style="color: #0000dd; font-weight: bold;">4</span>,<span style="color: #0000dd; font-weight: bold;">5</span>,<span style="color: #0000dd; font-weight: bold;">6</span>,<span style="color: #0000dd; font-weight: bold;">7</span>,<span style="color: #0000dd; font-weight: bold;">8</span>,<span style="color: #0000dd; font-weight: bold;">9</span>]: <span style="color: #007020;">print</span>(value) </pre> </div> <span style="color: #666666; font-size: x-small;"><i>I just passed a literal list into the above code but I could have passed in a list variable like I do in the below examples.</i></span><br /> <br /> For most cases the above syntax is all that is needed and I estimate that I use it 90% of the time and rarely use any other looping mechanism. I suspect that the gate keepers of Python had the same experience and that is why they chose only two loop structures ( <i>while</i> and <i>for in</i> ). Programmers coming from a different language such as C++, C# or Java are usually quick to resort to the <i>range</i> function because they need access to the index not just the value. However, python has a better solution to this problem by using the built-in function&nbsp;<i>enumerate</i>.<br /> <br /> The below example uses the <i>enumerate</i>&nbsp;function to iterate through all values in a list with the <b>for in </b>loop and print the index and the value accordingly.<br /> <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #333333;">&gt;&gt;&gt;</span> lst <span style="color: #333333;">=</span> [<span style="color: #0000dd; font-weight: bold;">10</span>, <span style="color: #0000dd; font-weight: bold;">3</span>, <span style="color: #333333;">-</span><span style="color: #0000dd; font-weight: bold;">1</span>, <span style="color: #0000dd; font-weight: bold;">40</span>, <span style="color: #0000dd; font-weight: bold;">9</span>, <span style="color: #0000dd; font-weight: bold;">1</span>, <span style="color: #0000dd; font-weight: bold;">0</span>, <span style="color: #0000dd; font-weight: bold;">3</span>, <span style="color: #0000dd; font-weight: bold;">3</span>] <span style="color: #333333;">&gt;&gt;&gt;</span> <span style="color: #008800; font-weight: bold;">for</span> index, value <span style="color: black; font-weight: bold;">in</span> <span style="color: #007020;">enumerate</span>(lst): <span style="color: #333333;">...</span> <span style="color: #008800; font-weight: bold;">print</span>(<span style="background-color: #fff0f0;">"index: "</span> <span style="color: #333333;">+</span> <span style="color: #007020;">str</span>(index) <span style="color: #333333;">+</span> <span style="background-color: #fff0f0;">" value: "</span> <span style="color: #333333;">+</span> <span style="color: #007020;">str</span>(value)) <span style="color: #333333;">...</span> index: <span style="color: #0000dd; font-weight: bold;">0</span> value: <span style="color: #0000dd; font-weight: bold;">10</span> index: <span style="color: #0000dd; font-weight: bold;">1</span> value: <span style="color: #0000dd; font-weight: bold;">3</span> index: <span style="color: #0000dd; font-weight: bold;">2</span> value: <span style="color: #333333;">-</span><span style="color: #0000dd; font-weight: bold;">1</span> index: <span style="color: #0000dd; font-weight: bold;">3</span> value: <span style="color: #0000dd; font-weight: bold;">40</span> index: <span style="color: #0000dd; font-weight: bold;">4</span> value: <span style="color: #0000dd; font-weight: bold;">9</span> index: <span style="color: #0000dd; font-weight: bold;">5</span> value: <span style="color: #0000dd; font-weight: bold;">1</span> index: <span style="color: #0000dd; font-weight: bold;">6</span> value: <span style="color: #0000dd; font-weight: bold;">0</span> index: <span style="color: #0000dd; font-weight: bold;">7</span> value: <span style="color: #0000dd; font-weight: bold;">3</span> index: <span style="color: #0000dd; font-weight: bold;">8</span> value: <span style="color: #0000dd; font-weight: bold;">3</span> <span style="color: #333333;">&gt;&gt;&gt;</span> </pre> </div> <span style="color: #666666; font-size: x-small;"><i>This implementation would be blessed by the python elders and priests.</i></span><br /> <br /> The same task using the <i>range</i> function, as shown below, is a little more wordy and is more difficult to debug.<br /> <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #333333;">&gt;&gt;&gt;</span> lst <span style="color: #333333;">=</span> [<span style="color: #0000dd; font-weight: bold;">10</span>, <span style="color: #0000dd; font-weight: bold;">3</span>, <span style="color: #333333;">-</span><span style="color: #0000dd; font-weight: bold;">1</span>, <span style="color: #0000dd; font-weight: bold;">40</span>, <span style="color: #0000dd; font-weight: bold;">9</span>, <span style="color: #0000dd; font-weight: bold;">1</span>, <span style="color: #0000dd; font-weight: bold;">0</span>, <span style="color: #0000dd; font-weight: bold;">3</span>, <span style="color: #0000dd; font-weight: bold;">3</span>] <span style="color: #333333;">&gt;&gt;&gt;</span> <span style="color: #008800; font-weight: bold;">for</span> index <span style="color: black; font-weight: bold;">in</span> <span style="color: #007020;">range</span>(<span style="color: #007020;">len</span>(lst)): <span style="color: #333333;">...</span> <span style="color: #008800; font-weight: bold;">print</span>(<span style="background-color: #fff0f0;">"index: "</span> <span style="color: #333333;">+</span> <span style="color: #007020;">str</span>(index) <span style="color: #333333;">+</span> <span style="background-color: #fff0f0;">" value: "</span> <span style="color: #333333;">+</span> <span style="color: #007020;">str</span>(lst[index])) <span style="color: #333333;">...</span> index: <span style="color: #0000dd; font-weight: bold;">0</span> value: <span style="color: #0000dd; font-weight: bold;">10</span> index: <span style="color: #0000dd; font-weight: bold;">1</span> value: <span style="color: #0000dd; font-weight: bold;">3</span> index: <span style="color: #0000dd; font-weight: bold;">2</span> value: <span style="color: #333333;">-</span><span style="color: #0000dd; font-weight: bold;">1</span> index: <span style="color: #0000dd; font-weight: bold;">3</span> value: <span style="color: #0000dd; font-weight: bold;">40</span> index: <span style="color: #0000dd; font-weight: bold;">4</span> value: <span style="color: #0000dd; font-weight: bold;">9</span> index: <span style="color: #0000dd; font-weight: bold;">5</span> value: <span style="color: #0000dd; font-weight: bold;">1</span> index: <span style="color: #0000dd; font-weight: bold;">6</span> value: <span style="color: #0000dd; font-weight: bold;">0</span> index: <span style="color: #0000dd; font-weight: bold;">7</span> value: <span style="color: #0000dd; font-weight: bold;">3</span> index: <span style="color: #0000dd; font-weight: bold;">8</span> value: <span style="color: #0000dd; font-weight: bold;">3</span> <span style="color: #333333;">&gt;&gt;&gt;</span> </pre> </div> <i><span style="color: #666666; font-size: x-small;">This would be considered non-pythonic because it is not the most readable and compact implementation.</span></i> <br /> <br /> The former example using enumerate is most likely to get a thumbs up from fellow python developers but the later is probably going to give you a little bit of push back. I would prefer the enumerate implementation as well but because I have written a good number of C, COBOL, C++ and C# programs I don't judge either one as being good or bad. Its important to note that many developers are very good at looping through collections and they may not even see the benefit in the enumerate function.<br /> <br /> The <b>for in range</b> structure&nbsp; is still a useful construct and is needed if we want to:<br /> <ol> <li>Iterate over a fixed number without indexing a collection.&nbsp;</li> <li>Calling an internal or external API that gives us a count and a "get item" method instead of a collection.</li> <li>Skipping or "stepping" through index values.</li> </ol> Ranges can actually be saved into a variable, count backwards, step by positive and negative numbers and can be converted to other sequences like lists and tuples. The range function and xrange function are actually implemented differently and have a different processing cost. Even though their usage may be rare they do belong in python!<br /> <br /> More on ranges can be found online here:<br /> <a href="https://pynative.com/python-range-function/">https://pynative.com/python-range-function/</a> <br /> <br /> A good book on python such as the one below can also be a valuable resource in learning python. <br /> <br /> <iframe frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=US&amp;source=ac&amp;ref=tf_til&amp;ad_type=product_link&amp;tracking_id=startiprogra-20&amp;marketplace=amazon&amp;region=US&amp;placement=1449355730&amp;asins=1449355730&amp;linkId=2e233f987627b3e39c15ee51d399f9c6&amp;show_border=true&amp;link_opens_in_new_window=true&amp;price_color=333333&amp;title_color=0066c0&amp;bg_color=ffffff" style="height: 240px; width: 120px;"> </iframe>Kenneth Parkerhttp://www.blogger.com/profile/13907305526364974493[email protected]1tag:blogger.com,1999:blog-7020411281490343654.post-30133535285026408692019-06-30T09:19:00.001-07:002019-06-30T09:29:24.666-07:00if, if..else, if..elif..elseWhen you need to execute code if and only if a certain <a href="https://kenpythonic.blogspot.com/2019/06/python-conditional-expressions.html">condition</a> is met then you can use the <i>if statement</i>. If statements can be very simple or very complex.<br /> <br /> <h3> if</h3> In it's simplest form an <i>if statement</i> in python looks like <b>if a == b: &lt;&lt;statement&gt;&gt;</b><br /> <br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="font-weight: bold;">if</span> a == b: a = 100 </pre> </div> <i><span style="color: #666666; font-size: x-small;">One liner if statements are sometimes pointed at as not pythonic due to readability. But I believe this is unfounded when the statement is very short.</span></i><br /> <i><br /></i> Indentation is very important when writing structures such as if statements in python. If we expand the above statement to two lines the if statement only executes lines that are indented.<br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #008800; font-weight: bold;">if</span> a <span style="color: #333333;">==</span> b: a <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">100</span> b <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">0</span> c <span style="color: #333333;">=</span> random(<span style="color: #0000dd; font-weight: bold;">1</span>,<span style="color: #0000dd; font-weight: bold;">0</span>) d <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">1</span> <span style="color: #888888;">#always executes </span> </pre> </div> <br /> <h3> if..else</h3> You can also use the keyword <b>else</b> that will only execute if the condition in the <a href="https://kenpythonic.blogspot.com/2019/06/python-conditional-expressions.html">conditional expression</a> is false. You can only have one <b>else</b> in an if statement. The following example will always print hello because the condition is the literal value&nbsp;<b>True</b>.<br /> <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #008800; font-weight: bold;">if</span> <span style="color: #008800; font-weight: bold;">False</span>: <span style="color: #008800; font-weight: bold;">pass</span> <span style="color: #008800; font-weight: bold;">else</span>: <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"Hello"</span>) </pre> </div> <i><span style="color: #666666; font-size: x-small;">The <b>pass</b> keyword in python just tells python to do nothing. Many programming languages allow you to write a comment or simply leave a blank line but python requires an empty if to at least have pass statement in its body.</span></i> <br /> <i><span style="color: #666666;"><br /></span></i> You can put several if statements together if you have multiple conditions and statements to run. <br /> <br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #008800; font-weight: bold;">if</span> s <span style="color: #333333;">==</span> <span style="background-color: #fff0f0;">"Hello"</span>: <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"World"</span>) <span style="color: #008800; font-weight: bold;">if</span> s2 <span style="color: #333333;">==</span> <span style="background-color: #fff0f0;">""</span>: <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"The string is empty"</span>) <span style="color: #008800; font-weight: bold;">if</span> s3 <span style="color: #333333;">==</span> <span style="background-color: #fff0f0;">"abc"</span> <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"I know my abcs"</span>) </pre> </div> <h3> if..elif..else</h3> If you want to check multiple conditions but only if the previous condition(s) are false then use the <b>if..elif</b> structure. The following example is very similar to the above series of if statements but each condition is only evaluated if the previous condition is false.<br /> <br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #008800; font-weight: bold;">if</span> s <span style="color: #333333;">==</span> <span style="background-color: #fff0f0;">"Hello"</span>: <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"World"</span>) <span style="color: #008800; font-weight: bold;">elif</span> s2 <span style="color: #333333;">==</span> <span style="background-color: #fff0f0;">""</span>: <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"The string is empty"</span>) <span style="color: #008800; font-weight: bold;">elif</span> s3 <span style="color: #333333;">==</span> <span style="background-color: #fff0f0;">"abc":</span> <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"I know my abcs"</span>) </pre> </div> <i style="color: #666666;"><span style="font-size: x-small;">The keyword elif just means else if. The makers of python just wanted to save three stroke on a keyboard!</span></i><br /> <br /> The else statement must go at the end of this series of statements. It will be executed if all <b>if</b> and <b>elif</b> conditions are false. For example:<br /> <br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #008800; font-weight: bold;">if</span> s <span style="color: #333333;">==</span> <span style="background-color: #fff0f0;">"Hello"</span>: <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"World"</span>) <span style="color: #008800; font-weight: bold;">elif</span> s2 <span style="color: #333333;">==</span> <span style="background-color: #fff0f0;">""</span>: <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"The string is empty"</span>) <span style="color: #008800; font-weight: bold;">elif</span> s3 <span style="color: #333333;">==</span> <span style="background-color: #fff0f0;">"abc"</span>: <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"I know my abcs"</span>) <span style="color: #008800; font-weight: bold;">else</span>: <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"Nothing else was true!"</span>) </pre> </div> <br /> <h3> Backwards If Statements</h3> You can also put an if statement proceeding another statement in python. Unlike the first example this version of a one liner if statement is considered good form and is very useful when converting raw data into something readable. The else is required in this case because otherwise the variable has no assignment if the condition is false.<br /> <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">s <span style="color: #333333;">=</span> <span style="background-color: #fff0f0;">"Not Entered"</span> <span style="color: #008800; font-weight: bold;">if</span> s <span style="color: #333333;">==</span> <span style="background-color: #fff0f0;">""</span> <span style="color: #008800; font-weight: bold;">else</span> s </pre> </div> <i><span style="color: #666666; font-size: x-small;">Notice that you don't need the colon (:) in this statement</span></i><br /> <br /> You may be tempted to add an elif to the above example but it will not work. The elif statement doesn't apply to this if structure.<br /> <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #888888;">#This will not run. The elif keyword is not valid here</span> s <span style="color: #333333;">=</span> <span style="background-color: #fff0f0;">"Not Entered if s == "" elif s == "</span><span style="color: #333333;">*</span><span style="background-color: #fff0f0;">" "</span>Err<span style="background-color: #fff0f0;">" else s</span> </pre> </div> <br /> <h3> Nested If Statements</h3> In python, and in most modern programming languages for that matter, you can nest or place <b>if</b> statements within <b>if</b> statements for more complex conditions.<br /> <br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">a <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">1</span> b <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">1</span> c <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">1</span> d <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">1</span> <span style="color: #008800; font-weight: bold;">if</span> a <span style="color: #333333;">==</span> b: <span style="color: #008800; font-weight: bold;">if</span> a <span style="color: #333333;">==</span> c: <span style="color: #008800; font-weight: bold;">if</span> a <span style="color: #333333;">==</span> d: <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"a b c and d are all equal"</span>) <span style="color: #008800; font-weight: bold;">else</span>: <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"a is not equal to b"</span>) </pre> </div> <br /> The above example is pretty lengthy and is for demonstration purposes. It can be written instead, without nested if statements, as:<br /> <br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">a <span style="color: #333333;">=</span> b <span style="color: #333333;">=</span> c <span style="color: #333333;">=</span> d <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">1</span> <span style="color: #008800; font-weight: bold;">if</span> a <span style="color: #333333;">==</span> b <span style="color: #333333;">==</span> c <span style="color: #333333;">==</span> d: <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"a b c and d are all equal"</span>) <span style="color: #008800; font-weight: bold;">else</span>: <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"a is not equal to b"</span>) </pre> </div> <br /> You can also nest if, if..elif..else statements inside of the else and elif statement bodies like this:<br /> <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">a <span style="color: #333333;">=</span> b <span style="color: #333333;">=</span> c <span style="color: #333333;">=</span> d <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">10</span> <span style="color: #008800; font-weight: bold;">if</span> a <span style="color: #333333;">==</span> b: <span style="color: #008800; font-weight: bold;">if</span> a <span style="color: #333333;">==</span> c: <span style="color: #008800; font-weight: bold;">pass</span> <span style="color: #008800; font-weight: bold;">elif</span> a <span style="color: #333333;">==</span> d: <span style="color: #008800; font-weight: bold;">pass</span> <span style="color: #008800; font-weight: bold;">elif</span> a <span style="color: #333333;">==</span> <span style="color: #0000dd; font-weight: bold;">0</span>: <span style="color: #008800; font-weight: bold;">if</span> a <span style="color: #333333;">!=</span> <span style="color: #0000dd; font-weight: bold;">1</span>: <span style="color: #008800; font-weight: bold;">pass</span> <span style="color: #008800; font-weight: bold;">else</span>: <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"Hello!"</span>) <span style="color: #008800; font-weight: bold;">else</span>: <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"Hello"</span>) </pre> </div> <br /> Nesting if statements too deep can lead to unreadable code. Sometimes it is the best solution to the problem but I find that is very rare. It is not often that I need to nest an if statement more than two levels deep in any programming language.<br /> <br /> <i>COBOL programs are notorious for having a "dangling if" problem. Reading deeply nested if statements in COBOL is very difficult because its hard to tell, in a very nested if structure, what if statement goes to what else or else if. Python doesn't have this problem because it uses indentation. You can easily see what if, elif, and if statements go together because they are on the same column.</i> Kenneth Parkerhttp://www.blogger.com/profile/13907305526364974493[email protected]0tag:blogger.com,1999:blog-7020411281490343654.post-48977225603717235262019-06-29T11:32:00.001-07:002019-06-29T11:32:11.089-07:00Python Conditional ExpressionsPython supports conditional expressions. Conditional expressions allow you to execute statements only when a specific condition is met. Conditions are mathematical expressions such as: <!-- HTML generated using hilite.me --><br /> <br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">a <span style="color: #333333;">==</span> <span style="color: #0000dd; font-weight: bold;">0</span> <span style="color: #888888;">#Is a equal to zero?</span> a <span style="color: #333333;">!=</span> <span style="color: #0000dd; font-weight: bold;">0</span> <span style="color: #888888;">#Is a equal to zero?</span> a <span style="color: #333333;">&gt;</span> <span style="color: #0000dd; font-weight: bold;">100</span> <span style="color: #888888;">#Is a greater than 100</span> a <span style="color: #333333;">&gt;=</span> <span style="color: #0000dd; font-weight: bold;">100</span> <span style="color: #888888;">#Is a greater than or equal to 100</span> a <span style="color: #333333;">&lt;</span> c <span style="color: #888888;">#Is a less than c</span> a <span style="color: #333333;">&lt;=</span> c <span style="color: #888888;">#Is a less than or equal to c</span> </pre> </div> <br /> Conditionals can be used outside of an <i>if</i>, <i>while</i> or other conditional statement. If you set the variable a to a value you can use the above expressions to evaluate the result. The below program sets a to 0 and then evaluates its condition <br /> <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #333333;">&gt;&gt;&gt;</span> a <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">0</span> <span style="color: #333333;">&gt;&gt;&gt;</span> a <span style="color: #333333;">==</span> <span style="color: #0000dd; font-weight: bold;">0</span> <span style="color: #008800; font-weight: bold;">True</span> <span style="color: #333333;">&gt;&gt;&gt;</span> a <span style="color: #333333;">&lt;</span> <span style="color: #0000dd; font-weight: bold;">0</span> <span style="color: #008800; font-weight: bold;">False</span> <span style="color: #333333;">&gt;&gt;&gt;</span> a <span style="color: #333333;">&lt;=</span> <span style="color: #0000dd; font-weight: bold;">0</span> <span style="color: #008800; font-weight: bold;">True</span> <span style="color: #333333;">&gt;&gt;&gt;</span> a <span style="color: #333333;">&gt;</span> <span style="color: #0000dd; font-weight: bold;">0</span> <span style="color: #008800; font-weight: bold;">False</span> <span style="color: #333333;">&gt;&gt;&gt;</span> a <span style="color: #333333;">==</span> <span style="color: #0000dd; font-weight: bold;">10000</span> <span style="color: #008800; font-weight: bold;">False</span> <span style="color: #333333;">&gt;&gt;&gt;</span> </pre> </div> <br /> Conditional expressions evaluate to a boolean type. If you pass them to the built-in <i>type</i> function you can see they are boolean objects. <!-- HTML generated using hilite.me --><br /> <br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">&gt;&gt;&gt; type(a == 0) &lt;<span style="font-weight: bold;">class</span> <i>'</i><span style="font-weight: bold;">bool'</span><span style="font-style: italic;">&gt;</span> &gt;&gt;&gt; </pre> </div> <br /> Because conditional expressions can be evaluated to a variable, really an object, we can store the conditional for later use.<br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">&gt;&gt;&gt; is_a_equal_to_zero = a == 0 &gt;&gt;&gt; is_a_equal_to_zero <span style="font-weight: bold;">True</span> &gt;&gt;&gt; </pre> </div> <br /> Once the variable is_a_equal_to_zero is assigned it stores the last known evaluation of a == 0 and not what it currently is. If you re-assign a to a new value it will not change is_a_equal_to_zero.<br /> <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">&gt;&gt;&gt; is_a_equal_to_zero = a == 0 &gt;&gt;&gt; is_a_equal_to_zero <span style="font-weight: bold;">True</span> &gt;&gt;&gt; a = 10000 &gt;&gt;&gt; is_a_equal_to_zero <span style="font-weight: bold;">True</span> &gt;&gt;&gt; </pre> </div> <br /> Conditional Expressions are fundamental in programming and it is difficult to get any "real work" done without having some kind of conditional logic. You can combine conditional expressions with <b>if statements</b>, <b>while loops</b> and other python structures. Kenneth Parkerhttp://www.blogger.com/profile/13907305526364974493[email protected]1tag:blogger.com,1999:blog-7020411281490343654.post-17711565122151645722019-06-28T20:50:00.003-07:002019-07-08T02:20:59.161-07:00Comments in Python<h3> Single Line Comment</h3> <br /> Python uses the symbol <b>#</b> to represent a comment. Unlike many languages like C++ and C# there is no begin and end comment.<br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #888888;">#This is a comment</span> <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"Hello World"</span>) <span style="color: #888888;">#This is a comment too</span></pre> </div> <!-- HTML generated using hilite.me --><br /> <span style="background-color: white;">You can also put a comment after a line of code but not before a line of code.</span><br /> <span style="background-color: white;"><br /></span> <br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"Hello World"</span>) #This is a comment too! </pre> </div> <br /> Python comments are stripped before the code is compiled to byte code for execution so unlike some interpreted languages it does not cause a penalty during runtime. If there are a bunch of comments then it could cause extra <i>compile time.</i><br /> <br /> <h3> A Multiline Comment Hack</h3> I was quickly corrected by one of my fellow python developers when I referred to multiline strings as comments. They are in fact just strings that are not assigned a variable.<br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #dd4422;">"""</span> <span style="color: #dd4422;">This is a multiline string.</span> <span style="color: #dd4422;">It is often used for long comments...</span> <span style="color: #dd4422;">but it is really just a string that is not assigned to a variable</span> <span style="color: #dd4422;">"""</span> </pre> <pre style="line-height: 125%; margin: 0;">def print_hello():</pre> <pre style="line-height: 125%; margin: 0;"> print("Hello World")</pre> </div> Kenneth Parkerhttp://www.blogger.com/profile/13907305526364974493[email protected]0tag:blogger.com,1999:blog-7020411281490343654.post-70845208167710069122019-06-28T15:56:00.002-07:002019-06-29T13:03:11.880-07:00Writing Loops With Break and Continue The simplest form of a loop in python is the <b>while True: </b>infinite loop but you can pass other expressions to the while loop that will make it infinite.<br /> <br /> <div style="background: rgb(255, 255, 255); border: solid gray; color: #444444; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 16.25px;"><span style="color: #996633;">i</span> <span style="color: #333333;">=</span> 0 <span style="color: #008800; font-weight: bold;">while </span><b>1</b>: i +<span style="color: #333333;">=</span> 1 print<span style="color: #333333;">(</span><span style="background-color: #fff0f0;">"Hello "</span>+ str<span style="color: #333333;">(</span>i<span style="color: #333333;">))</span> </pre> </div> <br style="background-color: white; color: #444444; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px;" /> The above will do the same thing as passing <b>while True</b>.<br /> <br /> You can write other <a href="https://kenpythonic.blogspot.com/2019/06/python-conditional-expressions.html">conditional expressions</a> in a while loop to manipulate the number of repetitions.<br /> <br /> <div style="background: rgb(255, 255, 255); border: solid gray; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 16.25px;"><span style="color: #996633;">i</span><span style="color: #444444;"> </span><span style="color: #333333;">=</span><span style="color: #444444;"> 0 </span><span style="color: #008800; font-weight: bold;">while </span><span style="font-weight: bold;">i</span><span style="font-weight: bold;"> &lt;= 10</span><span style="color: #444444;">: i +</span><span style="color: #333333;">=</span><span style="color: #444444;"> 1 print</span><span style="color: #333333;">(</span><span style="background-color: #fff0f0; color: #444444;">"Hello "</span><span style="color: #444444;">+ str</span><span style="color: #333333;">(</span><span style="color: #444444;">i</span><span style="color: #333333;">))</span><span style="color: #444444;"> </span></pre> </div> <br style="background-color: white; color: #444444; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px;" /> The above will print <i>hello n </i>10 times instead of printing forever.<br /> <br /> <h3> The <i>break</i> Statement </h3> You can also write infinite loops and break out of them using the <i>break</i> statement in python. This is very common and replaces the <i>goto</i> statement that is often demonized in modern programming.&nbsp; When you break out of a while loop or any other loop your code stops execution where break is encountered and continue execution after the while loop.<br /> <br /> Recall that python works with indentation so that the while loop ends when the indentation is no longer there.<br /> <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">i <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">0</span> <span style="color: #008800; font-weight: bold;">while</span> <span style="color: #0000dd; font-weight: bold;">1</span>: i <span style="color: #333333;">+=</span> <span style="color: #0000dd; font-weight: bold;">1</span> <span style="color: #008800; font-weight: bold;">if</span> i <span style="color: #333333;">&lt;=</span> <span style="color: #0000dd; font-weight: bold;">10</span>: <span style="color: #008800; font-weight: bold;">break</span> <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"Hello "</span><span style="color: #333333;">+</span> <span style="color: #007020;">str</span>(i)) a <span style="color: #333333;">=</span> i </pre> </div> <br style="background-color: white; color: #444444; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px;" /> In the case above we do the same loop but a little less compact. When the break statement is hit execution continues at <b>a= i.&nbsp;</b><br /> <br /> <h3> The <i>continue</i> Statement </h3> Similar to the break statement the <i>continue</i> statement is used to control the flow of the while loop. Instead of exiting the while or other looping mechanism it is used to skip statements below it and go to the beginning of the loop. It will re-evaluate the condition. Because we are doing an infinite while loop it will always be true. It is usually combined with an if statement like above but the if is not required in either one.<br /> <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">i <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">0</span> <span style="color: #008800; font-weight: bold;">while</span> <span style="color: #0000dd; font-weight: bold;">1</span>: i <span style="color: #333333;">+=</span> <span style="color: #0000dd; font-weight: bold;">1</span> <span style="color: #008800; font-weight: bold;">if</span> i <span style="color: #333333;">&lt;=</span> <span style="color: #0000dd; font-weight: bold;">10</span>: <span style="color: #008800; font-weight: bold;">break</span> <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"Hello "</span><span style="color: #333333;">+</span> <span style="color: #007020;">str</span>(i)) a <span style="color: #333333;">=</span> i </pre> </div> <br style="background-color: white; color: #444444; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; font-size: 13px;" /> The above program prints <i>hello n </i>exactly like the other two examples except it skips the <i>print </i>command when <b>i</b> has the value <b>5</b>. If <b>i </b>= 5 all statements under continue are skipped. Often times you will see code that always evaluates to true or simply has a continue statement without a conditional statement ( if statement ). This is sometimes used to skip code that should not be ran. It is equivalent to commenting code. However, it is bad practice and code that never runs is referred to as DEAD code.<br /> <br /> Dead code is frowned upon and is often the target of re-factoring or re-writing of a program.<br /> <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #008800; font-weight: bold;">while</span> <span style="color: #0000dd; font-weight: bold;">1</span>: <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"Hello"</span>) <span style="color: #008800; font-weight: bold;">continue</span> <span style="color: #007020;">print</span>(<span style="background-color: #fff0f0;">"World"</span>) <span style="color: #888888;"># &lt;---- DEAD CODE</span> </pre> </div> <br /> The above program will print Hello forever / infinite but never reaches <b>print("World")</b>.<br /> <br /> More about loops in python can be found here: <br /> <pre style="line-height: 16.25px;"></pre> <pre style="line-height: 16.25px;"><span style="font-family: &quot;times&quot; , &quot;times new roman&quot; , serif;"><a href="https://www.w3schools.com/python/python_while_loops.asp">https://www.w3schools.com/python/python_while_loops.asp</a></span></pre> <pre style="line-height: 16.25px;"></pre> <pre style="line-height: 16.25px;"></pre> <pre style="line-height: 16.25px;"></pre> <i><br /></i> <i>I must confess that I have sinned in this way many times. Often times I write "dead code" like the above example because I am troubleshooting the loop to see what will happen if I skip to the end or to see what happens under certain conditions if I continue or break out of the loop. Unfortunately, "The road to hell is paved with good intentions" and I sometimes forget to take those statements out before committing or saving my work.</i>Kenneth Parkerhttp://www.blogger.com/profile/13907305526364974493[email protected]0tag:blogger.com,1999:blog-7020411281490343654.post-52302092588388695472019-06-20T11:13:00.000-07:002019-06-28T14:51:23.488-07:00PIP - Python's Package Management SystemPython has an easy to use and very robust package management system called pip. In order to take advantage of another programmer's work you have to import their source code into your program. The Python package management system offers a true advantage over compiled language such as C++ and even other interpreted languages like Ruby.<br /> <br /> Pip is included with Python 3 but if you don't have it installed the instructions can be found here:<br /> <a href="https://pip.pypa.io/en/stable/installing/">Pip Installation</a><br /> <br /> Its dead simple to include an external package using pip:<br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">$ pip install mortgage </pre> </div> <br /> In some operating systems you may need to install and use pip3.<br /> <br /> <div style="background: rgb(255, 255, 255); border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 16.25px;">$ pip3 install mortgage </pre> </div> <br /> For instance pip3 installation on a Debian system:<br /> <br /> <div style="background: rgb(255, 255, 255); border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 16.25px;">$ sudo apt-get update </pre> <pre style="line-height: 16.25px;">$ sudo apt-get install python3-pip</pre> <pre style="line-height: 16.25px;">$ pip3 --version</pre> </div> <br /> <a href="https://linuxize.com/post/how-to-install-pip-on-debian-9/">https://linuxize.com/post/how-to-install-pip-on-debian-9/</a>After you have installed the package you can include it in your own python code using the import statement. After the package is installed you use it as follows:<br /> <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #008800; font-weight: bold;">from</span> <span style="color: #0e84b5; font-weight: bold;">mortgage</span> <span style="color: #008800; font-weight: bold;">import</span> Loan loan <span style="color: #333333;">=</span> Loan(principal<span style="color: #333333;">=</span><span style="color: #0000dd; font-weight: bold;">30000</span>, interest<span style="color: #333333;">=.</span><span style="color: #0000dd; font-weight: bold;">925</span>, term<span style="color: #333333;">=</span><span style="color: #0000dd; font-weight: bold;">6</span>) loan<span style="color: #333333;">.</span>summarize </pre> </div> <br /> If you run the above program in python you will get a very nice summary of a loan with the given parameters.<br /> <br /> Because of the overwhelming popularity of python for both commercial and open source projects, there are a ton of projects written in python that you can take advantage of. This is one of the biggest selling points for me when deciding on a good programming language for a project. If there is a package available and I don't have to write one or extend and existing package then I can save a-lot of time and effort.<br /> <h3> The Dirty Way To Include External Python Code</h3> <div> Many compiled languages and even interpreted languages don't have a package management system or they are so difficult to use that it takes as much time to include someone else's source code as it would to re-write it yourself.<br /> <br /> C and C++ programs and even Java and C# programs for that matter are littered with copy and paste code. If a programmer can't figure out how to reference a library or include code the "correct" way they will use whatever means necessary to get the program working.<br /> <br /> Copy and paste code is a huge burden for both commercial and open source projects. Source code always carries with it a maintenance cost.<br /> <h3> How to Find Packages</h3> </div> You can find packages easily online by navigating to&nbsp;<a href="https://pypi.org/%C2%A0">The Python Package Index</a>. When you find the package you are looking for you can use the <b>pip install &lt;&lt;package&gt;</b> just like we did the the Mortgage example above.<br /> <br /> Another good way to find a package is to search for open source projects on <a href="https://sourceforge.net/">SourceForge</a> or&nbsp;<a href="https://github.com/">GitHub</a>. Most python projects have instructions on how to install the package using pip. Many commercial vendors such as Microsoft and Amazon have open source packages to support their applications.<br /> <br /> If you prefer the command line then you can use <b>pip search &lt;&lt;package&gt;&gt;&nbsp;</b>&nbsp;. It will also tell you if the package is already installed, what version is installed and if there is a later version available.<br /> <br /> You can see from the below command that we have several other packages to choose from. Packages that have a version below 1.0.0, py-mortgage 0.1.0 for example, are generally less mature. Sometimes they can be useful but if you are doing serious work then I would stick with 1.0 and above.<br /> <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">$ pip search Mortgage mortgage (1.0.3) - Mortgage Calculator <b>INSTALLED</b>: 1.0.2 <b>LATEST</b>: 1.0.3 py-mortgage (0.1.0) - A package to handle mortgage calculations pymortgage (0.1.4) - Python Mortgage utilities py-mortgagekit (1.0.3b1) - Python library for mortgage calculations. Mortgages-and-Loans (0.1.2) - Simple Python Scripts for Complex Mortgages pandicake (0.3.3) - Utilities for mortgage backed securities cash flow analytics </pre> </div> <br /> Pip has a-lot of functionality and can get complicated if you get into advanced features. Most of the time you just need a simple <b>pip install </b>to get your python program to work. However, if you are working on a larger project or in a strict programming shop then you may need to dig deeper into how pip works.<br /> <br /> The official user guide for pip can be found here:<br /> <a href="https://pip.pypa.io/en/stable/user_guide/">PIP - User Guide</a><br /> <br /> <iframe frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=US&amp;source=ac&amp;ref=tf_til&amp;ad_type=product_link&amp;tracking_id=startiprogra-20&amp;marketplace=amazon&amp;region=US&amp;placement=1449355730&amp;asins=1449355730&amp;linkId=34567f5b66847b4a0099d619fc8b0c9f&amp;show_border=true&amp;link_opens_in_new_window=true&amp;price_color=333333&amp;title_color=0066c0&amp;bg_color=ffffff" style="height: 240px; width: 120px;"> </iframe>Kenneth Parkerhttp://www.blogger.com/profile/13907305526364974493[email protected]0tag:blogger.com,1999:blog-7020411281490343654.post-70793891603179388422019-06-10T19:23:00.001-07:002019-06-10T21:13:01.735-07:00The While Loop in PythonIn order to perform operations over and over again in a programming language you need to have syntax that allows you to execute the same lines of code without having to re-write each individual line. In python there are a few ways to do this and one way is the <b>while</b> command.<br /> <br /> The indentation is important in python. All statements under the while command must be indented by at least one space, and by convention some programmers use 4 spaces. If you use an editor the tab key must be setup in the editor so that when you press tab it really insert spaces instead of tabs.<br /> <br /> <br /> The below example will print <b>Hello n </b>until the end of time or you press CTRL-C.<br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #996633;">i</span> <span style="color: #333333;">=</span> 0 <span style="color: #008800; font-weight: bold;">while </span>True: i +<span style="color: #333333;">=</span> 1 print<span style="color: #333333;">(</span><span style="background-color: #fff0f0;">"Hello "</span>+ str<span style="color: #333333;">(</span>i<span style="color: #333333;">))</span> </pre> </div> <br /> <br /> This is what we refer to as an <i>infinite loop</i> and when I learned programming 20 years ago we were told to avoid them at all cost because it would hang your computer and cause you to lose your work. But python, and modern operating systems for that matter, are very good and handling this situation.<br /> <br /> The output for the above program is as follows:<br /> <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">Hello 2548067 Hello 2548068 Hello 2548069 Hello 2548070 Hello 2548071 Hello 2548072 Hello 2548073 Hello 2548074 Hello 2548075 Hello 2548076 Hello 2548077 Hello 2548078 ^CHello 2548079 Hello 2548080 Traceback <span style="color: #333333;">(</span>most recent call last<span style="color: #333333;">)</span>: File <span style="background-color: #fff0f0;">"&lt;stdin&gt;"</span>, line 3, in &lt;module&gt; KeyboardInterrupt </pre> </div> <br /> You will notice ˆC and the KeyboardInterrupt in the output. This is expected behavior because we never gave a command to end the loop.<br /> <br /> Also understand that inside of the parenthesis we used <b>"Hello " + str(i)</b>. This is called string concatenation. We use the plus operator, which you would expect to be used for math operations, to join two strings together. The <b>str(i) </b>function<b>&nbsp;</b>is used to convert i, which is an integer, to a string instead.<br /> <br /> For a dynamic language python can be strict on using types. Many dynamic languages would automatically assume that you wanted <b>i</b> to be converted to a string. Python simply wants to make sure that you really intended on converting <b>i</b> to a string before it joins it to "Hello".<br /> <br /> <br /> <a href="https://www.w3schools.com/python/python_while_loops.asp">https://www.w3schools.com/python/python_while_loops.asp</a>&nbsp;- More information about while loops and for loops.<br /> <br /> <table> <tbody> <tr> <td><iframe frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=US&amp;source=ac&amp;ref=tf_til&amp;ad_type=product_link&amp;tracking_id=startiprogra-20&amp;marketplace=amazon&amp;region=US&amp;placement=B079HZPW86&amp;asins=B079HZPW86&amp;linkId=2ed9949109416bf4e5df4d4ef688bd39&amp;show_border=true&amp;link_opens_in_new_window=true&amp;price_color=333333&amp;title_color=0066c0&amp;bg_color=ffffff" style="height: 240px; width: 120px;"> </iframe> </td> <td style="padding: 5px;" width="500px">I am writing this blog and testing my examples using an iMac very similar to this one. You don't really need a powerful computer but its nice to have one that has a nice display and is very quite. Macintoshes are very elegant and the unix base that OS X is built on helps me to access unix command line tools which I find more powerful than Windows command prompts. </td> </tr> </tbody></table> <br /> <br /> <br /> <br />Kenneth Parkerhttp://www.blogger.com/profile/13907305526364974493[email protected]0tag:blogger.com,1999:blog-7020411281490343654.post-11020026146323219282019-06-10T09:27:00.000-07:002019-06-10T09:27:29.323-07:00Reading User Input in Python<h3> Reading Input From The Keyboard</h3> <div> In order to process user input you are going to need to retrieve keyboard data from the user. One of the most easy and straightforward ways of getting user input is to use the <b>input</b> function.<br /> <br /></div> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">&gt;&gt;&gt; <span style="color: #996633;">a</span> <span style="color: #333333;">=</span> input<span style="color: #333333;">(</span><span style="background-color: #fff0f0;">"Enter a number:"</span><span style="color: #333333;">)</span> Enter a number:23 &gt;&gt;&gt; print<span style="color: #333333;">(</span>a<span style="color: #333333;">)</span> 23 &gt;&gt;&gt; </pre> </div> <div> <br /></div> <div> In the above example we use the input command to retrieve a number and store it in the variable <b>a</b>. We could have first used the print command and then called <b>input() </b>but it is more compact and easier to read to display the user input and retrieve it at the same time.<br /> <br /> A common mistake would be to call input(a) expecting the input command to store the value in a.<br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;">&gt;&gt;&gt; input<span style="color: #333333;">(</span>x<span style="color: #333333;">)</span> Traceback <span style="color: #333333;">(</span>most recent call last<span style="color: #333333;">)</span>: File <span style="background-color: #fff0f0;">"&lt;stdin&gt;"</span>, line 1, in &lt;module&gt; NameError: name <span style="background-color: #fff0f0;">'x'</span> is not defined &gt;&gt;&gt; </pre> </div> <br /> NOTE: The variable <b>a</b> is automatically declared in python and we don't even have to give it an initial value before retrieving it from the user.<br /> <br /> <br /> <br /></div> <iframe frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=US&amp;source=ac&amp;ref=tf_til&amp;ad_type=product_link&amp;tracking_id=startiprogra-20&amp;marketplace=amazon&amp;region=US&amp;placement=1491946008&amp;asins=1491946008&amp;linkId=a8109592a6f52f55d510511dfe78a193&amp;show_border=true&amp;link_opens_in_new_window=true&amp;price_color=333333&amp;title_color=0066c0&amp;bg_color=ffffff" style="height: 240px; width: 120px;"> </iframe> Kenneth Parkerhttp://www.blogger.com/profile/13907305526364974493[email protected]0tag:blogger.com,1999:blog-7020411281490343654.post-54919831393209116772019-06-09T18:58:00.000-07:002019-06-09T18:58:18.102-07:00More About VariablesPython is a strongly typed dynamic programming language. This means that when you create a variable in python it is assigned a type and can be used as that type. Because python is extremely flexible it has the ability, without any extra syntax, to change one type to another type.<br /> <br /> Because typing is dynamic in python it does not check if the type is correct until the program runs. So if you for instance try to check the absolute value, which is a numeric operation, you will get a syntax error when the program runs but the program will run up until that point. This is a little bit of a double edge sword because on one hand your program has the flexibility to handle this situation and even have dynamic code that relies on it but on the other hand your program could be more stable if this was checked ahead of time.<br /> <br /> This is an example of a type error when we try to get the absolute value of "Hello".<br /> <br /> <!-- HTML generated using hilite.me --><div style="background: #ffffff; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;"><pre style="margin: 0; line-height: 125%">&gt;&gt;&gt; abs<span style="color: #333333">(</span><span style="background-color: #fff0f0">&quot;Hello&quot;</span><span style="color: #333333">)</span> Traceback <span style="color: #333333">(</span>most recent call last<span style="color: #333333">)</span>: File <span style="background-color: #fff0f0">&quot;&lt;stdin&gt;&quot;</span>, line 1, in &lt;module&gt; TypeError: bad operand <span style="color: #007020">type </span><span style="color: #008800; font-weight: bold">for </span>abs<span style="color: #333333">()</span>: <span style="background-color: #fff0f0">&#39;str&#39;</span> &gt;&gt;&gt; </pre></div> <br /> Python understands types as classes:<br /> <br /> &lt;class 'int'&gt;<br /> &lt;class 'float'&gt;<br /> &lt;class 'bool'&gt;<br /> &lt;class 'str'&gt;<br /> <br /> The simplest way to declare or create one of these variables is to use the correct literal syntax when assigning a variable. In the below example I create one of each type.<br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <table><tbody> <tr><td><pre style="line-height: 125%; margin: 0;">1 2 3 4</pre> </td><td><pre style="line-height: 125%; margin: 0;"><span style="color: #996633;">a</span> <span style="color: #333333;">=</span> 1 <span style="color: #996633;">b</span> <span style="color: #333333;">=</span> 1.0 <span style="color: #996633;">c</span> <span style="color: #333333;">=</span> True <span style="color: #996633;">d</span> <span style="color: #333333;">=</span> <span style="background-color: #fff0f0;">"Hello"</span> </pre> </td></tr> </tbody></table> </div> <br /> Python allows you to check the type ( class name) of these variables by using the type function. We consider this method built-in and available to use. You can create user-defined functions in python as well but it is not necessary to learn that at this point.<br /> <br /> In the below example I can print out each of the above type names for each variable: <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <table><tbody> <tr><td><pre style="line-height: 125%; margin: 0;">1 2 3 4 5 6 7 8 9</pre> </td><td><pre style="line-height: 125%; margin: 0;"><span style="color: #996633;">a</span> <span style="color: #333333;">=</span> 1 <span style="color: #996633;">b</span> <span style="color: #333333;">=</span> 1.0 <span style="color: #996633;">c</span> <span style="color: #333333;">=</span> True <span style="color: #996633;">d</span> <span style="color: #333333;">=</span> <span style="background-color: #fff0f0;">"Hello"</span> <span style="color: #007020;">type</span><span style="color: #333333;">(</span>a<span style="color: #333333;">)</span> <span style="color: #007020;">type</span><span style="color: #333333;">(</span>b<span style="color: #333333;">)</span> <span style="color: #007020;">type</span><span style="color: #333333;">(</span>c<span style="color: #333333;">)</span> <span style="color: #007020;">type</span><span style="color: #333333;">(</span>d<span style="color: #333333;">)</span> </pre> </td></tr> </tbody></table> </div> <br /> The output of the above example will be: <br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <table><tbody> <tr><td><pre style="line-height: 125%; margin: 0;">1 2 3 4</pre> </td><td><pre style="line-height: 125%; margin: 0;">&lt;class <span style="background-color: #fff0f0;">'int'</span>&gt; &lt;class <span style="background-color: #fff0f0;">'float'</span>&gt; &lt;class <span style="background-color: #fff0f0;">'bool'</span>&gt; &lt;class <span style="background-color: #fff0f0;">'str'</span>&gt; </pre> </td></tr> </tbody></table> </div> <br /> If you just want the name of the type you can use <b>type(variable).__name__.</b> This will just print out the name and not the extra syntax that you see above. This is very useful for some programs that need to ensure they are really getting an integer and not a string for instance.<br /> <br /> Use the below example to get the variable types.<br /> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <table><tbody> <tr><td><pre style="line-height: 125%; margin: 0;">1 2</pre> </td><td><pre style="line-height: 125%; margin: 0;"><span style="color: #007020;">type</span><span style="color: #333333;">(</span>3.14<span style="color: #333333;">)</span>.__name__ <span style="color: #007020;">type</span><span style="color: #333333;">(</span><span style="background-color: #fff0f0;">"Hello"</span><span style="color: #333333;">)</span>.__name__ </pre> </td></tr> </tbody></table> </div> <span style="font-size: x-small;">Notice I just pass values, called literals, into the function instead of first assigning them to a variable.</span><br /> <br /> The above program will output: <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="background-color: #fff0f0;">'int'</span> <span style="background-color: #fff0f0;">'str'</span> </pre> </div> <br /> You can learn more about built-in types on the below link:<br /> <a href="https://docs.python.org/3.7/library/stdtypes.html">https://docs.python.org/3.7/library/stdtypes.html</a><br /> <br />Kenneth Parkerhttp://www.blogger.com/profile/13907305526364974493[email protected]0tag:blogger.com,1999:blog-7020411281490343654.post-23462191272597024832019-06-09T15:43:00.001-07:002019-06-09T16:09:58.330-07:00What Does It Mean To Be Pythonic?As you go out into the community and seek help from the python developers<br /> you will encounter various, well meaning and experienced python developers that will accuse you of not being "pythonic". This simply means that you are not writing code the way the python community believes is efficient, straightforward and follows python guidelines.<br /> <br /> <iframe frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=US&amp;source=ac&amp;ref=qf_sp_asin_til&amp;ad_type=product_link&amp;tracking_id=startiprogra-20&amp;marketplace=amazon&amp;region=US&amp;placement=B07CHNPJZM&amp;asins=B07CHNPJZM&amp;linkId=9769e4c67bfc7c342d728790740c3913&amp;show_border=true&amp;link_opens_in_new_window=true&amp;price_color=333333&amp;title_color=0066c0&amp;bg_color=ffffff" style="height: 240px; width: 120px;"> </iframe> The above T-Shirt could help you if you are feeling a little bit code shamed. To be honest I know too many programming languages to really be cleansed by the python community. <br /> <br /> To protect me from such religious zealots I would like to reference the below definition of pythonic until I write better code :)<br /> <br /> <br /> <br /> <br /> <section class="css-0 e1rg2mtf0" style="color: #4a4a4a; font-family: Arial; font-size: 14px;"><div class="css-16k3qdb e1rg2mtf5" style="color: #1a1a1a; display: inline-block; margin-right: 10px;"> <h1 class="css-1lr0y5c e1rg2mtf8" style="display: inline; font-size: 49px; line-height: normal; margin: 0px 10px 10px 0px; word-break: break-word;"> pythonic</h1> <span class="css-dpy2vi e1rg2mtf4" style="font-size: 10.5px; line-height: 10px; margin-left: -6px; margin-right: 6px; position: relative; top: 4px; vertical-align: top;">1</span></div> <div class="css-1baulvz e1rg2mtf6" style="display: inline-block;"> <div class="pron-spell-ipa-container show-spell css-19i23xe evh0tcl0" style="display: inline-block;"> <div class="pron-spell-container css-1hyfx7x evh0tcl1" style="display: inline-block;"> <span class="pron-spell-content css-blvt6m evh0tcl2" style="font-size: 20px; vertical-align: super;">[ pahy-<span class="bold" style="font-weight: bold;">thon</span>-ik, pi- ]</span></div> </div> </div> </section><br /> <hr class="css-3qvlff etjs7ll0" style="border-bottom-color: rgb(182, 182, 182); border-bottom-style: solid; border-top: 0px; box-sizing: content-box; color: #4a4a4a; font-family: Arial; font-size: 14px; height: 0px; margin-bottom: 20px; overflow: visible;" /> <br /> <br /> <br /> <section class="css-qfguj9 e1hk9ate0" style="color: #4a4a4a; font-family: Arial; font-size: 14px;"><h3 class="css-sdwj8v e1hk9ate1" style="margin: 25px 0px 0px;"> <span class="css-1gxch3 e1hk9ate2" style="color: #1a1a1a; font-size: 18px; font-style: italic; font-weight: normal;">adjective</span></h3> <div class="css-1o58fj8 e1hk9ate4" style="font-size: 15px; margin-left: 20px;"> <div class="css-kg6o37 e1q3nk1v3" style="display: list-item; line-height: 1.5; list-style: none; margin-bottom: 4px; margin-top: 8px; padding-left: 25px; position: relative;" value="1"> <span class="one-click-content css-98tqe9 e1q3nk1v4" style="color: #1a1a1a; font-size: 18px;">of or&nbsp;<span class="one-click" data-linkid="nn1ov4" data-term="relating">relating</span>&nbsp;to&nbsp;<a class="luna-xref" data-linkid="nn1ov4" href="https://www.dictionary.com/browse/python" style="color: #3a76c3; text-decoration-line: none;">pythons</a>.</span></div> <div class="css-12vimxp e1q3nk1v3" style="display: list-item; line-height: 1.5; list-style: none; margin-bottom: 4px; margin-top: 8px; padding-left: 25px; position: relative;" value="2"> <span class="one-click-content css-98tqe9 e1q3nk1v4" style="color: #1a1a1a; font-size: 18px;"><span class="one-click" data-linkid="nn1ov4" data-term="similar">similar</span>&nbsp;to a&nbsp;<span class="one-click" data-linkid="nn1ov4" data-term="python">python;</span>&nbsp;<span class="one-click" data-linkid="nn1ov4" data-term="pythonlike">pythonlike.</span></span></div> <div class="css-1nmzxaj e1q3nk1v3" style="display: list-item; line-height: 1.5; list-style: none; margin-bottom: 4px; margin-top: 8px; padding-left: 25px; position: relative;" value="3"> <span class="one-click-content css-98tqe9 e1q3nk1v4" style="color: #1a1a1a; font-size: 18px;"><span class="one-click" data-linkid="nn1ov4" data-term="gigantic">gigantic</span>&nbsp;or&nbsp;<span class="one-click" data-linkid="nn1ov4" data-term="monstrous">monstrous.</span></span></div> </div> </section><br /> <a href="https://www.dictionary.com/browse/pythonic">https://www.dictionary.com/browse/pythonic</a><br /> <br /> <br /> <br /> <br /> <br />Kenneth Parkerhttp://www.blogger.com/profile/13907305526364974493[email protected]0tag:blogger.com,1999:blog-7020411281490343654.post-36048809989955762722019-06-09T15:10:00.001-07:002019-07-03T10:23:33.167-07:00Variables in PythonIn order to do anything with your output it is useful, and it can be argued absolutely necessary to store information somehow in order to manipulate that information. Python has a very straight forward and easy syntax ( set of rules ) in order to do this called variables.<br /> <br /> They are called variables because the value can be changed.<br /> <br /> To <i>declare</i> a variable in python is simple: <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <table><tbody> <tr><td><pre style="line-height: 125%; margin: 0;">1 2</pre> </td><td><pre style="line-height: 125%; margin: 0;">a <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">1</span> b <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">100</span> </pre> </td></tr> </tbody></table> </div> <br /> In the above example I have <i>declared</i> two variables named a and b. I store the value 1 in <b>a</b> and the value 100 in <b>b</b>. To avoid confusion I like to say that <b>a</b> becomes 1 and <b>b</b> becomes 100. This is to avoid confusion between equality and assignment. To say that <b>a</b> is equal 1 and/or <b>b</b> = 100 could be true for this portion of the code but the variable could later be manipulated to become another value. <br /> <br /> Now that these values are stored in variables I can output them using the <a href="https://kenpythonic.blogspot.com/2019/06/what-is-python.html">print command we learned earlier</a>: <!-- HTML generated using hilite.me --><br /> <br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <table><tbody> <tr><td><pre style="line-height: 125%; margin: 0;">1 2 3 4 5</pre> </td><td><pre style="line-height: 125%; margin: 0;">a <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">1</span> b <span style="color: #333333;">=</span> <span style="color: #0000dd; font-weight: bold;">100</span> <span style="color: #008800; font-weight: bold;">print</span>(a) <span style="color: #008800; font-weight: bold;">print</span>(b) </pre> </td></tr> </tbody></table> </div> <br /> If you type this in to a python shell or in a python program you will get the output: <!-- HTML generated using hilite.me --><br /> <br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"> 1 100 </pre> </div> <br /> <br /> <span style="font-size: large;"><a href="https://kenpythonic.blogspot.com/2019/06/more-about-variables.html">Continued On -&gt; More About Variables in Python</a></span><br /> <br /> <br /> <a href="https://www.w3schools.com/python/python_variables.asp">https://www.w3schools.com/python/python_variables.asp</a>&nbsp;- More about Variables<br /> <br /> <a href="https://www.amazon.com/gp/product/B07RB18XH4/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=B07RB18XH4&amp;linkCode=as2&amp;tag=startiprogra-20&amp;linkId=28fc1370adbabfdcaa654b192c609c70" target="_blank">Python Programming: A Practical Introduction To Python Programming For Total Beginners</a><img alt="" border="0" height="1" src="//ir-na.amazon-adsystem.com/e/ir?t=startiprogra-20&amp;l=am2&amp;o=1&amp;a=B07RB18XH4" style="border: none !important; margin: 0px !important;" width="1" /> <br /> <br /> Note: I use the term <i>declare</i> to describe how to create a variable in python. If I am honest I have told a white lie. To <i>declare</i> a variable usually means that it has to be predefined before it is used. In python its first use automatically declares it. For someone learning python I think this is splitting hairs and it is inevitable that programmers are going to ask "How do I declare a variable in python" and the python zealots will respond with "One does not declare variables in python".Kenneth Parkerhttp://www.blogger.com/profile/13907305526364974493[email protected]0tag:blogger.com,1999:blog-7020411281490343654.post-45158724715656774992019-06-09T09:57:00.000-07:002019-06-29T10:06:15.921-07:00What is PythonPython is a powerful dynamic, interpreted ( actually byte compiled ) programming language that is extremely useful and widely used. Because of its popularity there is a large amount of amount of documentation, example programs, books, blogs and open source libraries available.<br /> <br /> Python is also widely used in both commercial and open source projects, and it has the ability to compile to native executable, java, and .NET<br /> <br /> Although I believe python has a very strong object oriented syntax, my favorite aspect of the language is its ability not to force you in to an object oriented solution. Instead, you can write very simple and very powerful python programs without understanding or needing to use classes, dependency injection or other advanced object oriented concepts.<br /> <br /> Having programmed for many years, I wanted to get back to basic programming and engineering concepts that are fundamental and did not rely on modern design patterns and practices.<br /> <br /> <a href="https://www.python.org/">https://www.python.org/</a><br /> <br /> <br /> One of the best tells of an easy programming language is how easy it is to get started. If you have an internet browser you can navigate to&nbsp;<a href="https://www.python.org/shell/">https://www.python.org/shell/</a>&nbsp;and type in the provided <i>python shell </i>and immediately begin to learn python.<br /> <br /> <h3> Hello World</h3> <div> The traditional way to begin learning a programming language is with the Hello World program and in python it is very simple:</div> <div> <br /></div> <div> <br /></div> <!-- HTML generated using hilite.me --><br /> <div style="background: #ffffff; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;"> <pre style="line-height: 125%; margin: 0;"><span style="color: #008800; font-weight: bold;">print</span> <span style="background-color: #fff0f0;">'hello world!'</span> </pre> </div> <br /> The above program simply prints the words "Hello World" to the given terminal. It is an output only program and that is very easy to write and maintain!<br /> <br /> <h4> Useful Links</h4> <br /> <a href="https://www.w3schools.com/python/">https://www.w3schools.com/python/</a>&nbsp;- One of the best to the point python tutorials available.<br /> <br /> <br /> <a href="https://realpython.com/installing-python/">https://realpython.com/installing-python/</a>&nbsp;- Guide to installing python<br /> <br /> <br /> <br /> <br /> O'Rielly books are really good and I would suggest purchasing one if you want to learn more about python. <iframe style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=tf_til&ad_type=product_link&tracking_id=startiprogra-20&marketplace=amazon&region=US&placement=1449355730&asins=1449355730&linkId=d165ea4b93d872c856c30dc166a59d28&show_border=true&link_opens_in_new_window=true&price_color=333333&title_color=0066C0&bg_color=FFFFFF"> </iframe>Kenneth Parkerhttp://www.blogger.com/profile/13907305526364974493[email protected]2