Solidifying Python foundations: Conditions and Loops in Python with the help of Traveling Salesman story

Görkem Aksoy
10 min readNov 30, 2022

--

I talked about data types in my previous article about Python programming. In this article, which is complementary to basic programming knowledge, I will talk about conditions and loops. Anyone who studies data types and the topics in this article well will be very comfortable working on the next step, specialized libraries. As a matter of fact, this information will be at the core of your transactions. It may sound cliché, but it’s really important to have a solid foundation. I took my lesson on this subject when I took the basics halfway and moved on to writing programs. I hope you read these lines before you start off wrong like me, and I hope these lines shed some light on you.

In programming, the way to explain what you would like to be done by the computer, as if you were explaining it to a baby who has just started life, is to master the conditions and cycles. Functions are the way to use the same code without having to write it over and over. Someone who can combine these two parts correctly can, in theory, write any program and change the world! In this article, I will first talk about conditions and cycles. The next post will be about functions.

I think one of the best ways to keep a topic in mind is through storytelling. I will try to convey the conditions and cycles with a story in order to visualize it. For example, let’s imagine that we are a sales representative. Let’s think about that salesperson profile in American movies. Let’s also go back in time, before the 2000s or even the 90s. What we sell is up to your imagination.

If we think of old American movies, we probably think of houses next to each other and opposite each other, aka suburbs. We woke up in the morning and set off for the suburbs. There are 50 houses in this neighborhood, and we will visit each house one by one, until we sell at least 10 of our product or we complete our visit in the neighborhood (i.e. visit all 50 houses). In some of the 50 houses there will be no one at that time, in some, people will not even want to listen to us, in others they will listen and refuse. We do not know how many sales we will make.

Before we make our story a program understandable, let’s outline it using logical arguments:

1- Visit 50 houses one by one

2-If we are accepted by the landlord, enter the house

3- If the landlord is convinced, make the sale.

4-If we made 10 sales, we have reached the goal, no need to visit all the houses, complete the program.

5-If we visit all 50 houses before we make 10 sales, then the loop is over, unfortunately we fail to reach our goal.

Among these logical arguments, the first argument is an argument for the loop. We can see the number of loops as 50. The 2nd, 3rd, 4th and 5th arguments express the conditions. The condition in the last two arguments are terminating conditions for our loop.

In how many rounds can our above loop be completed at minimum? As you can guess, the answer is 10. If your guess is wrong, don’t worry too much. Since we can sell 10 products by entering at least 10 houses (we assume that we can make a maximum of 1 sale per house), our cycle can be completed in at least 10 rounds and at most 50 rounds (because there are 50 houses in the suburbs).

We can express the above logic structure to Python with two different loop types. The first is the type of loop we call for, and the second is the type of loop we call while. The for loop has a beginning and an end. So obviously the for loop will end. In some cases, we may interrupt the cycle earlier than it should. The other one, while loop, the completion of our loop depends on a condition. If that condition is not met, the loop continues indefinitely. Of course, since Python imposes a tour constraint for such cases, we do not really reach infinity (how can we reach it anyway?) but theoretically, the program will continue looping as long as that condition is not met.

If we wrote this story with a for loop, it would look like this:

import random
total_house = 50
max_sell = 10
houses_visited = 0
products_sold = 0
for house in range(total_house):
houses_visited += 1
permit = True if random.randint(1, 10) <= 5 else False # %50 chance that the landlord permits us to enter his/her house
if permit == True:
sell = True if random.randint(1, 10) <= 4 else False # %40 chance for us to make sell.
if sell == True:
products_sold += 1
if products_sold == max_sell:
print(f"Congrats! You reach the target with only {houses_visited} houses visited.")
break
else:
continue
if products_sold < max_sell:
print(f"Oops. You only sell {products_sold} products!")

Starting from the top, I called a python module named random into my program. This part is not very important, I used this module inside the loop, but it is not related to the loops topic, so you don’t have to worry. In the next 4 lines, I created variables suitable for our story and assigned initial values ​​to them. For those who don’t know, let me explain briefly;

total_house = 50
max_sell = 10
houses_visited = 0
products_sold = 0

In the above image, the expressions on the left side of the equality demonstrates the variable, and the right side shows the value assigned to this variable. A variable can be assigned to any of the data types I described in my previous post. That is, one variable can be assigned an integer as above, another variable can be assigned a binary data type (bool), and another variable can be assigned a dictionary. What we call a variable, so to speak, is something that can take on different values ​​in different parts of the program. You can understand why we need this by examining the example above. I don’t need to explain at length here, so let’s get back to our topic..

The for loop starts with the following line, let’s take a closer look at this line:

for house in range(total_house):

The “house” part, which is written after the for, refers to the variable that allows us to continue the for loop. Python understands the necessary information through the range method and its arguments. This information is where to start, where to end and the number of steps. These expressions are comma-separated expressions. In our code, only total_house variable is declared but Python is way too smart to figure out what is meant. It’s default starting point is 0 and default step size is 1. So for our example, 0 is the starting point, 50 is the ending point, and 1 is the number of steps. If you ask why the initial zero is taken here, I can say that it is a habit brought by the index numbering in Python. If there are 50 endpoints here, then the question may arise, are we not looping a total of 51 times? The answer is no, we’re going to loop 50 times because it’s Python! This is because numbers up to the end point are taken into account. So we’re essentially circling from 0 to 50 without taking 50, which would equal laps from 1 to 50 inclusive. Bro, why are you bothering us, you can say range(1,51,1) from the beginning. I do this as a habit, you can continue with the second option, which seems more logical but I assure you in Python you would prefer starting from zero.

One of the best things about Python, in my opinion, is that you can transfer what you have in mind to the program with little effort. It allows me to code in a very similar way to the logic structure I mentioned above. For example, let’s interpret the for loop together:

for house in range(total_house):
houses_visited += 1
permit = True if random.randint(1, 10) <= 5 else False # %50 chance that the landlord permits us to enter his/her house
if permit == True:
sell = True if random.randint(1, 10) <= 4 else False # %40 chance for us to make sell.
if sell == True:
products_sold += 1
if products_sold == max_sell:
print(f"Congrats! You reach the target with only {houses_visited} houses visited.")
break
else:
continue

First line: Loop for each house, since we have 50 houses, visit 50 houses one by one in total

Second line: Increase the number of houses visited by one

Third line: See if the landlord allow us to go inside (no need to digest this at this stage, what I’m actually doing here is to assign a probabilistic type to a variable of type bool, True or False).

Fourth Line: If allowed to enter the house, go to the next step (Go to line 5 if allowed) otherwise skip to line 11

Fifth line: See if I can sell (Sell variable is assigned a probabilistic bool type value with same logic in third line)

Sixth line: If sales permit is given, move to next line (7th line), if not, move to next house

Seventh line: When the sixth line is True, that is, when we make a sale, we increase the number of sales by one, since we come to this line.

Eighth line: If the sales count is 10, move to the next line, if the sales count is not 10, go to the next house

Ninth line: Since we see this line when we have 10 sales, it allows us to see how many houses we reached with a printout before ending the program and how many houses we reached this sales number.

Tenth line: The break command here is a statement we use when we are not going to complete the for loop. In our story, we stated that if we made 10 sales, we would stop touring the houses. We are ending our cycle as we have 10 sales.

Eleventh line: Actually, we don’t need to add this line, but I added it for informational purposes because conditional structures use else with if. If condition can also be used on its own, if you notice, you’ll see that I don’t use else in other if commands.

Twelfth line: Since I’m using the Else structure as an example, I entered “continue” to underline it. If Python sees this command inside a loop, it will move on to the next issue of the loop. In our example, it will move to the next house.

Our example is actually one that includes both loops and conditions. The Python equivalent of the conditional statement is the if statement. Notice that the indentation of each line are not equal. In Python, a condition, or a loop ends where the indentation becomes the same level with condition or loop. So Python tells us, bro, I don’t know what the conditional expression is in your head, I’m not a seer. That’s the condition for me to understand the conditional statement, in my program you have to follow these rules. The same goes for loops. Here, too, indent determines the scope of that loop.

Let’s examine this situation by taking a section from our example above:

if permit == True:
sell = True if random.randint(1, 10) <= 4 else False # %40 chance for us to make sell.
if sell == True:
products_sold += 1
if products_sold == max_sell:
print(f"Congrats! You reach the target with only {houses_visited} houses visited.")
break
else:
continue

If our variable named permit has the value True, the program continues right below this condition. If you notice, this line continues with an indentation. According to the IDE you use (programs that make it easier to write code), when you put a colon after the condition and press the “Enter” key on the keyboard, the indentation automatically shifts to the right. If the conditional expression is False, then the program skips the lines further until it finds a line with the same or less (whichever comes first) indentation level (in our example here, the line that says else:). Indentations are at a distance of 4 space keys (or 1 Tab key) from each other. The program will throw an error when it is more or less.

Let me add something about the conditions. We may have more than one condition. In this case, the if-elif-else structure is used instead of just the if-else structure. elif is short for else if. In a conditional loop, only one if and one else can take place, whereas number of elif’s can be numerous.

As I conclude this article, I include the alternative of the example we mentioned, written with a while loop. As you may remember, while loops continued the loop until a certain condition was met. You can give this alternative a little thought and discover how it works. Let me add one more thing to make this alternative more understandable. If the variable being checked in the while and if structures is itself a boolean type, then you don’t need to check with “==”. If you examine the line that starts with while, you will understand what I mean.

If you’ve read this far, I’d like to express my appreciation for your patience. When I started this article, I did not think that it would be such a long article, I even thought that I could specify the functions in this article, but at this point, I did not even have the opportunity to explain the while loops. If you have any questions, you can reach me here or on Linkedin. See you in the next article..

Same example using while loop:

import random
total_house = 50
max_sell = 10
houses_visited = 0
products_sold = 0
keep_continue = True
while keep_continue:
houses_visited += 1
permit = True if random.randint(1, 10) <= 5 else False # %50 chance that the landlord permits us to enter his/her house
if houses_visited > 50:
keep_continue = False
print(f"Oops. You only sell {products_sold} products!")
elif permit == True:
sell = True if random.randint(1, 10) <= 4 else False # %40 chance for us to make sell.
if sell == True:
products_sold += 1
if products_sold == max_sell:
keep_continue = False
print(f"Congrats! You reach the target with only {houses_visited} houses visited.")

--

--

Görkem Aksoy

BSc in Industrial Engineering - METU | Data-Science | Statistics | Content Creator