New to python. Can't get my head around loops

im new to python and I’ve been struggling lately with loops and in the [Code Challenge: Loops]
challenge. (https://www.codecademy.com/courses/learn-python-3/lessons/python-functions-loops-cc)

I’ve had no problem up until now, but its like I’ve hit a road block. in every challenge it feels like I had to look at the “look here if you’re stuck” box or literally just look at the whole answer so i could get a grip of what was actually going on.

I would be thankful if i could get tips just in general how i should think and tackle the problems. Should i go back and revisit everything I’ve learned so far? relearn and go back to loops when I feel I have everything up until then under absolute control?

And how do you think when you see a loop? I really just want to know the thought processes so i can continue learning and so i can grasp everything.

Im thankful for all kinds of answers.

1 Like

Hi there! Welcome to the forums!

In Python, there’s two kinds of loops: for loops, and while loops. They behave slightly differently, but ultimately the point of a loop is to execute the same block of code - which Python calls the “suite” - multiple times in a row.

For loops

A for loop is good if you have a sequence of things, and you want to run the same suite of code against each of those things.

Here’s an example:

from random import randint

def odd_or_even(numbers):
    if not isinstance(numbers, list):
        print("Not a list!")
        return None

    output = {
        "nums" : numbers,
        "odd" : 0,
        "even" : 0,
        }

    for number in numbers:
        if number % 2 == 0:
            result = "even"
            output["even"] += 1
        else:
            result = "odd"
            output["odd"] += 1

        print("%d is %s!" % (number,result))

    return output

random_numbers = [randint(1,10) for i in range(10)]
print("Checking random numbers: ",random_numbers)

result = odd_or_even(random_numbers)
print("In the list %r, there are %d odd and %d even numbers." % (result["nums"],result["odd"],result["even"]))

Here I’ve defined a function, odd_or_even, which takes a list of numbers* as input. Within the function, you can see I have this line: for number in numbers:

The for loop takes the first value from the list - or any other iterable value - and puts it in a temporary variable, which in this case is number. We then run the code suite inside the for loop, using the current value of number. When we get to the end of the code block we take the next value from the list, assign that value to number, and run the code all over again.

(Bonus: I have another for loop on this line: random_numbers = [randint(1,10) for i in range(10)]. This is called a list comprehension, which you might not have covered yet. The for loop is serving the same purpose, though - having Python do the same thing once for every item in the iterable value, which here is the range object.

Don’t worry if the list comprehension confuses you, so long as the main for example in my function makes sense.)

While loops

A while loop, in contrast to a for loop, looks at a boolean condition - true or false - and uses that to decide whether or not it needs to run the code suite another time.

Another example:

def double_up(number):
    if number > 1000:
        print("%d is already over 1000!" % (number))
    else:
        count = 0
        start = number
        while number < 1000:
            number *= 2
            count += 1
        print("You need to double the number %d %d times to get over 1000!" % (start,count))
    return None

double_up(2)
double_up(10)

Here, I’ve defined a function double_up.

The loop is here: while number < 1000:, and let’s say I called the function like this: double_up(50).

The first time we get to the loop, number = 50. Python evaluates the loop condition the same way it would for an if/else structure - number < 1000. Since 50 is less than 1000, we run the code suite in the loop, and double the number to 100.

Python now re-evaluates the loop condition - is number still less than 1000. The answer is yes, so we run the loop again, and double the value to 200. Here’s the steps:

  1. number = 50, 50 < 1000 = true, run the loop -> number = 100.
  2. number = 100, 100 < 1000 = true, run the loop -> number = 200.
  3. number = 200, 200 < 1000 = true, run the loop -> number = 400.
  4. number = 400, 400 < 1000 = true, run the loop -> number = 800.
  5. number = 800, 800 < 1000 = true, run the loop -> number = 1600.
  6. number = 1600, 1600 < 1000 = false, end the loop -> number = 1600.

Where a for loop will only run a finite number of times - once for every item in the iterator you give it** - a while loop will continue until its condition becomes false. This makes it possible for you to create an infinite loop, one where the condition never becomes false and the loop never ends!

while loops are useful if you need to continue doing something, but you don’t know how many times you’ll need to do it or if you just want to continue until something interrupts your program - for instance, a terminal program which continues until the user enters Q to quit…

Hopefully that’s given you an idea of what the different types of loops do, and some rudimentary examples of their use. If anything’s still unclear, though, let me know and I’ll try and explain better. :slight_smile:

Caveats

* I’ve added a test in the function to check that the input is a list, but not one to check that each item pulled from the list is a number… Oops.

** Generally speaking, a for loop will run once for every value in the iterator. This is not guaranteed, though: your code may terminate the loop early, by way of the break keyword, or if you mutate the iterator during iteration you can get some fun behaviour…

3 Likes

Thank you so much for your time and effort!
superb answer! I’ll start practicing more for loops and while loops right away.
Thanks once again!

1 Like

No worries. :slight_smile:

If you get stuck with anything else, pop back and ask us and we’ll do what we can to help. :slight_smile: