►► Python For Loops: ◄◄

Prince

[ Verified Seller ]
Staff member
Trusted Seller
Joined
11 yrs. 6 mth. 26 days
Messages
5,381
Reaction score
18,380
Age
45
Wallet
11,590$
[0x01] Python For Loop:
For loops are traditionally used when you have a piece of code which you want to repeat n number of times. The for loop can iterate over items of any sequence, such as list, commands, strings, and integers. This being said loops have great power and can save developers lots of time and lines of code.

[0x02] For Loop Syntax:

for iterating_variable in sequence:statments(s)


[*] Flow Diagram:




Quick thing to note down it never forget to have an indention in your block of code.This is the first thing you should learn as a python developer, block indentions. Python is very unique and just missing one of these indentions can cause a whole program not to run. Back to the syntax, if a sequence contains and expression list, it is evaluated first. Then, the first item in the sequence is assigned to the iterating variable -> interating_variable. Next, the statements block is executed that we just discussed. Each item in our given list is then assigned to the "iterating_variable", and the "statement(s)" block is executed until the entire sequence is exhausted or stopped by a loop control statement or a return statement.

[*] Quick Example:

for char in 'Zentrix':print 'Spelling zentrix:', charfavs = ['Zentrix', 'Mrgreen', 'Logic']for names in favs:print 'I love no homo:', names

OUTPUT:Spelling zentrix: ZSpelling zentrix: eSpelling zentrix: nSpelling zentrix: tSpelling zentrix: rSpelling zentrix: iSpelling zentrix: xI love no homo: ZentrixI love no homo: MrgreenI love no homo: Logic


[0x03] Sequence Indexing
Another simple and effective way of iterating through a list of items is by index offset into the sequence itself:

favs = ['Zentrix', 'Mrgreen', 'Logic']for index in range(len(favs)):print 'I love no homo:', favs[index]

OUTPUT:I love no homo: ZentrixI love no homo: MrgreenI love no homo: LogicThe above code works because we used two of pythons built-in functions: len() & range(). The len() function above gives us the total number of elements in the given list "favs" and range() gives us the sequence to iterate over in the list. Each element is specified an index number in the list, Zentrix being #1 (of course he is :>) Mrgreen being #2 and Logic being #3. So when "favs[index]" is called every index number just corresponds to the item in the list and then prints it out for us.


[0x04] The great Else: statment used in a for Loop
This is where loops become so very helpful. Here I will be discussing the if and else statements being used inside a loop and in the next section I will show you how to nest for loops inside one another. So first lets gets some basic tips down for the else statement being used in a loop:

Tip #1: If the else statement is used with a for loop. the else is executed when the loop has exhausted or finished iterating the list.Tip #2: If the else statement is used with a while loop, (will not be discussing now, but known as condition testing loop "True False conditions"), the else statement is executed when the condition becomes false.Look below for an example of using the else statement with the for statement.

for char in 'hello':if char == 'H':print ' Cap H was found in hello'else:print 'Cap H was not found in hello'

OUTPUT:Cap H was not found in hello


[0x05] Nested For Loops
A nested loop can be quite useful when you are wanting to either do a large work load or just combine sequences to get a final output. Below is the basic syntax for a nested for loop statement:

for iterating_variable in sequence:for iterating_variable in sequence:statements(s)statements(s)

Quick Example:for x in range(2):for y in range(2):print 'x:', xprint 'y:', y         text = x + y                 print 'x + y =', text         print


OUTPUT:x: 0y: 0x + y = 0x: 0y: 1x + y = 1x: 1y: 0x + y = 1x: 1y: 1x + y = 2

[0x06] How for loops can be of use in cryptography
As many may know, Im REALLY interested in the cryptography field. For most encryptions, a programming language is needed to help generate algorithms, encryptions, and keys. The for loop is a great asset to me when I want to iterate over text and messages to apply a simple cipher to. Here is a small example of how the caesar cipher can encrypted and decrypted using a for loop with the else statement.

for arg in sys.argv:if arg in ("--caesar"):raw = raw_input('Enter Text File to Encrypt-Decrypt:')mode = raw_input('Mode:')files = open(raw, 'r')message = files.read()key = int(raw_input('Key:'))LETTERS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'translated = ''for symbol in message:if symbol in LETTERS:num = LETTERS.find(symbol)if mode == 'encrypt':num = num + keyelif mode == 'decrypt':num = num - keyif num >= len(LETTERS):num = num - len(LETTERS)elif num < 0:num = num + len(LETTERS)translated = translated + LETTERS[num]else:translated = translated + symboloutput = open(raw, 'w')output.write(translated)


[0x07] Closing
Well thats some basic knowledge on the python for loop. Hope some people find this useful! Good luck to all the python developers. :p
 
Top Bottom