There is yet another type of loop. That loop is designed for iterating sets of data. That's right, lists. Unlike while loops, these for loops have a defined length based on the data set that they are iterating over.
Generally, for loops are used to access and modify each element in a list. To do this, they temporarily represent each element as a new variable used only within the loop.
for loops have a slightly different structure than while loops do. They begin with the word for, which is followed by the temporary variable being created for the loop. Then there is the keyword in specifying the set of data being used, followed by the data set itself and, ultimately, a colon.
For With Range
There is a method called range() that either takes a single number and behaves like a list of numbers going from zero until the number before the one specified or takes two numbers separated by a comma and acts like a slice starting at the first number and listing all numbers until the number before the last one.
Many times in programming, you will need to repeat the same task many times. In fact, looping through and repeating an operation is one of the cornerstones of programming. After all, one of the things that computers are way better than humans at is performing repetitive tasks without getting tired or making mistakes.
One of the simplest ways to make a program repeat the same task is to use a while loop. A while loop repeats the same block of code while a condition is true. When that condition becomes false, the loop will break, and the regular flow of code will resume.
The structure of a while loop is similar to what you encountered in the last guide with if. A while loop begins with the word while followed by parenthesis containing the condition of the loop and a colon. The following lines are indented and will execute in the loop.
Check out this while loop. Try it yourself in your interpreter to see exactly what it does. You might be somewhat surprised.
# Import time for sleep
# While loop
What happened? Rather, what is happening? If you haven't figured out how to stop it yet, just press Ctrl+C. A while loop will run indefinitely as long as the condition that it is given remains True. The loop above was given True as its condition, which will never not be true.
How can a program make a decision? Can a program choose between two or more options. Actually, it can. This isn't some kind of advanced AI concept, it's just a matter of evaluating whether or not certain conditions have been met and choosing a response.
The way that a program can evaluate a condition comes down to true and false. If something is true, do this. If it isn't true do, that. The if statement is the structure for a program to pose these questions and evaluate whether or not they are true. if statements can check multiple conditions and provide multiple responses. They can be used to divert code down one path or another and control the overall flow of a program. They can also be used as a gating mechanism to determine whether certain blocks of code run. Have you ever gotten a message telling you that you needed to log in to continue? That was the result of if.
If you've been following along, you're probably tired of hearing about lists right about now. Well, this guide has nothing to do with lists! Remember back when you first leaned about variables; how there was one that just held True or False called a Boolean? There hasn't been a guide on them because Booleans are actually that simple. However, there are symbols called Boolean Operators that are used to evaluate whether a statement is true or false. They compare statements and return either true or false. It sounds simple, and in a way it is, but it can get more complex when more comparisons get added.
The first comparison operator is and. You can use and to test in one statement and another statement are both true.
Tuples are immutable data sets made up of data of different types. While tuples are very similar to lists, they are different in those key ways.
Tuples cannot be changed once they are created. The data they hold can be passed to a different tuple, but the original tuple cannot be changed. This means that tuples don't have methods for manipulating them like lists do because they cannot be manipulated.
Like lists, tuples can also contain data of different types. Tuples can contain strings, integers, floats, booleans, and even lists. Because tuples are immutable, they aren't meant to be manipulated, so data types don't matter nearly as much.
Now it's time to take lists to a new dimension. No, you don't need to learn how to code in "The Upside Down," but there are additional degrees of complexity to lists. Lists are used to hold data, but they are also used to categorize it. Values inside a list can be further broken down into other sets. That's essentially what a multidimensional list is.
Two Dimensional Lists
What is a list that holds lists? That's all a two dimensional list is. The list below consists of three lists. Each of the three lists has five elements. Don't worry about numbers quite yet. Just focus on the top level elements, the lists. You can access them the way you would any element in a normal list.
Using methods with lists gives you the power to manipulate the data stored in the lists quickly and effectively. Many of these methods are concerned with finding, adding, and removing pieces of data stored within the list they are being called on. Others are more concerned with the structure of the list itself.
In any case, they will make your experience using lists a lot less frustrating by saving you time and effort writing and rewriting the same code.
Finding the Length
Yes, this does start off with some more overlap with strings. The len() method works on lists as well. So, in order to find the amount of elements in a list, just place it in the len() method.
Again, keep in mind that the result is the number of elements in the list. The last element is available at the index of six. You can also use the len() method to access elements in the list, if you have to.
Adding the - 1 at the end is necessary, because there is no index of seven, since the list starts counting at zero. Using this method is another way to access elements based on the length of the list. In some cases, it may be preferable to using the negative numbers.
Lists are a big deal. It really can't be overemphasized what a big deal they are. Lists are not only used for iterating through data, but they are also a popular data storage and categorization method used for handling data as a program is running. For anyone who's programmed in another language, lists are often known as arrays.
Lists may be either very simple or very complex, but they all follow the same rules. Lists may contain different types of data, but be careful when working with it. If you create a list that mixes, say, strings and floats, be sure not to try to call a string method on a list item containing a float.
Remember when the string guides said that strings were just a list of characters. Well, now's the time to be glad that you paid attention to strings. You can do many of the same things that you did with strings with lists, and you can do them in the same way. So, some of this is going to feel like a repeat of the string guide, but don't break focus. There are differences, and there are list specific methods, so assuming that strings and lists are the exact same this will get you into trouble.
Creating a List
Creating a list is a bit different than the other variables that you've learned about so far. You can create a list with absolutely no values in it at all. This is useful for situations where you don't exactly know what will be added to the list because the data isn't in the program yet. There will also be plenty of situations where you won't be sure how many entries will be in a list, so again, creating an empty one and adding data later is the right move.
This guide isn't about programming. In fact, there is no new code involved at all. However, it does have everything to do with making sure that the code that you write is understandable to both yourself and anyone else that might look at it down the line.
If you've looked at any open source projects, you've probably noticed notes placed in by the programmers. Those notes are just plain text. The programming language doesn't compile or interpret them in any way. It just ignores them. It knows that those comments are for humans, not computers.
In the previous guide, you learned the basics of handling strings in Python. In this guide, you will explore some of the more complex things that strings are capable of. There are tools built into Python, called string methods, that help you to handle strings and do some very powerful things. Through the use of string methods, you can masterfully manipulate text and use it to its fullest potential without writing a ton of code.
Navigating a String
Strings aren't words. They aren't sentences, phrases, and believe it or not, they aren't even a collection of text. Strings are just a lists of characters. Those characters can be letter, numbers, symbols, spaces, and escape characters. Python sees strings by their parts(the characters) and uses those parts to manipulate strings. This is actually true of almost any programming language. So, that means that you can select individual characters out of a string. Try this:
phrase_string = "This phrase is a string!"
Strings are called what they are because they are strings of characters. It doesn't matter if those characters are letters, numbers, symbols or spaces. They are all taken literally and not processed within a string. That's why strings are sometimes referred to as string literals.
If you've been following along with the previous guides, you've already experimented with some strings. You've typed in some, and you've printed them back out. What about getting user input when the Python script runs? Python has built in functionality to take in user input and assign it to a variable. Try it out.
user_input = input("Please enter some text: ")
Obviously working with numbers in programming is important. Python as excellent mathematical capabilities, and there are tons of additional libraries available to extend Python's built in functionality for even the most advanced calculations. Of course, the basics are important too, and numbers and some basic calculations come into play when controlling the flow of programs and making selections. That's why knowing your way around working with numbers in Python is especially important.
Do you remember variables from math class in school? Variables in programming are actually very similar. Variables are just symbols that that represent a value and that value can be changed; thus the name variable. Unlike in math, variables in programming can be much more free form. Variables don't just have to be a letter. Variables can be a single character, but they are more commonly a word or a short descriptive phrase in lower case with words separated by underscores. It's actually best to name variables something descriptive so the you and anyone else that you're working with knows exactly what that variable is, even much later on in the code.
Types of Variables
Python is a dynamic duck typed language. Don't worry too much about the terminology, but that means that Python doesn't force you to specify which types variables are when you create them. Oh yeah, there are types of variables. Even though you don't necessarily have to specify their type when you create them, it's a good idea to know what type you want them to be. Later on, having the wrong type of variable will invariably get you into big trouble.
You probably want to jump in and start coding right away. That's a great attitude to have, but it's much better to experiment with the language and your programming environment first. If you've never programmed or never worked with an interpreted language like Python before, it's important to get a feel for the way Python works and start to develop a workflow. One great aspect of Python being interpreted is the ability to write a couple of quick lines of code and test them out in real time. There really isn't much setup beyond what you've already done.
Playing With Numbers
Without knowing anything about the language, you can use Python like a basic calculator. Open up either your .py file or the interpreter. Type in a basic math problem and run it.
Python is an interpreted language, meaning that it is compiled every time that it is run. There are a number of pros and cons when talking about an interpreted language like this.
First, on a positive note, they tend to be easier to debug. They fail immediately when they are run, and tell you what went wrong, which is nice compared to compiled languages like C/C++, which can compile just fine, but fail silently when run.
Interpreted languages are also very portable. All you have to do is install the interpreter on a system, and most code written in that language can run fine, regardless of the operating system. There are some exceptions when dealing with operating system specific code and libraries, but if you've planned for portability, you can work around those situations.