How to Have a for Loop Run Again With a Different Variable Python
24. For Loops
By Bernd Klein. Last modified: eighteen April 2022.
Introduction
Like the while loop the for loop is a programming language statement, i.east. an iteration statement, which allows a code cake to be repeated a certain number of times.
There are inappreciably whatever programming languages without for loops, but the for loop exists in many different flavours, i.east. both the syntax and the semantics differs from one programming linguistic communication to another.
Unlike kinds of for loops:
-
Count-controlled for loop (Three-expression for loop)
This is by far the nearly common blazon. This argument is the one used by C. The header of this kind of for loop consists of a iii-parameter loop control expression. Generally it has the course: for (A; Z; I) A is the initialisation role, Z determines a termination expression and I is the counting expression, where the loop variable is incremented or dcremented. An example of this kind of loop is the for-loop of the programming language C: for (i=0; i <= n; i++) This kind of for loop is not implemented in Python!
-
Numeric Ranges
This kind of for loop is a simplification of the previous kind. Information technology's a counting or enumerating loop. Starting with a kickoff value and counting up to an end value, like for i = 1 to 100 Python doesn't use this either.
-
Vectorized for loops
They behave equally if all iterations are executed in parallel. That is, for example, all expressions on the correct side of assignment statements get evaluated before the assignments.
-
Iterator-based for loop
Finally, we come to the one used by Python. This kind of for loop iterates over an enumeration of a set of items. It is usually characterized by the use of an implicit or explicit iterator. In each iteration step a loop variable is set to a value in a sequence or other data drove. This kind of for loop is known in almost Unix and Linux shells and information technology is the 1 which is implemented in Python.
Syntax of the For Loop
Every bit we mentioned earlier, the Python for loop is an iterator based for loop. It steps through the items of lists, tuples, strings, the keys of dictionaries and other iterables. The Python for loop starts with the keyword "for" followed by an capricious variable name, which will concord the values of the following sequence object, which is stepped through. The general syntax looks like this:
for <variable> in <sequence>: <statements> else: <statements>
The items of the sequence object are assigned i subsequently the other to the loop variable; to be precise the variable points to the items. For each item the loop trunk is executed.
Example of a simple for loop in Python:
languages = [ "C" , "C++" , "Perl" , "Python" ] for language in languages : impress ( language )
OUTPUT:
The else cake is special; while Perl developer are familiar with it, it's an unknown concept to C and C++ programmers. Semantically, it works exactly as the optional else of a while loop. It will exist executed only if the loop hasn't been "broken" by a break statement. So it will only be executed, afterward all the items of the sequence in the header have been used.
If a pause statement has to be executed in the programme menstruum of the for loop, the loop volition be exited and the program menstruation volition continue with the commencement statement following the for loop, if there is any at all. Usually interruption statements are wrapped into conditional statements, e.g.
edibles = [ "salary" , "spam" , "eggs" , "nuts" ] for nutrient in edibles : if food == "spam" : print ( "No more spam delight!" ) intermission print ( "Great, delicious " + food ) else : print ( "I am so glad: No spam!" ) print ( "Finally, I finished stuffing myself" )
OUTPUT:
Not bad, succulent bacon No more than spam please! Finally, I finished stuffing myself
Removing "spam" from our listing of edibles, we will gain the post-obit output:
$ python for.py Great, delicious bacon Great, delicious eggs Keen, succulent basics I am so glad: No spam! Finally, I finished stuffing myself $
Mayhap, our cloy with spam is not then high that nosotros want to cease consuming the other nutrient. Now, this calls the go along statement into play . In the following little script, we use the proceed statement to become on with our listing of edibles, when nosotros have encountered a spam item. So keep prevents us from eating spam!
edibles = [ "bacon" , "spam" , "eggs" , "nuts" ] for food in edibles : if nutrient == "spam" : print ( "No more than spam delight!" ) continue impress ( "Great, delicious " + food ) print ( "Finally, I finished stuffing myself" )
OUTPUT:
Great, succulent bacon No more spam please! Great, delicious eggs Bang-up, succulent nuts Finally, I finished stuffing myself
The range() Function
The congenital-in function range() is the correct part to iterate over a sequence of numbers. Information technology generates an iterator of arithmetic progressions: Example:
OUTPUT:
This result is not self-explanatory. It is an object which is capable of producing the numbers from 0 to iv. We tin utilise information technology in a for loop and you will see what is meant by this:
for i in range ( 5 ): print ( i )
OUTPUT:
range(n) generates an iterator to progress the integer numbers starting with 0 and ending with (due north -1). To produce the listing with these numbers, we accept to cast range() with the list(), every bit we practise in the following example.
OUTPUT:
[0, 1, ii, 3, 4, 5, half dozen, 7, 8, 9]
range() tin can too be called with two arguments:
range(begin, end)
The above call produces the list iterator of numbers starting with brainstorm
(inclusive) and ending with one less than the number end
.
Example:
OUTPUT:
OUTPUT:
So far the increment of range() has been one. We tin can specify a different increment with a third argument. The increment is called the step
. It can exist both negative and positive, but not nada:
range(begin,cease, step)
Example with step:
OUTPUT:
[4, 9, fourteen, nineteen, 24, 29, 34, 39, 44, 49]
Information technology can be done backwards besides:
OUTPUT:
[42, 35, 28, 21, xiv, 7, 0, -7]
The range() function is especially useful in combination with the for loop, every bit nosotros can meet in the post-obit example. The range() function supplies the numbers from 1 to 100 for the for loop to calculate the sum of these numbers:
north = 100 sum = 0 for counter in range ( 1 , n + 1 ): sum = sum + counter impress ( "Sum of ane until %d : %d " % ( north , sum ))
OUTPUT:
Live Python training
Upcoming online Courses
Enrol hither
Calculation of the Pythagorean Numbers
By and large, information technology is assumed that the Pythagorean theorem was discovered by Pythagoras that is why it has his proper noun. Nonetheless, there is a debate whether the Pythagorean theorem might take been discovered earlier or by others independently. For the Pythagoreans, - a mystical movement, based on mathematics, religion and philosophy, - the integer numbers satisfying the theorem were special numbers, which had been sacred to them.
These days Pythagorean numbers are not mystical anymore. Though to some pupils at school or other people, who are not on good terms with mathematics, they may still appear so.
So the definition is very elementary: Three integers satisfying a2+b2=c2 are called Pythagorean numbers.
The following program calculates all pythagorean numbers less than a maximal number. Remark: We take to import the math module to be able to calculate the square root of a number.
from math import sqrt due north = int ( input ( "Maximal Number? " )) for a in range ( ane , n + 1 ): for b in range ( a , n ): c_square = a ** ii + b ** 2 c = int ( sqrt ( c_square )) if (( c_square - c ** 2 ) == 0 ): print ( a , b , c )
OUTPUT:
3 4 v v 12 xiii half dozen eight ten seven 24 25 8 15 17 ix 12 xv 9 40 41 10 24 26 eleven lx 61 12 16 20 12 35 37 xiii 84 85 fourteen 48 l fifteen 20 25 15 36 39 xvi 30 34 sixteen 63 65 18 24 30 eighteen 80 82 20 21 29 20 48 52 20 99 101 21 28 35 21 72 75 24 32 40 24 45 51 24 70 74 25 60 65 27 36 45 28 45 53 28 96 100 30 40 l 30 72 78 32 sixty 68 33 44 55 33 56 65 35 84 91 36 48 threescore 36 77 85 39 52 65 39 80 89 40 42 58 40 75 85 40 96 104 42 56 70 45 60 75 48 55 73 48 64 fourscore 48 90 102 51 68 85 54 72 ninety 56 ninety 106 57 76 95 sixty 63 87 60 80 100 60 91 109 63 84 105 65 72 97 66 88 110 69 92 115 72 96 120 80 84 116
Iterating over Lists with range()
If you have to access the indices of a list, it doesn't seem to be a skilful idea to use the for loop to iterate over the lists. We can admission all the elements, but the index of an chemical element is non available. Nonetheless, there is a way to access both the index of an element and the element itself. The solution lies in using range() in combination with the length role len():
fibonacci = [ 0 , 1 , 1 , ii , 3 , 5 , 8 , 13 , 21 ] for i in range ( len ( fibonacci )): print ( i , fibonacci [ i ]) impress ()
OUTPUT:
0 0 ane one ii 1 3 2 iv 3 5 5 6 viii 7 13 eight 21
Remark: If you apply len() to a list or a tuple, you get the number of elements of this sequence.
List iteration with Side Effects
If yous loop over a listing, information technology's best to avoid changing the list in the loop torso. Take a look at the following instance:
colours = [ "reddish" ] for i in colours : if i == "red" : colours += [ "blackness" ] if i == "black" : colours += [ "white" ] print ( colours )
OUTPUT:
['reddish', 'black', 'white']
To avoid these side effects, information technology's all-time to work on a copy past using the slicing operator, as can be seen in the adjacent example:
colours = [ "red" ] for i in colours [:]: if i == "red" : colours += [ "blackness" ] if i == "black" : colours += [ "white" ] print ( colours )
OUTPUT:
We still might have done something, we shouldn't accept done. We changed the list "colours", but our change didn't have whatever effect on the loop. The elements to be looped remained the same during the iterations.
Exercises with for Loops
Exercise 1
This do is about the Ramanujan-Hardy number. There is a petty anecdote of the Mathematician Thousand.H. Hardy when he visited Indian mathematician Srinivasa Ramanujan in infirmary. It goes like this:
I remember once going to see him when he was ill at Putney. I had ridden in taxi cab number 1729 and remarked that the number seemed to me rather a tedious one, and that I hoped it was not an unfavourable omen. "No," he replied, "it is a very interesting number; it is the smallest number expressible as the sum of two cubes in two unlike ways."
For this reason 1732 is known as the Ramanujan-Hardy number.
Can you verify this with a Python program?
Exercise 2
1729 is the lowest number which can be represented by a Loeschian quadratic form $a^ii + ab + b^two$ in four unlike ways, with positive integers a and b .
Solutions
Solution to Do 1
import math number = 1729 due north = int ( number ** ( 1 / three )) cubes = {} for i in range ( north + 1 ): for j in range ( i ): result = i ** 3 + j ** 3 if effect in cubes : cubes [ outcome ] . append (( i , j )) else : cubes [ result ] = [( i , j )] if result > number : intermission for ten in cubes : if len ( cubes [ 10 ]) > 1 : print ( x , cubes [ ten ])
OUTPUT:
Solution to Exercise two
import math number = 1729 n = int ( number ** ( 1 / 2 )) results = {} for a in range ( n + i ): for b in range ( a ): event = a ** 2 + a * b + b ** ii if result in results : results [ issue ] . suspend (( a , b )) else : results [ result ] = [( a , b )] if upshot > number : break for x in results : if len ( results [ x ]) > three : print ( x , results [ x ])
OUTPUT:
1729 [(25, 23), (32, 15), (37, viii), (40, iii)]
Live Python grooming
Upcoming online Courses
Enrol here
Source: https://python-course.eu/python-tutorial/for-loop.php
0 Response to "How to Have a for Loop Run Again With a Different Variable Python"
Post a Comment