Beginning Python Programming—Part 4

There is a keyword that allows us to skip over a loop iteration.

It is the continue keyword.

Using the example from above, we will change it to count only in multiples of a number.

number_to_count_by = 4number_to_start_with = 11current_number = number_to_start_withsum_of_all_numbers = 0while true: if current_number % number_to_count_by != 0: current_number += 1 continue sum_of_all_numbers += current_number current_number += 1 if current_number == 100: breakSee if you can follow this logic.

I’m sure by now you are starting to see why descriptive variable names help the readability of your code.

Breaking this down line by line:while True means run indefinitely.

True is a constant for 1.

False is a constant for 0.

if current_number % number_to_count_by != 0.

If the remainder of 11 / 4 is not 0, add 1 to current_number, so we don’t trap ourselves in an infinite loop and skip over this iteration using continue.

If we didn’t finish performing the logic for this round.

Add the current_number to the sum_of_all_numbers.

We know when this executes it will have to be a number divisible by number_to_count_by based on the prior logic.

current_number += 1.

I know it looks like we already did this, but we really haven’t.

If our current_number was not divisible by number_to_count_by evenly, then we added 1 to current_number and skipped over everything else.

We never did anything for current_number if the if statement evaluated to false.

Finally, as a catch-all to keep us from an infinite loop even if the current_number wasn’t divisible by number_to_count_by,if current_number >= 100 we break.

For LoopsThe sibling to while loops are for loops.

For loops are used primarily in lists and dictionaries, but they can also be used in a range of characters or numbers.

Here’s how for loops look:# Using listsnames = ["Bob", "Mary", "John", "David"]for name in names: separated_names += name + " "# Using dictionariespets = { "Spot": "Dog", "Sassy": "Cat", "Jerry": "Mouse", "Tom": "Cat", "Jimminey": "Cricket",}for (name, type) in pets: pet_names.

append(name) if pet_type_counts[type] is None: pet_type_counts[type] = 1 else: pet_type_counts[type] += 1# Using rangescount = 0for value in range(count, 10): count += 1OK, so a few new things here.

First of all, let’s talk about the for loop.

A for loop needs a few things to get started.

First, you need to give it a variable that you plan to use in the body of the loop and you should give it a meaningful name.

In the first example, we use for name in names.

This reads for the current name we are iterating over in the list names.

Next, we add logic on what to do with the name.

In our case, we create a nice long string with all of the names using string concatenation.

When we have looped through all of the names, the for loop exits.

Dictionaries are a little different but are based around the same idea.

In our example above, we have some weird syntax up front, for (name, type).

This actually introduces another type we haven’t talked about called a tuple.

A tuple is a list of comma-separated variables surrounded in parentheses that can contain a value for each variable in the list.

They are passed around as a single variable.

We will cover them more in the future, but for now, that’s all you need to know.

The reason for this is dictionaries have two parts to each item they contain.

A key and a value.

The key is the first part of the dictionary, the value is the second part.

Keys are used for accessing values.

If you were using a real dictionary, the word that you want to look up would be your key, and the definition you find would be the value.

When we use for (name, type) it can be directly translated to for (key, value) in dictionary.

So with that said let us move onward.

We iterate through each key-value pair in the dictionary, for every key, or name, we append it to pet_names.

For every value, or type, we check to see if we have a key for the type.

In the case pet_type_counts keys would be “Dog,” “Cat,” “Mouse,” or “Cricket.

” Because dictionary keys may or may not exist, we need to be careful.

First, we check if pet_type_counts[name] is None.

If it is we need to set the initial value to 1 since our current iteration holds that type.

Otherwise, we do have a value in pet_type_counts[name] and we just need to update the value.

If you try to pull a value out of a dictionary where the key doesn’t exist, you get a KeyValue error and your program will crash.

I promise I will talk about errors and how to deal with them in a future article.

In the last example, I show you how to use a for-in loop with a range.

First we give it the variable value to use in the loop, then we give it range so it knows which number to start at, and, finally, we give it a range between count which is 0 and 10.

The loop iterates through all of the numbers and adds them together.

Now I can ask you to write a program where you give me all the numbers divisible by 3 between 57 and 398 and you can do it.

I can do that in my head, but it would take a while.

The nice thing about programming is you take a lot less time to write it out and the computer does the calculation for you in less than a second.

SummaryWhew, that was a lot, but we’re learning some really cool stuff.

In this post, you learned about how you can make decisions in your programs, and you learned how to loop through data sets and numbers.

Think about how far you’ve come.

We have a lot more to learn though, so I strongly suggest that you read up on the Python documentation as a follow-up and for more information.

Don’t worry if you see something you don’t quite understand yet, I’ll probably cover it in the next part.

Suggested reading:If you haven’t already, you should check out the Python tutorial and go through chapters 1 through 4.

4…The Python Tutorial – Python 3.


3 documentationPython is an easy to learn, powerful programming language.

It has efficient high-level data structures and a simple but…docs.


org… and skip ahead to chapter 5 and read it in full.


Data Structures – Python 3.


3 documentationRemove the item at the given position in the list, and return it.

If no index is specified, removes and returns the…docs.


orgI understand it’s out of order, but I’m explaining the most common things first.

We will cover all of the topics in these tutorials.

If you want to read more because you are hungry, I won’t stop you.

We will jump back to 4.

6 to talk about functions very soon.

What’s NextFunctions and Scope are what’s next.

Here’s a little sneak peek.

Functions allow you to take a segment of related code and break it out into a separate section that you can re-use as many times as you want.

Scope helps us keep things organized and our memory usage low, but not without a huge tradeoff responsible for many bugs.

As usual, keep exploring, and try to make your own program that does something neat.

Don’t have any ideas?.At this point, you can make decisions and loop through arrays.

Why not see if you can sort this array of 15 numbers from smallest to largest or largest to smallest, without using sort.

No cheating.

[21, 46, 32, 38, 30, 35, 82, 94, 40, 28, 16, 51, 90, 86, 46]Good luck!.. More details

Leave a Reply