FORever ALONE

--Originally published at Coding The Future

Image via GIPHY

Today, I will share the very sad story of my relationship life: I am, and forever will be a forever alone. But that's ok. To be honest, I don't mind the single life. Love's just complicated for me.

But anyways, you are probably wondering why am I telling you this, which is probably useless. Well it kind of is useless, but today's topic, For Loops, got me thinking.

So, let's dive into today's topic: For Loops. Remember while loops? Well for loops are not so difference. Only difference is that this time, we know exactly how many times the loop needs to run.

Here's an example: Let's say we wanted to ask a user to enter their password, and we need the user to enter it twice. Since we know that the loop will run exactly twice, the most appropriate way to accomplish this is a for loop. Let's take a look at the following program:

password = ["pass1","pass2"]
i=0;

for counter in range(0,2):
⠀⠀password[counter] = input("Please enter your password: ")
⠀⠀i= i+1

if (password[0] == password[1]):
⠀⠀print("Both passwords match")
else:
⠀⠀print("Passwords do not match")

As you can see, the first two lines simply declare a list and an integer. The following lines is where the magic happens. As you can see, I started with the keyword for, and declared a counter variable called counter, followed by the key words in range and the range from which the loop will run. As you can see, this range is in brackets, and it says (0,2). Check the footnote to know why this means it will run twice.1 I end off with a colon.

The code bellow just asks the user for input, stores it in a list, and at the end of the loop it.

There are several cool things you can do with for loops as well. For example, instead of using in range, you can run a for loop for every character in a string, or for every item in a list, and more! Here's an example of what we would do if we wanted to improve the program's efficiency:

for index in range(len(password)): password[index] = input("Please enter your password: ") i= i+1

Check out this tutorial by TutorialsPoint to find out more ways on how you can use for loops.

That's it for today, I hope my post was useful. And that I find someone who loves me one day... ?

Remember to stay in touch! @emamex98

  1. If you are wondering why the loop runs twice when the range should actually run "thrice", the answer is because of Python. Check out this explanation by Python Central.

comments powered by Disqus