4-1 Working with For-Loop (syntex)

python

Looping through an entire List

when you want to do the same action with every item in a list, you can use Python’s for loop. Let’s say we have a list of magician’s names and we want to print out each name in the list.

This loop system approach could cause several problems for one, it would be repetitive to do this with a long list of names. Also we’d have to change our code each time the list’s length changed. A for loop avoids both of these issues by letting Python manage these issues internally. Let’s use a for loop to print out each name in a list of magicians :

magicians = ['alice' , 'david' , 'carolina']
for magician in magicians:
	print(magician)

The output is a simple printout of each name in the list :

alice
david
carolina

A closer look at looping

One of the most common ways to automates repetitive tasks. For example :

for magician in magicians:

This line tells Python to retrieve the first value from the list magicians and associate it with the variable magician. This first value is ‘alice’ . Python the reads the next line :

	print(magician)

Python prints the current value of magician which is still ‘alice’. Because the list contains more values, Python returns to the first line of the loop :

for magician in magicians:

Python retrieves the next name in the list, ‘david’ , and associates that value with the variable magicians.Python then executes the line:

print(magician)

Python prints the current value of magician again, which is now ‘david’ . Python repeats the entire loop once more with the last value in the list ‘carolina’ . Because no more values are in the list, Python moves on to the next line in program. In this case nothing comes after the for loop, so the program simply ends.

Doing more work within a for-loop

Printing a message to each magician, telling they performed a great trick.

magicians = ['alice' , 'david' , 'carolina']
for magician in magicians:
	print(f"{magician.title()}, that was a great trick!")

The output shows a personalized message for each magician in the list:

Alice, that was a great trick!
David, that was a great trick!
Carolina, that was a great trick!

You can write many lines as you like in the for loop. Every intended line following the line for magician in magicians is considered inside the loop, and each indented line is executed once for each value in the list. Let’s add a second line to our message.

magicians = ['alice' , 'david' , 'carolina']
for magician in magicians:
	print(f"{magician.title()}, that was a great trick!")
	print(f"I can't wait to see your next trick, {magician.title()}. \n")

Why I put a \n to end of the line. This will make a blank line after printing that pair of lines.

Alice, that was a great trick!
I can't wait to see your next trick, Alice. 

David, that was a great trick!
I can't wait to see your next trick, David. 

Carolina, that was a great trick!
I can't wait to see your next trick, Carolina. 

Doing something after a for loop

Any lines of code after the for loop that are not indented are executed once without repetition.

magicians = ['alice' , 'david' , 'carolina']
for magician in magicians:
	print(f"{magician.title()}, that was a great trick!")
	print(f"I can't wait to see your next trick, {magician.title()}. \n")
print("Thank you, everyone, That was a great magic show!")
Alice, that was a great trick!
I can't wait to see your next trick, Alice. 

David, that was a great trick!
I can't wait to see your next trick, David. 

Carolina, that was a great trick!
I can't wait to see your next trick, Carolina. 

Thank you, everyone, That was a great magic show!

When you’re processing data using a for loop, you’ll find that this is a good way to summarize an operation that was performed on an entire data set.

Avoiding Indentation Errors

Python uses indentation to determine how a line, or group of lines, is related to the rest of the program. As you begin to write code that relies on proper indentation, you’ll need to watch for a few common indentation errors, For example, people sometimes indent lines of code that don’t need to be indented or forget to indent lines that need to be indented. For example :

Forgetting to Indent

Always indent the line after the for statement in a loop.

magicians = ['alice' , 'david' , 'carolina']
for magician in magicians:
print(f"{magician.title()}, that was a great trick!")

Python Trace back error :

File "C:\Users\visith\OneDrive\Documents\Programming\Test.py", line 3
    print(f"{magician.title()}, that was a great trick!")
    ^
IndentationError: expected an indented block

You can usually resolve this kind of indentation error by indenting the line or lines immediately after the for statement.

Forgetting to Indent Additional lines (Logical error)

Sometimes your loop will run without any errors but won’t produced the expected result. For example :

magicians = ['alice' , 'david' , 'carolina']
for magician in magicians:
	print(f"{magician.title()}, that was a great trick!")
print(f"I can't wait to see your next trick, {magician.title()}. \n")
Alice, that was a great trick!
David, that was a great trick!
Carolina, that was a great trick!
I can't wait to see your next trick, Carolina. 

If you expect to see certain action repeated once for each item in a list and it’s executed only once, determine whether you need to simply indent a line or a group of lines.

Indenting unnecessarily

If you accidentally indent a line that dosen’t need to be indented, Python informs you about the unexpected indent

message = "Hello python world!"
	print(message)

Python trace back error :

File "C:\Users\visith\OneDrive\Documents\Programming\Test.py", line 2
    print(message)
IndentationError: unexpected indent

You can avoid unexpected indention errors by indenting only when you have a specific reason to do so.

Indenting unnecessarily after the loop

If you accidentally indent code that should run after a loop has finished that code will be repeated once for each item in list. Sometimes this prompts python to report an error, but often this will result in a logical error.

Forgetting the colon:

The colon at the end of a for statement tells Python to interpret the next line as the start of a loop. If you accidentally forget the colon, You’ll get a syntax error because Python dosen’t know what you’re trying to do.

Popular posts from this blog

Mustacchio - TryHackMe

Tech_Supp0rt: 1 - TryHackMe