Python 3 – Learning it properly this time from Hello World to Scripting, learning Python 3 from scratch Post #1 Completed – Session #2 begins!

I will pick up right where I left off from the previous Intro to Expert thread here!

That being said, I will be looking at another noob feeling topic in depth!

Python Sequence Types

The 5 sequence types are as follow the (first 3 are actually built into Python):

  • String
  • List
  • Tuple
  • Range
  • Bytes / Bytearray

What is a sequence? A sequence is an ordered set of items, much alike Hello World! is a sequence 12 indexed characters in Python, however seen at the very ending of my first Python for Noobs post when I was going through Step Splicing you can find a common separator of values to create list of usable information along with even just logically group info at all.

Before diving into pulling apart sets of data though its important to look at this example of things that were on my camping list before vacation this last weekend:

[“food”, “clothes”, “gas”, “medical supplies”, “tent”, “warm sleeping bags”]

In Python this is a Sequence of Strings, though it is also a which “List” as well.

For this reason if you didn’t read the “Step Splicing” portion of my last thread I would give it a quick looking at, as sequences are basically designed for “Step Splicing” as its purpose is to separate data which here will be defined by its “sequence” in the data sets.

For some reason my course took a quick pivot back to math and strings, which I assume will segway back info this, however its showing the fact that math precedence still affects strings:

This shows both how we can use math to add strings together in math expressions to complete a sentence, and use the multiplier operator to repeat a string, however there is sort of a trick to know of that when operators are used in the same argument it will be used as a math expression in the function as shown here with adding vs Concatenation.

Actually first a quick show of what fails, and why it fails first:

Python actually tell me why this fails, because when it see’s the + Operator with a String it thinks Concatenation, so there are two different ways to approach fixing this depending on what it is you intend to do in this situation:

I assume this to be the PEMDAS Math Precedence executing Paranthesis first before processing other Math operations within the Functions argumentents, however this could just be Python Error Handling / Intepretation of a sloppy way of writing code – However this will result in Hello! being printed 4 additional times as though the line was “Hello! ” * 9.

Whereas the second line we are simply multiple Hello! * 5 then adding a string 4 to the end.

Another way to do this that I alluded to earlier is to make the Integer a String in the expression:

I used this earlier with Concatenation, though either way works, for “clean code” I would be inclined to use the str() rather than “” to define a String where an integer is.

Now to demonstrate an example of a boolean true / false sequence of strings and how they work, I added today (Monday, bleh) as the day, and show here that each following iteration of this statement will either be “True” or “False” if it contains the part of the variable defined:

Mon and day are both “True” to say is in Monday, however “Friday!!!” and Hello! are False to say they are within the Variable today / Monday.

Going back to making Integers into Strings though this time through Variables, there is a method that allows “String Replacement Fields” rather than manually adding Variables to String and manually defining them as Strings:

The second print statement essentially calls out the value at the 0 index of the “age” variable or Tuple as it would technically be called in this scenario, with the “.format(something)” being the “Method” from which it is going to choose its index value object.

This is called using a replacement field, called from a “Tuple” identified by the curly braces {}, and can also be in a non-variable format shown below (and much more):

Though generally the actual “format” method would not be defined at the end of the function, this is exactly how it works, it starts at index 0 and calls out each # listed like step splicing.

This can be used in many situations like listing downwards, I am kind of playing around with how to create lists to use this, but feel I am getting ahead here and hitting the break

Instead I will Pivot to String Formatting

This first demo will just be a simple math equation where we can find the squared and cubed result of a # with a “for loop” within a certain range:

I don’t know that I’ve covered this type of math operator, but ** means exponential multiplication, so an i (Integer) ** 2 means it is times itself once (power of), and then the power again of that result.

A variation of this to get a side by side chart would be to replace the String Replacements:

This makes exponential math a bit more clear as well, showing that 2 cubed is 8, meaning it is 2 * 2 = 4 * 2 = 8, however this is hardly the point of this concept.

Let us review this program as a whole to dig deeper into the understanding / formatting”

for i in range(1,15):
print(“No. {0:4} squared {1:2} and cubed is {2:4}”.format(i, i ** 2, i ** 3))

I only put the “for” loop line in there reference but it is otherwise not part of this discussion.

What we are printing here is declaring within the Curly Braces starting with the First # value the index # being placed or “replaced” into the string, however one key note is that the “format” option are within this function so they are the candidates for replacement!

There is no variable, no list, we did specify a range but that only matters for the first “replacement” in the string where “i” in the “range” gets exponentially multiplied, then get cubed using the i ** 3 at the end of the format – These are 3 replacements being used!

This was hard for me to understand initially, but the index is referring the the format #

It does not pick from “i” in the range, it replaces the values with both the “i” as it is defined as Index 0 to display the base #, then the power of #, then the cubed result of the #.

Another point here is the Tuples or String Replacements are not locked into static results, as seen here we are using them to make lists of “Power of” and “Cubed” #’s with lots of other uses that I am sure we will be demonstrating shortly.

The # value to right of it also uses Indexed #’s to format the “Width” of the output:

Please excuse the chicken scratch, that is {1:3} for the second tuple and {2:5} as the third to show out it simple increases or decreases the width in this case for human readability.

This is the “Width” value essentially reserving characters on the screen, so it quite literally is the formatting of the output, and where the end of the String will place your value in the output of the function being run – So please grab the code from this page and pactice if needed.

I had to full screen for the demonstration of using Less Than < for the Width value to demo:

Here we can see that Less Than or < in the Width mashes it together, while the Karat ^ symbol actually center the output of the column the best that it can in the Cubed section.

There is also a way to add “Precision Width” using Floats as shown below here as well:

This all gives the same correct output, however if we wanted to just ever so slightly alter the output, we can do that by adjusting the width by small amounts to see what it gives us. Also the code is right here in case you want to copy / pasta to practice:

print(“Pi is approx {0:12}”.format(22/7))
print(“Pi is approx {0:12}”.format(22/7))
print(“Pi is approx {0:12}”.format(22/7))
print(“Pi is approx {0:12}”.format(22/7))
print(“Pi is approx {0:12}”.format(22/7))
print(“Pi is approx {0:12}”.format(22/7))

I’ve actually shortened this two iterations as I think it gets the point across just below here:

One Huge Thing I first overlooked – The 3rd value in the Tuple is separated by a ‘.’ not a ‘:’

So when doing a “Precision Width” the “f” at the end is telling Python to generate a float result which demonstrates Python will only display the first 6 digits by default in a float, however on the next line I put 50f with a width of 12, however Python chooses precision over Width restrain and prints out 50 characters of decimal value as shown here.

The other examples are simply to show the formatting the output properly.

Now one other important point is that a Python Precision Float will output a maximum of 51-53 digits as taught in my class, however my lab is showing a different story here:

And also when adding some Greater Than and Less Thans in the Width for test:

So it sure appears like the Precision float result ends at 50 character to me, and ignores the manually entered width if there is a Precision parameter that is a higher value than the width.

Clear as mud? Good! We are just getting started! (Or at least one more quick topic)

At least on the original “for” loop in which we were getting power of / cubed values:

The “Replacement” and “Width” values do not to be set at all for this to run, you just read all of that for nothing, MWAHAHAHAAAAA!!!

Though in all seriousness, it is just a for loop going through iterations until it exits the loop, and it will assume each value is the current value of the iteration it is on and the width is 1 space.

With the current print function we are handing it the arguments to use per iteration so none need to be supplied (i, i ** 2, i ** 3), so the “for” loop is already taking care of going through each iteration separately though leaving these empty would not work in any situation.

Using “f string” in Python 3 (mainly used for Python 2 so I won’t cover much)

Typing Python using the “f” string method reduces the size and complexity of code, however it only work with certain version of Python, so I would tend to stay away from it outside of being curious or if you were going to work with (I will someday I am sure review it).

A short example of how “f string” can make life easier for people running Py3.6+ :

Without f string line 7 would be written as:

print(name + ” is”, str(age) + ” years old!”) <— as we need to turn the Integer to a String


print(name + f” is {age} years old!”) <— Avoid need to declare the data type and quotes!

Also with the above example we can do the format portion right in the line of code rather than an after thought of it, though again its kind of venturing into waters where it may or may not be used, and so I won’t go much beyond that (which is disappointing as I’ve seen f string mentioned in 2.x Python forums but my class is 3.x only).

Program Flow Control coming next!!!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s