Python Lesson 6: Loops

Advertisements

Hello everybody,

It’s Michael, and today’s Python lesson will be on loops. Like Java, Python also has loops, but while Java has three main types of loops, Python only has two-while and for. There is no do-while loop in Python.

Let’s start by discussing the while loop. The Python while loop works the same as its Java counterpart since both loops will keep running WHILE a certain condition is true. Here’s a demonstration of a Python while loop:

x = 10
y = 1
while (y <= 6):
print(x**y)
y += 1

And here’s the output:

10
100
1000
10000
100000
1000000

In this while loop, successive powers of 10 are printed as long as y is less than or equal to 6; y is also incremented by 1 with each iteration of the loop. In other words, the first 6 powers of 10 (from 10^1 to 10^6) will be printed.

One thing to keep in mind is that, even though Python while loops work the same as their Java counterparts, the syntax between the two while loops differs. However, the difference is fairly minor, as Python would use a colon to denote the loop, while Java would use a pair of curly brackets.

Now, let’s make things a little more complex by adding the break statement. Here’s a sample program:

x = 1936
while (x <= 2020):
print(x)
x += 4
if (x % 7 == 0):
break

And here’s the output:

1936
1940
1944
1948
1952
1956

One thing to remember with the break statement is that it gives the loop another condition to evaluate. Loops with a break statement will keep running until either one of two conditions has been met. In the example above, the program will keep printing numbers (starting from 1936) and increasing them by 4 after each iteration until either 2020 (or the closest possible number to 2020) OR a number evenly divisible by 7 has been reached. In this case, 1960 would be the first number evenly divisible by 7, but the program will stop printing at the closest possible number-1956.

Now let’s try implementing a continue statement:

x = 2
while (x <= 20):
x += 2
if (x == 10):
continue
print(x)

And here’s the output:

4
6
8
12
14
16
18
20
22

Unlike the break statement, the continue statement won’t stop running a loop if a certain condition is met. Rather, if a certain condition is met, the continue statement will skip a certain iteration of the loop but then continue to run the loop. In this example, x is 2 and will keep increasing by 2 until x reaches 20. However, the continue statement says if (x == 10) continue. This means that 10 will not be displayed in the final output; rather, the program will jump from 8 to 12, as it was told to skip 10.

Now I’ll discuss for loops in Python. They are similar to their Java counterparts, except that they don’t require an indexing value to be set beforehand.

  • In case you’re wondering, the x in all of my while loop examples is an indexing variable. In Python while loops, an indexing variable acts as a “guide” by telling the loop where to start.

Another difference between Python for loops and their Java counterparts is that Python for loops are mostly used just to run through sequences of characters or Strings while Java for loops have more mathematical capabilities. In other words, with Java for loops, you’re able to do calculations with each iteration, but that isn’t possible with Python for loops. However, you can run through basic number sequences with Python for loops, which I will explain later.

Let’s demonstrate a basic Python for loop:

for y in “Michael”:
print(y)

And here’s the output:

M
i
c
h
a
e
l

In this program, I have a basic for loop that will run through all the letters in my name-Michael-and print out each letter one by one.

Notice that the syntax for Python for loops is much simpler than for their Java counterparts. In Java, you would need one line with three different statements whereas in Python, you only need one line for one statement, which always goes like for _____ in _____ followed by the body of the loop.

Now let’s try adding a break statement with a for loop:

teams = [“Heat”, “Cavaliers”, “Timberwolves”, “76ers”, “Jazz”]
for y in teams:
print(y)
if (y == “76ers”):
break

And here’s the output:

Heat
Cavaliers
Timberwolves
76ers

In this example, the loop will run through all of the elements in this sequence before stopping once it reaches the 76ers element, which will be the last element displayed in the output.

Now let’s try a for loop with a continue statement:

teams = [“Heat”, “Cavaliers”, “Timberwolves”, “76ers”, “Jazz”, “Nets”, “Hawks”]
for y in teams:
if (y == “Jazz”):
continue
print(y)

And here’s the output:

Heat
Cavaliers
Timberwolves
76ers
Nets
Hawks

In this program, the loop will run through MOST of the elements, but Jazz will be skipped, since that’s where the loop will continue.

  • One thing I wanted to mention is that, with both for and while loops, if you have a break statement in the loop, put the print before the break statement. However, if you have a continue statement, put the print after the continue statement.

Now, I did mention that even though Python for loops aren’t capable of doing much in the way of calculations, they are capable of running through basic number sequences. Here’s an example:

for y in range(11):
print(y)

And here’s the output:

0
1
2
3
4
5
6
7
8
9
10

In this program, the range(11) function will print out 11 numbers. You might be thinking “What 11 numbers?”. You might be thinking the numbers 1-11 will be printed, but that is a common misconception. Whenever the range(N) function is used, the first number printed will always be 0, with each successive number being incremented by 1, until N-1 is reached, which is 10 in this case.

However, range() sequences don’t always have to begin with 0. Here’s an example of that:

for y in range(4, 13):
print(y)

And here’s the output:

4
5
6
7
8
9
10
11
12

In this example, range() has the parameters 4, 13. The program then prints out numbers between 4 and 13, but not including 13 (I’m not totally sure why 4 was printed but 13 wasn’t, but I guess it’s one of those weird coding rules).

Another thing about the range() function is that, even though it defaults to an increment by 1 pattern, you can change the increment pattern simply by adding a third parameter. Here’s how:

for y in range(20, 100, 14):
print(y)

And here’s the output:

20
34
48
62
76
90

In this program, range() has the parameters 20, 100, 14. The program will print out numbers between 20 and 100 using an increment by 14 pattern. The loop will stop running when it has reached the closet possible number to 100 (using the increment pattern).

You can also use decrement patterns in your for loops. Here’s how:

for y in range(112, 16, -8):
print(y)

And here’s the output:

112
104
96
88
80
72
64
56
48
40
32
24

In this program, the parameters for range() are 112, 16, -8. The program will start by printing 112; each subsequent number will be decreased by 8 until the closest possible number to 16 (using this pattern) is obtained. If 16 can be reached with this pattern (which it can), it will not be printed.

  • With increments, make sure your second number is greater than your first. On the other hand, with decrements, make sure your first number is greater than your second.
  • Also, remember to make the third parameter negative to denote a decrement pattern.

Now, let me show you what the else statement can do in a for loop:

for y in range(112, 16, -8):
print(y)
else:
print(“All done”)

And here’s the output:

112
104
96
88
80
72
64
56
48
40
32
24
All done

The else statement in a for loop is simple to understand, as it tells the loop what to do (or what to print) when it finishes iterating. In this case, the program prints out the same thing as the previous example along with the message All done when the loop is finished iterating.

Last but not least, I want to  demonstrate and discuss the concept of a nested for loop. Here’s an example:

adj = [“young”, “old”, “hairy”, “playfu]”]
animal = [“dog”, “cat”, “ferret”, “hamster”]
for x in adj:
for y in animal:
print(x, y)

And here’s the output:

young dog
young cat
young ferret
young hamster
old dog
old cat
old ferret
old hamster
hairy dog
hairy cat
hairy ferret
hairy hamster
playfu] dog
playfu] cat
playfu] ferret
playfu] hamster

In this example, the program will print out one element from adj (or x) and one element from animal (or y). Since x is the first parameter of print adj (or adjective) will print first followed by y (or animal). In other words, the adjective describing the animal will be printed first, followed by the name of the animal. Since this is a loop, every animal’s name will appear once alongside every adjective.

But what if there weren’t the same amount of elements in each sequence? Here’s an example of that case (it’s the same program with the word hamster omitted):

adj = [“young”, “old”, “hairy”, “playfu]”]
animal = [“dog”, “cat”, “ferret”]
for x in adj:
for y in animal:
print(x, y)

And here’s the output:

adj = [“young”, “old”, “hairy”, “playfu]”]
animal = [“dog”, “cat”, “ferret”]
for x in adj:
for y in animal:
print(x, y)

So, even though I omitted a word, essentially nothing changes (well, aside from the omitted word). Each animal’s name still appears once alongside every adjective.

  • For the record, you can’t create nested while loops.

Thanks for reading,

Michael

Python Lesson 5: Conditional Statements & User Input

Advertisements

Hello everybody,

It’s Michael, and today’s lesson will be on conditional statements in Python. I covered Java conditional statements in Java Lesson 4: IF-ELSE statements & Logical/Comparison Operators, and in case you’re wondering, “conditional statements” is a more technical way of saying “if-else statements” (or “if statements” and “else statements”, for that matter). I will also cover user input in Python.

Just like Java, Python has if, else, and else if statements, except in Python, else if is referred to as elif. The logic behind conditional statements in Python is the same as in Java. By that I mean in any group of conditional statements, if will always come first, followed by any elif statements and an else statement at the end of the group. Here’s an example program with conditional statements (since I wrote this for explanatory purposes, I won’t have any sample output):

if (score >= 300) and (score <= 579); print (“POOR”)

elif (score >= 580) and (score <= 679); print (“FAIR”)

elif (score >= 680) and (score <= 739); print (“GOOD”)

elif (score >= 740) and (score <= 799); print (“VERY GOOD”)

else; print (“EXCEPTIONAL”)

In this program, there is a variable called score (a reference to FICO Credit Score) and based on the value of that variable, one of five things will be displayed-POOR, FAIR, GOOD, VERY GOOD, and EXCEPTIONAL. If the if statement is not true, each of the elif statements will be analyzed from the top down to see which one is true; once a true statement is found, any code on that statement will be executed and the compiler will stop analyzing the group of conditional statements. If neither the if statement nor any of the elif statements are true, then the else statement will execute.

Now. everything I just said will hold true in most cases, provided score falls between 300 and 849 inclusive. But what if the value of score was outside that range? You would simply write another elif statement that goes something like elif (score >= 800) and (score <= 850); print ("EXCEPTIONAL"). You would also have to revise the else statement so that it reads something like else; print ("NOT POSSIBLE"). By writing the new elif statement, the compiler will know to print out ERROR if score isn’t between 300 and 850 inclusive.

Now, let’s demonstrate conditional statements. Here’s a simple example:

rt = 78
if (rt >= 60) and (rt <= 100):
print(“fresh movie”)
else:
print(“rotten movie”)

And here’s the output:

fresh movie

Using Rotten Tomatoes’ movie scoring system as an example (the rt refers to Rotten Tomatoes score), the compiler will print out “fresh movie” if rt is between 60 and 100 and “rotten movie” if rt is below 60. Since rt is 78 (that’s the current score for the movie Good Boys), “fresh movie” will be displayed.

Now, here’s a more complex conditional statements example, with several elif statements:

IGN = 6.6
if (IGN == 10):
print(“MASTERPIECE”)
elif (IGN >= 9) and (IGN <= 9.9):
print(“AMAZING”)
elif (IGN >= 8) and (IGN <= 8.9):
print(“GREAT”)
elif (IGN >= 7) and (IGN <= 7.9):
print(“GOOD”)
elif (IGN >= 6) and (IGN <= 6.9):
print(“OKAY”)
elif (IGN >= 5) and (IGN <= 5.9):
print(“MEDIOCRE”)
elif (IGN >= 4) and (IGN <= 4.9):
print(“BAD”)
elif (IGN >= 3) and (IGN <= 3.9):
print(“AWFUL”)
elif (IGN >= 2) and (IGN <= 2.9):
print(“PAINFUL”)
elif (IGN >= 1) and (IGN <= 1.9):
print(“UNBEARABLE”)
else:
print(“DISASTER”)

And here’s the output:

OKAY

Using IGN’s gaming review scoring system in this example, the compiler will look at the value of IGN (referring to a game’s IGN score) and based on that value, will first analyze the if statement, then all of the elif statements from the top down, and finally the else statement (which will only be analyzed if neither the if statement nor the elif statements are true). Remember that the compilers will stop analyzing once it finds a true statement, which in this case would be elif (IGN >= 6) and (IGN <= 6.9) (which would print out OKAY).

  • Also remember that a colon would come after each conditional statement (in other words, right before the block of code that’s supposed to be executed with a particular statement). Unlike Java, there’s no need to place the code that goes with conditional statements in brackets (and you’ll likely get an error if you do so).

Now, one thing I would like to mention is that you can sometimes write conditional statements in a handy little shorthand.

Let’s use the if-else Rotten Tomatoes score example. Here’s the shorthand way of writing that program:

print(“fresh movie”) if (rt >= 60) and (rt <= 100) else print(“rotten movie”)

Even though you will need to assign a value to rt on a separate line, you can still write the if–else statement on the same line. However, if you’ve got multiple elif statements (like the IGN example), then this approach will not work.

Now, what if the value of a certain variable wasn’t already set. What if you needed to set the value of a certain variable?

This brings me to the next topic I will cover in this post-user input in Python. Just like Java, Python also allows for user input. Using the IGN scoring program from a previous example, here’s how to handle user input in Python:

IGN = float(input(“Give me an IGN score: “))
if (IGN == 10):
print(“MASTERPIECE”)
elif (IGN >= 9) and (IGN <= 9.9):
print(“AMAZING”)
elif (IGN >= 8) and (IGN <= 8.9):
print(“GREAT”)
elif (IGN >= 7) and (IGN <= 7.9):
print(“GOOD”)
elif (IGN >= 6) and (IGN <= 6.9):
print(“OKAY”)
elif (IGN >= 5) and (IGN <= 5.9):
print(“MEDIOCRE”)
elif (IGN >= 4) and (IGN <= 4.9):
print(“BAD”)
elif (IGN >= 3) and (IGN <= 3.9):
print(“AWFUL”)
elif (IGN >= 2) and (IGN <= 2.9):
print(“PAINFUL”)
elif (IGN >= 1) and (IGN <= 1.9):
print(“UNBEARABLE”)
else:
print(“DISASTER”)

And here’s the output if I use 5.1 as the value of IGN:

Give me an IGN score: 5.1
MEDIOCRE

In Python, user input is much simpler than it is in Java. In Java, you have to import a Scanner class for user input AND create a separate Scanner variable (along with familiarizing yourself with all the methods in the Scanner class). With regards to user input, Python is much simpler to use, as it has a built-in user input function-input()-so there is no need to import anything. As a result, it only take one line of code to handle user input in Python, as opposed to the three or four lines of code it can take in Java.

I have three important tips regarding user input in Python, which include:

  • You don’t technically need put in any parameters for the input() method, but it’s suggested that you do so, as I did with input(Give me an IGN score: ).
  • You can set the value of certain variable to the user’s input, as I did with the value of IGN.
  • The default type of user input in Python is String, so if you want to set the user input to another type, write something like this other type(input(text for input)). In my IGN example, I wanted input of type float, so I wrote IGN = float(input(Give me an IGN score: )). By writing this, my input for IGN would be read as float and not String.

Thanks for reading,

Michael

 

Python Lesson 4: Math & Logic

Advertisements

Hello everybody,

It’s Michael, and today’s lesson will be on Python math and logic, with an emphasis on mathematical and logical operators in Python.

First, we’ll start off with mathematical operators. Python has seven mathematical operators, which include +, -, *, /, %, ** and //. If you know Java (or basic arithmetic for that matter), then the first four operators would look very familiar to you, since they are the addition, subtraction, multiplication, and division operators, respectively.

However, let’s discuss the other three operators-%, **, and //. % is the modulo operator, which is what we would use for modular division. For those unfamiliar with the concept, modular division is similar to regular division, except you are trying to find the remainder of two numbers instead of the quotient. For instance, 11%4 (read as 11 mod 4) is 3, since 11 divided by 4 is 2 with a remainder of 3.

** is the exponentiation operator. This one is pretty simple to explain, since this would be the operator you would use if you want to raise a number to a certain power. That’s all. For example, 8 cubed in Python would be 8**3. This is much simpler than using Java’s Math.power() function (which requires importing a class-not the case with Python).

// would probably look the most unfamiliar to you (I had to look it up the first time I saw it). This is the floor division operator, and I’ll admit that, even though I do lots of coding, I’ve never heard of the concept of floor division. Apparently, floor division is a very simple concept, as it is regular division with any decimal points removed from the quotient. However, keep in mind that floor division rounds DOWN to the nearest integer, so in a division problem like 20/7 with a simple division quotient of 2.86 (rounded to two decimal places), the floor division quotient would be 2, not 3.

Another thing to keep in mind with floor division is that, if either the dividend or divisor is negative, the quotient will also be rounded down, but it will be rounded away from 0 NOT towards 0. For example, -20/7 has a simple division quotient of -2.86 but a floor division quotient of -3, not -2. So when I say a negative floor division quotient would be rounded away from 0, I mean that the quotient will be rounded to the LOWER negative number, not the higher negative number.

Now, let’s see the %, **, and // operators in action:

a = 30 % 8
b = 6**3
c = 177 // 33
print(a)
print(b)
print(c)

And here’s the output:

6
216
5

The answer for a-6-is displayed first. 30 mod 8 is 6, meaning that 30 divided by 8 will give you a remainder of 6. The answer for b-216-is displayed next. 6 cubed is 216. The answer for c-5-is displayed last. The simple division quotient (rounded to two decimal places) is 5.36, so the floor division quotient is rounded down to 5.

Now let’s demonstrate some PEMDAS (remember this?) in Python:

a = 4 – (2 + 5) * 11 / 2
print(a)

And here’s the output:

-34.5

OK, so this is a simple enough problem. Parentheses come first, so (2+5) would be solved first; you would get a result of 7. 7 would then be multiplied by 11 to get 77, which would then be divided by 2 to get 38.5, which would be subtracted from 4 to get the final result of -34.5.

Now let’s try something a little more complex:

a = 100 // (16 + 2) – 31 + 3**4 / (6 * 12) * 15 % 6
print(a)

And here’s the output:

-21.125

Here’s a breakdown showing how to get to the final answer:

  • 100 // (16 + 2) - 31 + 3**4 / (6 * 12) * 15 % 6
  • 100 // 18 - 31 + 3**4 / 72 * 15 % 6
  • 100 // 18 - 31 + 81 / 72 * 15 % 6
  • 5 - 31 + 1.125 * 15 % 6
  • 5 - 31 + 16.875 % 6
  • 5 - 31 + 4.875
  • -26 + 4.875
  • -21.125

Keep in mind that with order of operations in Python, the % and // operators are treated with the same precedence as the simple division operator (/).

Next, I’ll cover comparison operators, which are used to compare two values. There are 6 comparison operators in total-==, !=, >, <, >=, <=, which respectively represent:

  • Equal to
  • Not equal to
  • Greater than
  • Less than
  • Greater than or equal to
  • Less than or equal to

Statements with these logical operators will either return true or false. Let’s demonstrate the comparison operators:

a = (13 + 11) == 24
b = (41 + 16) != 66
c = (15 > 29)
d = (41 < 23)
e = (13 >= 9)
f = (55 <= 22)
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)

And here’s the output:

True
True
False
False
True
False

So, in order, here’s the result for each statement:

  • a-TRUE
  • b-TRUE
  • c-FALSE
  • d-FALSE
  • e-TRUE
  • f-FALSE

The next thing I wanted to discuss are the three logical operators-and,or, and not. The logical operators work just as they do in Java, except in Python, you would words instead of the symbols &&, ||, and !-which are and, or, and not, respectively. However, the logic behind these operators is the same as in Java. By this I mean:

  • For two statements combined with and, both of the individual statements must be true for the statement pair to be true. If one of the statements is false, then both are false.
  • For two statements combined with or, only one of the statements must be true for the statement pair to be true. However, if both statements are false, then the whole statement pair is false.
  • Statement pairs with not often contain an and or or as well (e.g. not(statement pair a or statement pair b)). The statement pair in parentheses would first be evaluated, and the result would be whatever the opposite of the result from the statement pair. For instance, if the statement pair was true, then (assuming there is a not), the result would be false, and vice versa.

Let’s start with a simple demonstration of logical operators:

m = (14 > 19) and (15 + 12 != 33)
o = (51 >= 16) or (9 – 2 > 6)
f = not(14**2 < 28 and 13 % 9 <= 1)
print(m)
print(o)
print(f)

And here’s the output:

False
True
True

The results to each statement are:

  • m-FALSE
  • o-TRUE
  • f-TRUE

Now, let’s try something slightly more complex with logical operators:

m = (14 < 19) and (23 >= 11) or (100 % 16 > 7)
print(m)

And here’s the output:

True

How did we get this result? First of all, keep in mind that the statement pairs will be evaluated from left to right (just as they would in order of operations problems). The result of the first statement pair-(14 < 19) and (23 >= 11)-is true, so that result would be evaluated with the second statement-(100 % 16 > 7)-which is also true. Since we are dealing with two trues and an or, the entire statement group is true.

Next, we’ll discuss the two identity operators-is and is not-which also function as comparison operators. However, these operators don’t evaluate whether or not two objects are equal or not; rather, these operators test whether or not two values are the same object with the same memory location. I know that sounds like a lot of coding jargon, so here’s a program to demonstrate identity operators:

a = (“ant”,”bear”,”cat”,”dog”,”eel”)
b = (“ant”,”bear”,”cougar”, “dog”, “eel”)
print(a is b)
print(a is not b)

And here’s the output:

False
True

A simple way to explain this program is that I’m trying to test whether a and b have the exact same values. The first statement-a in b-is false because a and b do not have the exact same values. However, the second statement-a not in b-is true because a and b do not have the exact same values.

An easy way to remember identity operators is that, when comparing two lists, is means the two lists are exactly alike while is not means that the two lists aren’t exactly alike.

Finally, let’s cover the concept of membership operators. Like identity operators, there are two membership operators-in and not in-and both identity and membership operators are used with lists. Here’s a program demonstrating identity operators:

a = (“carrot”, “celery”, “squash”, “cucumber”, “eggplant”)
print(“squash” in a)
print(“squash” not in a)

And here’s the output:

True
False

In this program, I am testing whether or not squash is in my list (a). Just as with the previous program, I used both possible operators-in and not in-to see which one would give me true and which would give me false. The first statement-squash in a-is true, meaning that squash is in list a. Thus, the second statement-squash not in a-is false.

Thanks for reading,

Michael

Python Lesson 3: Python Strings

Advertisements

Hello everybody,

It’s Michael, and today’s lesson will be on Python Strings. I know I mentioned Strings in the previous post, but I will go into greater depth with Strings this time.

Alright, let’s open up Anacoda, launch Spyder, and start our programming!

I’m going to start with Strings. Here’s a very simple sample program:

print(‘Hello friend’)
print(“Hello friend”)

And here’s the sample output:

Hello friend
Hello friend

Notice that even though I used single quotes for the first line and double quotes for the second line, I got the same output. That’s because in Python, you can write Strings with either single or double quotes (which is not the case with Java). But keep in mind that you must always use quote pairs (a quotation mark at the beginning and end of the String)

  • You can assign strings to variables, just as you can with numbers.

However, note that multi-line strings require three sets of quotes, whether single or double. And just as with single-line strings, place the quotes at the beginning and the end of the String. Here’s a sample program with a multi-line String:

a = “””The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…”””
print(a)

And here’s the output:

The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…

Notice how the String is printed as it is displayed on the code; this is because multi-line Strings will print the code exactly as it is displayed on the compiler (which is the place where you write the code).

  • Fun fact-I got the String from Interlude, which is a track from Jay-Z’s The Black Album (2003).

Now I will show you six common methods used with Python Strings-strip(),len(), lower(), upper(), replace(), and split(). What do each of these methods do? Well, here’s a breakdown:

  • strip()-removes any white-space in the String
  • len()-returns the length of a String
  • lower()-prints the String in all lowercase
  • upper()-prints the String in all uppercase
  • replace()-replace a String with another String
  • split()-split a String into sub-strings wherever a separator is found; the separator could be something like a period or a comma.

Now let’s demonstrate each method, using the multi-line String from the previous example. Here’s a sample program with the strip() method:

a = “””The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…”””
print(a.strip())

And here’s the output:

The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…

Since there was no white-space in the String, the output is the same as the input. In other words, without any white-space, there’s no need to alter the String.

Now let’s try the len() method:

a = “””The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…”””
print(len(a))

And here’s the output:

775

Since the len() method counts the number of characters in a String, 775 means that there are 775 characters in this String.

Now let’s try the lower() method:

a = “””The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…”””
print(a.lower())

And here’s the output:

the other night when i was researching what was going to be discussed today i came across a passage wrote down, i think it really exemplifies what the young brother next to me was just talking about and i learned that all things must come to an end
it is an inevitable part of the cycle of existence, all things must conclude
take the analogy of a tree that grows in brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
that came before
that came before
that came before
that came before…

Here’s the upper() method:

a = “””The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…”””
print(a.upper())

And here’s the output:

THE OTHER NIGHT WHEN I WAS RESEARCHING WHAT WAS GOING TO BE DISCUSSED TODAY I CAME ACROSS A PASSAGE WROTE DOWN, I THINK IT REALLY EXEMPLIFIES WHAT THE YOUNG BROTHER NEXT TO ME WAS JUST TALKING ABOUT AND I LEARNED THAT ALL THINGS MUST COME TO AN END
IT IS AN INEVITABLE PART OF THE CYCLE OF EXISTENCE, ALL THINGS MUST CONCLUDE
TAKE THE ANALOGY OF A TREE THAT GROWS IN BROOKLYN AMONG THE STEEL AND THE CONCRETE WITH ALL ITS GLORIOUS BRANCHES AND LEAVES, ONE DAY IT TOO WILL PASS ON ITS LEGACY THROUGH THE SEEDS IT DROPPED TO THE GROUND AND AS THE WIND CARRIES THESE SEEDS THROUGHOUT WHEREVER THEY MIGHT MOVE A NEW LIFE WILL BEGIN FOR EACH ONE OF THEM AS THEY STAND AS A MONUMENT TO THE ONE THAT CAME BEFORE
THAT CAME BEFORE
THAT CAME BEFORE
THAT CAME BEFORE
THAT CAME BEFORE…

Notice that the upper() and lower() methods are written as string name.upper() and string name.lower()and don’t have any parameters.

Now let’s try the replace() method:

a = “””The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…”””
print(a.replace(“before”, “in the end”))

And here’s the output:

The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came in the end
That came in the end
That came in the end
That came in the end
That came in the end…

The general syntax for the replace() method is string name.replace("string to be replaced", "replacement string"). Replace() will replace all instances of a certain String with another String. In the case of multi-line Strings like this one, you would replace() to replace a common word or phrase with another word or phrase. In this case, I replaced before with in the end.

And last but not least, let’s try the split() method:

a = “””The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…”””
print(a.split(“,”))

And here’s the output:

[‘The other night when I was researching what was going to be discussed today I came across a passage wrote down’, ‘ I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end\nIt is an inevitable part of the cycle of existence’, ‘ all things must conclude\nTake the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves’, ‘ one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before\nThat came before\nThat came before\nThat came before\nThat came before…’]

The general syntax of split is string name.split(separator), with the separator being the symbol where you want to split the String. In other words, I used a , as the separator, which means I wanted to split the String wherever there is a comma.

  • By the way, \n is a newline character, which is an indicator of a new line in a String.

Now, another thing I wanted to mention about Strings is that they are considered arrays, with each character in the String (including spaces) being an index in the String array. Here’s an example:

a = “””The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…”””
print(a[100])

And here’s the output:

w

In this example, I wanted to display index 100 of the String, which would be a w. Remember that, like in Java, the first index of the array (or String-array) is 0, so index 100 would be the 101st character in the String.

  • Unlike Java, Python doesn’t have a character or char type, so a single character is a String with a length of 1.

Let’s see what happens when we select a range of indexes:

a =”””The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…”””
print(a[400:420])

And here’s the output:

concrete with all it

In this example, I selected the 400th-420th indexes to print (which are the 401st-421st elements). I got the phrase concrete with all it as a result.

  • Always remember to use colons when selecting a range of indexes.

OK, so that’s not all I have to mention about Python Strings. There’s one more String method I want to discuss-format(). This will allow you to combine numbers and Strings in Python; you must use this method to combine numbers and Strings, as trying to use a plus sign (as you would in Java) will get you an error,

Here’s an example of how format() would be used:

a = 2019
b = “The current year is {}”
print(b.format(a))

And here’s the output:

The current year is 2019

The general syntax of the format() method is string name.format(number). The curly brackets indicate where the number would go. In this case, the number 2019 would be placed after the string The current year is to form the sentence The current year is 2019.

The format() method takes an unlimited number of arguments. Here’s an example:

a = 8
b = 11
c = 2019
d = “The current date is {}/{}/{}”
print(d.format(a,b,c))

And here’s the output:

The current date is 8/11/2019

Each of the numbers is put into their respective placeholders. By that I mean that since a is listed first, a will occupy the first placeholder. Likewise, b and c will occupy the second and third placeholders, respectively. The result will be the sentence The current date is 8/11/2019.

But what if you wanted to fill in the placeholders in a different order? Let’s say we wanted to display today’s date in British format. Here’s how you would do so:

a = 8
b = 11
c = 2019
d = “The current date is {1}/{0}/{2}”
print(d.format(a,b,c))

And here’s the output:

The current date is 11/8/2019

The print line will be the same, but this time the placeholders won’t be blank. The 0, 1, and 2 indicate which element goes in which placeholder (remember that 0 is the 1st element). In the example above, 1 (which corresponds to b) goes in the first placeholder, 0 (which corresponds to a) goes in the second placeholder, and 2 (which corresponds to c) goes in the third placeholder.

Thanks for reading,

Michael

Python Lesson 2: Variables & Number Types in Python (50th Post)

Advertisements

Hello everybody,

It’s Michael, and today’s lesson will be on rudimentary coding with Python. Since most of the previous post focused on the background and setup process of Python, this lesson will focus on some basic coding with Python.

First, let’s open up Anaconda and launch our Spyder* console:

Screen Shot 2019-08-06 at 2.12.42 PM

*By the way, Spyder stands for Scientific PYthon Development Environment. I don’t know why I forgot to mention this in my last post.

Now, let’s start with a simple Python program. Here’s the code:

x = 14
y = x * 2
z = “14-Doubled”
print(x, y, z)

And here’s the output:

14 28 14-Doubled

In this simple program, I demonstrated the concept of variables in Python. They work quite similarly to variables in Java, but with one notable difference-there is no need to declare variable type in Python. So writing something like int x = 14 would be unnecessary in Python (and I think doing so will generate an error).

Keep in mind that, even though syntax might be different, variable naming rules for Python are just like those for Java. First of all, variable names must start with either a letter or underscore; they can NEVER start with a number. Also, variables names can only contain letters, numbers, and underscores, so don’t include special characters like &, *, or %. Finally, remember that, like in Java, variable names in Python are also case sensitive, so walk, Walk, and WALK would be three different variables.

Also, take a look at the print function. Notice that I used commas to combine the variables, not plus signs (which is what I would use to print several variables on one line in Java). However, you would use a plus sign to combine text and a variable, like this (I used z from the example I just discussed):

print(“Twenty eight is ” + z)

Twenty eight is 14-Doubled

One cool thing about Python variables is that you can assign values to several variables on the same line. Here’s how (along with the program output):

a, b, c, d = “ant”, “bee”, “cat”, “dog”
print(a)
print(b)
print(c)
print(d)

And here’s the output:

ant
bee
cat
dog

First, you would simply write each of the variable names, separated by a comma. After you insert an equal sign, write the values of the variables separated by a comma. You only need the pair of quotation marks if the values are Strings, otherwise they aren’t necessary.

  • Keep in mind that the variable names and their corresponding values are listed in order. In other words, the first variable a corresponds to the first value ant, the second variable b corresponds to bee, and so on.

Another interesting thing you can do with Python variables is assigning the same value to several variables on the same line. Here’s how (I included a program along with sample output):

a = b = c = d = “The quick brown fox jumps over the lazy dog”
print(a)
print(b)
print(c)
print(d)

And here’s the output

The quick brown fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog

The idea is similar to that of the previous program (assigning values to variables in the same line). However, there is one major difference (aside from assigning a single value to multiple variables)-each variable name is separated with equals signs, not commas. Equals signs are used because you’re assigning a single value to four variables, thus, each variable would have the same value as the others.

  • By the way, anybody recognize the sentence I used in this example?

One more topic I wanted to discuss was number types in Python, which are different from number types in Java. First of all, there are only three number types in Python (int,float, and complex) as opposed to the six number types in Java (int, byte, long, short, double, and float).

The fact that there are only three number types, as opposed to six, makes Python simpler in this regard. After all, even though I like using Java, I find that the several different number types are redundant. After all, byte, long, and short are all integers with the only difference between each number type is their range of possible values. Likewise, float and double are both decimals, but the only major difference is the same as with the integers types-their range of possible values is different. In Python, int is the only possible number type for integers and float is the only possible number type for decimals.

  • Keep in mind that float can be either a simple decimal (e.g. -1.04, 21.335) or a number in scientific notation with an e to indicate a power of 10 (e.g. 5.3e6, 4.55e-1).

Now, you probably have never seen the complex number type before. After all, Java doesn’t have this number type.

Complex represents complex numbers, which are the combination of real and imaginary numbers. Some examples of complex numbers include 3+7i, 4-2i and 15+10i. If you see a pattern in all of these numbers, it’s because they are all written in the form a+bi, where a is the real number and bi is the imaginary number. However, numbers such as -3j, 5j, and 32j are also complex numbers since they have both a real and imaginary part.

  • If you’ve taken Algebra 1, you might remember the concept of imaginary numbers. But if you don’t recognize or remember the concept of imaginary numbers, click this link to learn more-Imaginary Numbers.
  • The i is replaced with a j in Python. You must use a j when writing any complex numbers because you will get an error if you try to use another letter, including i.

One cool thing about Python is that you can easily convert from one number type to another. However, the one exception to this rule is that you can’t convert complex numbers into float or int.

Here’s an example of Python number conversion (the sample program along with the output):

x = 2019
y = 8.07
z = 20j

print(x)
print(y)
print(z)

a = float(x)
b = int(y)
c = complex(x)

print(a)
print(b)
print(c)

Here’s the output:

2019
8.07
20j
2019.0
8
(2019+0j)

The top three lines include variables x, y, and z, which are of type int, float, and long, respectively; these variables are printed on the first three lines of the output.

Pay attention to the seventh through ninth lines of code, since they contain the number type conversions (these are variables a, b, and c). A will convert the integer x into a float. B will convert the decimal y into an int. C will convert the integer x into a complex number. The converted values are then displayed in the second three lines of the output.

  • If you noticed, I didn’t use z in any of the conversions. This is because z is a complex number, and remember that complex numbers can’t be converted into anything else.

Thanks for reading,

Michael

Python Lesson 1: Intro to Python

Advertisements

Hello everybody,

This is Michael, and I thought I’d introduce a new analytical tool-Python (after all, I did say in the welcome post that I would eventually include Python. Well 14 months later, here it is.). Don’t worry, I’ll continue my R and Java lessons, but I thought this would be a perfect time to introduce another tool.

So, what is Python? It’s a multipurpose programming language invented by Dutch programmer Guido van Rossum in 1991. I say multipurpose because while Python has the coding capabilities of Java and the analytical capabilities of R, Python also has several more uses, such as creating web applications or connecting to database systems.

What makes Python a good programming language? First of all, just like Java and R, it is an open-source language, meaning that it’s free to use for anybody. In other words, there’s no expensive annual license fee to use Python (and software licensing fees run at least $1000 a year). Secondly, Python has a simpler syntax than other languages (though I personally don’t find Java syntax to be that complicated), as you can write Python programs with fewer lines of code than you could with some other languages. Next, Python runs on an interpreter system, which means that code can be executed as soon as it written (which is not the case with Java), thus making programming quicker. Finally, Python can either be used in a procedural, object-oriented (like Java), or functional manner. I explained the concept of object-oriented programming in my first Java post, but what are procedural and functional programming languages? Procedural languages view the program as one long procedure, with each line of code being a step in the procedure; think of procedural programming like a recipe, where each step in the recipe is just like each line of code in the program. Two examples of procedural programming languages include C and BASIC (which became obsolete in the late 80s). Functional programming views the functions in the program (the functions being the code) as data. This means that you can use the functions as parameters, return them, create other functions from those functions and create custom functions. The functions in functional programming must be pure functions, must avoid shared state, and must be immutable. Pure functions are functions where the same type of input will always return the same type of output. Shared state is a state (I covered the concept of state in my Java posts) that is shared between two or more functions or data structures. Immutable means unable to be changed; in the context of functions, immutable refers to functions that can’t be changed once created.

Now, one thing I want to note is that for any Python lessons I will be posting, I will be using an IDE tool called Spyder. IDE stands for integrated development environment, which is essentially software for computer programmers to write their code to develop their programs. As a matter of fact, I’ve already used another IDE in my blog-NetBeans (for my Java posts). Both Spyder and NetBeans are free to use IDEs, though keep in mind that these two software tools aren’t the only IDEs for their respective languages (Python and Java). Some other Java IDEs include BlueJ and JCreator (which I’ve used before but I like NetBeans better) while some other Python IDEs include PyCharm and Cloud 9 IDE.

Now, how do you install Spyder? Take a look at this website-Spyder Website-as it will tell you how to install Spyder for your system (whether you’re using Mac, Windows, or Linux).

One thing I want to make clear is that during the installation process, you’re not technically downloading Spyder-rather you’re downloading something called Anaconda. Anaconda is a free open-source Python package and IDE manager, which means that Anaconda collects thousands of Python packages (such as numpy and pandas, which I’ll discuss in future Python posts)  as well as Python IDEs, such as Spyder. Here is the what the dashboard for Anaconda looks like:

As you can see, these are some of the tools available in Anaconda. Each tool has a description that mentions what that tool can be used to do. For instance, the Jupyter notebook serves as a “web-based, interactive computing notebook environment”. And if you’re wondering what the difference is between R-Studio and R, R is simply for statistical calculations, analytical model building, and data visualization, while R-Studio can do all of those things plus build programs using R-after all, R-Studio is an IDE.

So, let’s open up Spyder and start Python coding. Here’s what an empty Spyder console looks like:

The entire left side of the screen consists of white-space where you will write the code for your programs. The top right of the screen simply shows a message linking to a Spyder tutorial, which you will see when you open up Spyder for the first time (this was my first time opening Spyder). You can close this window down, since it isn’t relevant for your Python coding. The bottom right part of the screen is also very important, as it is the place where your code will run (or detect any errors, of which you will be informed).

Now, let’s start with something simple:

If you can’t see the picture, here’s the code:

print(“Hello World”)

And here’s the output:

Hello World

Does this example look familiar? If you read my first Java lesson, or just know Java programming, then it certainly would. I simply printed Hello World, which is usually the first thing beginning Java coders learn to do. But there are two notable differences between Python’s Hello World and Java’s Hello World. They are:

  • The function to print Hello World is simply print as opposed to System.out.println.
  • Unlike Java, there is no need for a semicolon after each line of code.

Thanks for reading, and don’t worry, we’ll get into more coding in Python Lesson 2.

Michael