STR Coding Club logo STR Coding ClubLearn to code, together
Python and Practice

Python For Loop Exercises With Six Beginner Problems

You can read a for loop in a tutorial and nod along, then open a blank file and have no idea what to put after the word "for". That gap between reading and writing is normal, and the only reliable way across it is practice.

A student at a club table typing Python code on a laptop, a notebook beside it with a hand drawn triangle of stars and a times table

You can read a for loop in a tutorial and nod along, then open a blank file and have no idea what to put after the word "for". That gap between reading and writing is normal, and the only reliable way across it is practice. These Python for loop exercises give you six short problems, each built around one habit a for loop needs, in the order I teach them at our club.

Plan on about 75 minutes for the whole set. Type every line yourself, run your code after each small change, and only look at the hints when you have been stuck for a solid ten minutes.

What a for loop actually does

A for loop takes a collection of things and hands them to you one at a time. The collection can be a list, a string, a range of numbers, or the lines of a file. On each pass, the loop variable holds the current item, and the indented block underneath runs once for that item.

Read the line for name in names as "for each name in the list called names". The word after "for" is a new variable you are creating. The word after "in" must already exist. Mixing those two up is the first bug almost every beginner hits.

Two other facts save a lot of confusion:

  • range(5) gives 0, 1, 2, 3, 4. It starts at zero and stops before the number you give it.
  • range(1, 11) gives 1 to 10. The second number is always left out.

If loops still feel abstract, our article on Python loops explained with things you already do builds the idea from everyday routines first.

Six Python for loop exercises

Exercise 1: the times table

Ask the user for a number, then print its times table from 1 to 12, one line each, in the form 7 x 3 = 21.

What it teaches: using range with a start and an end. Remember that input gives you text, so convert it with int before you multiply. If your table stops at 11, check the second number in your range.

Exercise 2: the running total

Given the list scores = [12, 7, 19, 4, 15], print the total and the average without using the built in sum function.

What it teaches: the accumulator pattern. Create total = 0 before the loop, add each score to it inside the loop, and print after the loop ends. The most common mistake is putting total = 0 inside the loop, which resets it on every pass and leaves you with only the last score. For the average, divide by len(scores), which here gives 11.4.

Exercise 3: count the vowels

Ask the user for a sentence and print how many vowels it contains. "Coding club rocks" should give 5.

What it teaches: looping over a string, one character at a time. Inside the loop, check whether the lowercase version of the character is in the string "aeiou". This is your first loop with an if statement inside it, and it is worth noticing how the two indentation levels line up.

Exercise 4: the biggest number

Given temps = [18, 23, 21, 27, 19, 25], find and print the highest value without using max.

What it teaches: tracking a "best so far" value. Start with highest = temps[0], then compare every item and replace highest when you find something larger. Starting with highest = 0 seems fine until someone gives you a list of negative winter temperatures, which is a useful bug to discover on purpose.

Exercise 5: numbered shopping list

Given items = ["bread", "milk", "eggs", "apples"], print them as a numbered list starting at 1, like 1. bread.

What it teaches: enumerate. Write for number, item in enumerate(items, start=1). Many beginners build a separate counter variable instead, and that works, but enumerate removes a whole category of off by one errors. Try it both ways and compare how many lines each takes.

Exercise 6: the star triangle

Ask for a height and print a right angled triangle of stars. A height of 4 gives one star on the first line, two on the second, and so on up to four.

What it teaches: nested loops, or a neat shortcut. The outer loop counts rows. You can either use an inner loop to print stars one by one with end="" to stay on the same line, or multiply a string with "*" * row. Do it with the nested loop first, because that is the skill you will need later for grids and tables.

Common for loop mistakes and quick fixes

SymptomLikely causeFix
Loop runs one time too fewrange end is excludedAdd 1 to the second number
Total only shows the last itemAccumulator reset inside the loopMove total = 0 above the for line
IndentationErrorMixed tabs and spacesSet your editor to insert 4 spaces
TypeError when multiplyinginput returned textWrap the input in int
Print runs once instead of every passPrint line is not indentedIndent it to match the loop body

Keep this table open while you work. Our longer list of common Python mistakes new coders repeat covers more errors beyond loops.

Why you should not start with list comprehensions

Many online answers will tell you to write [x * 2 for x in numbers] instead of a full loop, because it is shorter and "more Pythonic". For working programmers that advice is fine. For someone in their first month, I think it is a trap.

A comprehension hides the three things you are trying to learn: where the result list is created, what happens on each pass, and when the loop ends. When it breaks, you get one line of code and an error that points at the whole thing. A plain loop gives you four lines, and you can put a print on any of them to see what is going on.

So write every exercise above as a normal loop first. Once you can do all six without hints, go back to Exercise 2 and Exercise 5 and rewrite them as comprehensions. You will understand them in five minutes instead of memorising a pattern you cannot debug.

How to practise these so they stick

Doing the set once helps. Doing it three times across a week makes it automatic. Here is the routine our members use:

  1. Day 1: work through all six with hints allowed.
  2. Day 3: redo them from a blank file, no hints, with a 10 minute limit each.
  3. Day 7: change each problem slightly, such as a times table that counts down or a vowel counter that also counts consonants.

When you get properly stuck, try the steps in how to get unstuck on a practice problem without peeking before you search for an answer.

Frequently asked questions

What is the difference between a for loop and a while loop in Python?

A for loop goes through a collection that already exists, so it knows how many passes it will make. A while loop keeps going as long as a condition is true, which suits cases like waiting for correct user input. If you can name the thing you are looping over, use a for loop.

How many for loop exercises should a beginner do?

Quality beats quantity. Six varied problems done three times over a week teach more than thirty similar ones done once. Move on when you can write each from a blank file without hints.

Why does range not include the last number?

Python's range stops before the end value so that range(5) gives exactly five items, which matches list lengths and indexes. It feels odd at first, but it makes code like range(len(items)) work without adjustments.

BN
Bartholomew Ng

Bartholomew taught maths for years before switching to teaching Python. He writes about the basics of the language and about teaching code without drowning learners in syntax.

More posts by Bartholomew

More in Python and Practice

01doorganico 084goad 3hot8 4465456 after5internprogram ahandfulofblessings ahmadpc ahomcybersecurity allodialresources annodex antiquesandperiodcollectibles aotc asianworldkashmir beedlectrics bloggertemplatefree bluefeatheragency bodyweightsolution campaign08blog carfixadvisor catstreetcollective cbstvsports cnfanspurchasing committeeof500yearsofdignityandresistance covertopsdjs cs-kaiyuangame cuestacomunicaciontotal cxoutlet dancebetgame deskgearhub destinyvillastay detectmagazine di33 diamondsteelbuildings donmo dyanadropship emarsysfinance emimattl escapechan eskitarih evautoplay everythingweddings-orlando farmzone feedviewerapp foxstudiosscratch gamevui123 gleasongrade greetingsday hacklabasu haskell iw-kaiyun jagoanproperti jilidskripsi joltbusinessfinance juegodepokergratis juegospucca kaeru-festival latestmehndidesigns lestanzediottaviano litemagazines localcommunityhero lustrsazan mariashebets menswheels newwebstechs1 nikkit ootheday oxigenvpn plurfitness prefetial probudgetcarpetcleaning psychicmrsmartin pyaten qvantor rejoignezlogis rexzbot riselayouts ruchin rwxqsgd5 sakaltime shibiaowang shop-bot skrtips spotlesshaven tetapatrium topselller uneplanteartificielle vipertechcr webtech1223411 wo-kygaming yamaha-mekar yeknava yoybuysheets zenunwa yamaha-mekar jilidskripsi ankertoto ankertoto ankertoto