Python For Loops and If Statements Combined (Python for Data Science Basics #6)

Last updated on August 03, 2019

Last time I wrote about Python For Loops and If Statements. Today we will talk about how to combine them. In this article, I’ll show you – through a few practical examples – how to combine a for loop with another for loop and/or with an if statement!

Note: This is a hands-on tutorial. I highly recommend doing the coding part with me – and if you have time, solving the exercises at the end of the article! If you haven’t done so yet, please work through these articles first:

Note 2: On mobile the line breaks of the code snippets  might look tricky. But if you copy-paste them into your Jupyter Notebook, you will see the actual line breaks much clearer!

For loop within a for loop – aka the nested for loop

The more complicated the data project you are working on, the higher the chance that you will bump into a situation where you have to use a nested for loop. This means that you will run an iteration, then another iteration inside that iteration.

Let’s say you have nine TV show titles put into three categories: comedies, cartoons, dramas. These are presented in a nested Python list (“lists in a list”):

my_movies = [['How I Met Your Mother', 'Friends', 'Silicon Valley'],
    ['Family Guy', 'South Park', 'Rick and Morty'],
    ['Breaking Bad', 'Game of Thrones', 'The Wire']]

You want to count the characters in all these titles and print the results one by one to your screen, in this format:

"The title [movie_title] is [X] characters long."

How would you do that? Since you have three lists in your main list, to get the movie titles, you have to iterate through your my_movies list — and inside that list, through every sublist, too:

for sublist in my_movies:
    for movie_name in sublist:
        char_num = len(movie_name)
        print("The title " + movie_name + " is " + str(char_num) + " characters long.")

Note: remember len() is a Python function that results in an integer. To put this integer into a “printable” sentence, we have to turn it into a string first. I wrote about this in the previous Python For Loops tutorial.

python nested for loop - example

I know, Python for loops can be difficult to understand for the first time… Nested for loops are even more difficult. If you have trouble understanding what exactly is happening above, get a pen and a paper and try to simulate the whole script as if you were the computer — go through your loop step by step and write down the results.

One more thing:
Syntax! The rules are the same ones you learned when we discussed simple for loops — the only thing that I’d like to emphasize, and that you should definitely watch out for, is the indentations. Using proper indentations is the only way how you can let Python know that in which for loop (the inner or the outer) you would like to apply your block of code. Just test out and try to find the differences between these three examples:

python nested for loop - example

Example 1

 

python nested for loop - example 2

Example 2

 

python nested for loop - example 3

Example 3

If statement within a for loop

Inside a for loop, you can use if statements as well.

Let me use one of the most well-known examples of the exercises that you might be given as the opening question in a junior data scientist job interview.

The task is:
Go through all the numbers up until 99. Print ‘fizz’ for every number that’s divisible by 3, print ‘buzz’ for every number divisible by 5, and print ‘fizzbuzz’ for every number divisible by 3 and by 5! If the number is not divisible either by 3 or 5, print a dash (‘-‘)!

Here’s the solution!

for i in range(100):
    if i % 3 == 0 and i % 5 == 0:
        print('fizzbuzz')
    elif i % 3 == 0:
        print('fizz')
    elif i % 5 == 0:
        print('buzz')
    else:
        print('-')

python for loop and if statement - fizzbuzz example

As you can see, an if statement within a for loop is perfect to evaluate a list of numbers in a range (or elements in a list) and put them into different buckets, tag them, or apply functions on them – or just simply print them.

Again: when you use an if statement within a for loop, be extremely careful with the indentations because if you misplace them, you can get errors or fake results!

Break

There is a special control flow tool in Python that comes in handy pretty often when using if statements within for loops. And this is the break statement.

Can you find the first 7-digit number that’s divisible by 137? (The first one and only the first one.)

Here’s one solution:

for i in range(0, 10000000, 137):
    if len(str(i)) == 7:
        print(i)
        break

This loop takes every 137th number (for i in range(0, 10000000, 137)) and it checks during each iteration whether the number has 7 digits or not (if len(str(i)) == 7). Once it gets to the the first 7-digit number, the if statement will be True and two things happen:

  1. print(i) –» The number is printed to the screen.
  2. break breaks out of the for loop, so we can make sure that the first 7-digit number was also the last 7-digit number that was printed on the screen.

python break example

Learn more about the break statement (and its twin brother: the continue statement) in the original Python3 documentation: here.

Note: you can solve this task more elegantly with a while loop. However, I haven’t written a while loop tutorial yet, which is why I went with the for loop + break solution!

Test Yourself!

It’s time to test whether you have managed to master the if statement, the for loops and the combination of these two! Let’s try to solve this small test assignment!

Create a Python script that finds out your age in a maximum of 8 tries! The script can ask you only one type of question: guessing your age! (e.g. “Are you 67 years old?”) And you can answer only one of these three options:

  • less
  • more
  • correct

Based on your answer the computer can come up with another guess until it finds out your exact age.

Note: to solve this task, you will have to learn a new function, too. That’s the input() function! More info: here.

Ready? 3. 2. 1. Go!

Solution

Here’s my code.

Note 1: One can solve the task with a while loop, too. Again: since I haven’t written about while loops yet, I’ll show you the for loop solution.
Note 2: If you have an alternative solution, please do not hesitate to share it with me and the other readers in the comment section below!

down = 0
up = 100
for i in range(1,10):
    guessed_age = int((up + down) / 2)
    answer = input('Are you ' + str(guessed_age) + " years old?")
    if answer == 'correct':
        print("Nice")
        break
    elif answer == 'less':
        up = guessed_age
    elif answer == 'more':
        down = guessed_age
    else:
        print('wrong answer')

My logic goes:
STEP 1) I set a range between 0 and 100 and I assume that the age of the “player” will be between these two values.
down = 0
up = 100

STEP 2) The script always asks the middle value of this range (for the first try it’s 50):

guessed_age = int((up + down) / 2)
answer = input('Are you ' + str(guessed_age) + " years old?")

STEP 3) Once we have the “player’s” answer, there are four possible scenarios:

    • If the guessed age is correct, then the script ends and it returns some answer.
      if answer == 'correct':
          print("Nice")
          break
      
    • If the answer is “less”, then we start the iteration over – but before that we set the maximum value of the age-range to the guessed age. (So in the second iteration the script will guess the middle value of 0 and 50.)
      elif answer == 'less':
          up = guessed_age
      
    • We do the same for the “more” answer – except that in this case we change the minimum (and not the the maximum) value:
      elif answer == 'more':
          down = guessed_age
      
    • And eventually we handle the wrong answers and the typos:
      else:
          print('wrong answer')

python if and for combined - test

Did you find a better solution?
Share it with me in the comment section below!

Conclusion

Now you’ve got the idea of:

  • Python nested for loops and
  • for loops and if statements combined.

They are not necessarily considered to be Python basics; this is more like a transition to the intermediate level. Using them requires a solid understanding of Python3’s logic – and a lot of practicing, too.

There are only two episodes left from the Python for Data Science Basics tutorial series! Keep it going and continue with the Python syntax essentials!

Cheers,
Tomi

← Previous post

Next post →

6 Comments

  1. daudul

    awsome ..

  2. Nandita

    Hi Tomi,

    In the above assignment, how did you make sure that the script will find the answer in maximum 8 tries? I can see it did but was that calculated or by chance?

    Thanks,
    Nandita

    • Hi Nandita,
      Good question but it’s just basic math.
      If you divide 128 with 2, seven-times, you’ll get 1.
      So if you always half the distance between the upper and lower value, wcs, you’ll get the final result in 7 steps. (Not even 8 required.)
      The question was meant to help with the solution, too! 😉
      Tomi

  3. Balázs

    Hi Tomi!

    This age founding program is cool. And it inspired me to do some similar program too.
    I created a program which is able to find out which county do you live in Hungary.
    For the first question I give the answer scenarios, the rest of them yes-no questions.
    I know it is not a sophisticated one, and it is easy, but I enjoy the work on it!
    The for loop is for the wrong answers, but if you give a wrong answer you have to start it over.
    Here is the code:

    for i in range(1,4):
        answer=input('Do you live in Pest County? (Possible answers: correct, to the west, to the east, to the south) ')
        if answer=='correct':
            print('Good for you!')
        elif answer=='to the south':
            print('You live in Bács-Kiskun County.')
            break
        elif answer=='to the west':
            answer1=input('Do you live in the northern part of this region? (yes, no) ')
            if answer1=='yes':
                answer2=input('Do you live in a county which is next to the eastern border of the country? (yes, no) ')
                if answer2=='yes':
                    answer3=input('Do you live in the western part of this part? (yes, no) ')
                    if answer3=='yes':
                        print('You live in Győr-Moson-Sopron County.')
                        break
                    elif answer3=='no':
                        print('You live in Komárom-Esztergom County.')
                        break
                    else:
                        print('Wrong answer.') 
                elif answer2=='no':
                    answer4=input('Do you live in a county which is next to the western border of the country? (yes, no) ')
                    if answer4=='yes':
                        print('You live in Vas County.')
                        break
                    elif answer4=='no':
                        answer5=input('Do you live next to Pest County? (yes, no)')
                        if answer5=='yes':
                            print('You live in Fejér County.')
                            break
                        elif answer5=='no':
                            print('You live in Veszprém County')
                            break
                        else:
                            print('Wrong answer.')
                else:
                    print('Wrong answer.')
            elif answer1=='no':
                answer6=input('Does your county located next to the Danube? (yes, no) ')
                if answer6=='yes':
                    answer7=input('Does your county located next to the country border? (yes, no) ')
                    if answer7=='yes':
                        print('You live in Baranya County.')
                        break
                    elif answer7=='no':
                        print('You live in Tolna County.')
                        break
                    else:
                        print('Wrong answer.')
                elif answer6=='no':
                    answer8=input('Do you live in a county which is located to the south form the Lake Balaton? (yes, no) ')
                    if answer8=='yes':
                        print('You live in Somogy County.')
                        break
                    elif answer8=='no':
                        print('You live in Zala County.')
                        break
                    else:
                        print('Wrong answer.')                  
        elif answer=='to the east':
            answer9=input('Do you live in a county which is next to the Tisza (not intersecting it)? (yes, no) ')
            if answer9=='yes':
                answer10=input('Do you live to the east from the Tisza? (yes, no) ')
                if answer10=='yes':
                    answer11=input('Do you live in the eastern county of the country? (yes, no) ')
                    if answer11=='yes':
                        print('You live in Szabolcs-Szatmár-Bereg County.')
                        break
                    elif answer11=='no':
                        print('You live in Hajdú-Bihar County.')
                        break
                    else:
                        print('Wrong answer.') 
                elif answer10=='no':
                    answer12=input('Do you live in the northest county of the country? (yes, no) ')
                    if answer12=='yes':
                        print('You live in Borsod-Abaúj-Zemplén County.')
                        break
                    elif answer12=='no':
                        print('You live in Heves County.')
                        break
                    else:
                        print('Wrong answer.')
                else:
                    print('Wrong answer.')
            elif answer9=='no':
                answer13=input('Do you live in a county which is intersected by the Tisza (not next to it)? (yes, no) ')
                if answer13=='yes':
                    answer14=input('Do you live in a county which is located next to the country border? (yes, no) ')
                    if answer14=='yes':
                        print('You live in Csongrád-Csanád County.')
                        break
                    elif answer14=='no':
                        print('You live in Jász-Nagykun-Szolnok County.')
                        break
                    else:
                        print('Wrong answer.')
                elif answer13=='no':
                    answer15=input('Do you live in a county next to Pest County? (yes, no)')
                    if answer15=='yes':
                        print('You live in Nógrág County.')
                        break
                    elif answer15=='no':
                        print('You live in Békés County.')
                        break
                    else:
                        print('Wrong answer.')          
        else:
            print('Wrong answer.')
    
    • Oh, wow, nice job!!! That’s what I call a nested for loop + if statement. 😀
      I haven’t tested it but my first thought was that this probably can be made shorter by using Python’s switch + case syntax. (I haven’t written any tutorial about it yet.)

      Great job again, and thanks for sharing it, Balazs!

Leave a Reply