Sunday, February 25, 2018

Methods


Methods in Python have both similarities and differences to Java and other languages. Now that we have explored the concepts of loops and conditionals and are aware of some Python syntax, structure, and indentation rules, looking at the nature of methods is a good next step!

Basic Structure

  • First off, in Python, a class is necessary to run a method, so we must create one followed by a colon. 
  • Then, after an indentation, you need to define your method using the word 'def' followed by the name of the method. After the name of the method, in parentheses, we need to type the word 'self.' By convention, this is always the first argument in a method, so whether we have arguments to pass in or not, we need 'self' to refer to the newly created object. As in other Python code structures like loops and conditionals, we end this line with a colon. 
  • Following another indentation on the next line, we code what we want the method to accomplish. In the following example, I simply have a print statement, but methods can have multiple lines and statements in this section as long as they adhere to Python indentation rules.
  • Finally, to call the method, we call the method within the class. The example below is a very basic picture of what a Python method looks like: 




Constructor and Instance Variables

Now that we know the basics, let's define instance variables inside methods. The  __init__ constructor method is called once for any object of a class. In this example, we add numbers by passing parameters into the constructor. We define the instance variable sum within the method and then outside of the method, we print it. 



Note that alternatively, we would get the same result as the above program without using an instance variable, but my goal with the above example was to show how instance variables can be incorporated into methods:


We can also get the same result by calling our own created method instead of the constructor. When we write a method without a constructor, Python executes a default constructor that doesn't do anything. The difference between the code below and the code right above is that we have to create an object (adding) of the Addition class. The following method follows the same formula as the Basic Structure example.



Main Method

As in other object-oriented programming languages, we can use a main method to call all of our other methods. This is the sort of structure we would want to use as our programs become more complex and developed. The example below shows some key features of the main method:
  • Notice first that the final line of code calls to execute the main method. Without this, nothing happens.
  • In the Dog class, we declare class variables, define a constructor method, and define another method called set_score.
  • In the main method we create objects and pass in variables to run the constructor method to set up that object's instance variables.
  • We can print instance variables as well as class variables for a particular object from the main method.
  • We can call the method set_score in the Dog class from the main() method.




Lessons

There are different ways to do things to do things in Python. For example, instead of simply writing "main()" at the end of my program, I could have written a longer statement: 

if __name__=="__main__": main()

This is what my source was directing me to do. At first I did not understand it, so I looked up the purpose of this lengthy and confusing statement. In Python, __name__ is set to __main__ whenever a file is being executed, so when you run your program, if __name__=="__main__" returns true, which executes main(). But I found that if I eliminate the conditional my program still works. I am sure there are cases when the conditional is necessary, but in my case it was not. The lesson learned was that not everything is as complicated as sources might tell you, so it's worth monkeying around on your own to find what might be a simpler and more understandable version of your code.

Also, when I was putting this together, I was getting quite a few errors for various little things here and there. I think most of them were related to a struggle to remember how object oriented programming works, so if you've been away from this type of programming, I hope this post was a nice refresher!



Sources:

https://stackoverflow.com/questions/3786881/what-is-a-method-in-python
https://www.digitalocean.com/community/tutorials/understanding-class-and-instance-variables-in-python-3
https://stackoverflow.com/questions/22492162/understanding-the-main-method-of-python

Sunday, February 18, 2018

Repeated Action Syntax

There are two types of loops in Python, the for loop and the while loop.

Important to note: In loops, as in conditional statements, indentation matters.

For Loop:

The syntax for for-loops is the following:


The following example shows how we can print each letter of a word, using a loop. Since Python is dynamically typed, the program recognizes that word is a string variable, so the loop prints every letter of word. This is an example of strings as an iterable:

                

We can do something similar with numbers, looping through an array:



We can also nest conditionals inside of loops. Python uses "continue" and "break" statements to control the flow of the loop; the word "continue" causes the loop to skip the current block and return to the top for or while statement, whereas "break" stops the loop. These key words are not mandatory for loops and they can be used alone or together; they can be very useful and provide a quick solution in certain circumstances and a feature that other languages lack. In the example below, we skip even numbers and print the odd numbers in a range from 1-10:


The next example adds two lines to the code above to demonstrate how we can end a loop. Here we end the loop before printing the number 9:


While Loop:

While loops in Python follow a similar syntax to for loops:

In the following program, we add two at the end of each loop, resulting in even numbers 0-8:


        

We can use "continue" and/or "break" in while loops as well:


         

Nested Loops:

In Python, we can nest loops. The following program is an algorithm that prints prime numbers from one to one hundred. The outer loop runs through integers (i) two to ninety-nine. The inner loop loops through integers (j) that could be possible divisors of (i). If (j) does not divide (i) and (j) is greater than (i/j), (i) is prime. Until we reach a (j) that divides (i), we loop until (j) is greater than (i/j), so (i) is prime.

                                

                      


We can nest for loops in a similar way. The following example is a simple one that I made up to multiply numbers zero through nine by each number in the list containing one, two, and three:

             

         

It is also possible to put a for loop in a while loop and vice versa. Often times, we use nested loops to cycle through items in a list. The following method demonstrates this possibility in Python. Note how the conditional with the boolean here acts like the 'break' statement described previously to end the iterations of the loop:




In coding, there is usually more use for a while loop inside of a for loop than a for loop inside of a while loop, so I will not provide an example of the latter, but it is possible.

Else Statements in Loops:

Unlike languages like C, in Python, we can execute an "else" statement upon the completion of a loop. In the second loop below, the the loop is terminated before the end of it's iterations, so the else statement does not get executed.

   

Else statements in loops were a new concept to me, and they seem to be useful checks for when a loop has completed its rounds.


Also, in Python loops can be infinite. The following program will run forever unless you stop it, so be careful!


Response to Michelle's first comment:

Great question! In a 'for’ loop, to increment by a number other than one, you add parameters to range. The following code shows an example of this. The 'step' is whatever increment you want to add through every iteration of the loop:

             


Note if you were to use a while loop, the syntax to increment a variable would be: "i += number_you_want_to_add," and examples of this are included in my post.


Sources:

https://swcarpentry.github.io/python-novice-inflammation/02-loop/
https://www.learnpython.org/en/Loops
https://www.tutorialspoint.com/python/python_nested_loops.htm
https://stackoverflow.com/questions/21930663/while-loop-inside-of-for-loop

Sunday, February 11, 2018

Conditional Statements

Python's conditional statement structure has differences that I have not come across in other languages. What I believe is the most important point is that unlike other programming languages, indentation matters!

I was surprised when I first ran a simple code sample, which I had found online, that it did not work, considering that I had the same exact language as I was supposed to. When I fixed my indentation, everything worked. It is important, when coding in Python, to observe the proper structure of your conditional statements, especially the use of white space, because, whereas white space doesn't matter in other aspects of coding in Python, for conditional statements, its use is critical.

The three key words for conditional statements in Python are "if," "elif," and "else." These words introduce conditions and can form a simple constructs or more complex nested conditional statements.

Comparison operators in Python, which are used in conditions and result in the answer of true or false, are mostly the same as we are used to in languages such as Java. They include ==, !=, <> (same as !=), <, >, <=,  and >=.

A colon must follow immediately after every condition, and statements and nested conditions must be indented. Multiple statements can follow a single condition (see the last two lines in the code sample below). The following snippet, demonstrates Python conditional syntax:



The result is:



Conditional statements in Python are pretty easy to get used to, but definitely watch out and make sure you use proper language ("elif," not "else if"), colons after conditions, and proper indentation!


In response to the questions left in the comments:

There is a something like a ternary conditional in Python. Two examples are provided below, using the Python shell, yielding immediate results:



Additionally, one is certainly able to construct as simple if-statement in Python. And here is an example of that, using a Python module followed by a snip of the output code from the shell:




Sources:

https://www.tutorialspoint.com/python/nested_if_statements_in_python.htm
https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator

Sunday, February 4, 2018

Variables and Arithmetic Operations

There are three main categories of variables in Python: integers, floats, and strings.

What makes variables easy to use in Python is that you do not have to declare the type. The programmer keeps track of the variable type. For example, you can code num=9 and later num='Bob,' and Python doesn't care. In addition, variables do not need to be declared before use; you simply think of a name and start using the variable. This makes Python a dynamically typed language.


In Python, you cannot declare a variable as a constant. Instead, variables hold constants, and we typically use all caps to denote that a certain variable is a constant, though it can be changed later in our code, just like any variable. If you want a variable to stay constant, just don't change it.

Note that in Python, strings can be defined with either single or double quotes, whereas other languages are much more picky about this syntax.


Yet another interesting Python feature allows you to declare multiple variables in a single line:


The following snip of code demonstrates various uses of variables and arithmetic operations in Python, including modular arithmetic and variable casting. The code is written in the Python Shell, so it executes each line immediately.



In addition to the usual arithmetic operations, if you import the math module, you can use Python's built-in functions (which include mathematic constants like pi, e, and tau).


Sources:
General Variable Use
Very Good Source on Variables and Data Types in Python
Another Great Source on Variables
Powers and Roots