Python 3.6 Read File Lines With While Loop
What are loops and when do y'all use them?
Loops are an essential construct in all programming languages. In a loop structure, the programme first checks for a condition. If this condition is true, some piece of code is run. This code will keep on running unless the status becomes invalid.
For case, look at the following block of pseudo code:
IF stomach_empty eat_food() ENDIF //check if stomach is empty again. IF stomach_empty eat_food() ENDIF //check if breadbasket is yet empty, //....
Hither, we are checking whether the stomach_empty
variable is truthful
. If this condition is met, the plan volition execute the eat_food
method. Furthermore, notice that we are typing the same code multiple times, which means that this breaks the DRY rule of programming.
To mitigate this problem, we can utilize a loop structure similar and then:
WHILE stomach_empty //this lawmaking will continue on running if stomach_empty is true eat_food() ENDWHILE
In this code, we are using a while
statement. Hither, the loop get-go analyzes whether the stomach_empty
Boolean is true
. If this condition is satisfied, the program keeps on running the eat_food
function until the status becomes simulated. We will acquire about while
loops later in this commodity.
To summarize, developers use loops to run a piece of code multiple times until a certain condition is met. As a result, this saves time and promotes lawmaking readability.
Types of loops
In Python, in that location are two kinds of loop structures:
-
for
: Iterate a predefined number of times. This is as well known equally a definite iteration -
while
: Go along on iterating until the condition issimulated
. This is known every bit an indefinite iteration
In this article, you will learn the following concepts:
-
for
loops- Syntax
- Looping with numbers
- Looping with lists
- Listing comprehension
- Syntax
- Usage with lists
- Usage with numbers
-
while
loops- Syntax
- Looping with numbers
- Looping with lists
- Loop command statements
-
interruption
statement -
continue
statement -
pass
argument - The
else
clause
-
for
loops
A for
loop is a blazon of loop that runs for a preset number of times. It likewise has the power to iterate over the items of any sequence, such as a list or a string.
Syntax
for i in <collection>: <loop body>
Here, collection
is a list of objects. The loop variable, i
, takes on the value of the next element in collection
each time through the loop. The code within loop body
keeps on running until i
reaches the terminate of the collection.
Looping with numbers
To demonstrate for
loops, let's utilize a numeric range loop:
for i in range(10): # collection of numbers from 0 to 9 print(i)
In this piece of code, nosotros used the range
function to create a collection of numbers from 0 to 9. Afterwards, we used the print
function to log out the value of our loop variable, i
. As a result, this will output the list of numbers ranging from 0 to nine.
The range(<terminate>)
method returns an iterable that returns integers starting with 0, up to but not including <stop>
.
We tin even use conditional statements in our loops like so:
for i in range(ten): # numbers from 0-9 if i % two == 0: # is divsible past 2? (even number) print(i) # then impress.
This block of code will output all even numbers ranging from 0 to nine.
Looping with lists
We can even utilise a for
loop to iterate through lists:
names = ["Bill Gates", "Steve Jobs", "Mark Zuckerberg"] # create our list for name in names: # load our list of names and iterate through them print(name)
In the in a higher place snippet, we created a list called names
. Later on, nosotros used the for
control to iterate through the names
assortment then logged out the contents of this list.
The snippet below uses an if
statement to return all the names that include letter 'B':
names = ["Bill Gates", "Billie Eilish", "Marking Zuckerberg"] # create our list for proper noun in names: # load our list of names and iterate through them if "B" in name: # does the name include 'B'? print(name)
List comprehension
In some cases, you might want to create a new listing based off the data of an existing list.
For example, look at the following code:
names = ["Bill Gates", "Billie Eilish", "Mark Zuckerberg", "Hussain"] namesWithB = [] for proper noun in names: if "B" in proper noun: namesWithB.append(name) # add together this element to this array. print(namesWithB)
In this code, we used the for
control to iterate through the names
array and then checked whether any element contains the letter B
. If truthful, the plan appends this corresponding chemical element to the namesWithB
list.
Using the ability of list comprehension, we can shrink this block of code past a large extent.
Syntax
newlist = [<expression> for <loop variable> in <list> (if condition)]
Here, expression
can be a slice of code that returns a value, for instance, a method. The elements of list
volition be appended to the newlist
array if loop variable
fulfills the condition
.
Usage with lists
Permit's rewrite our code that we wrote before using list comprehension:
names = ["Bill Gates", "Billie Eilish", "Mark Zuckerberg", "Hussain"] namesWithB = [name for name in names if "B" in name] impress(namesWithB)
In this code, nosotros iterated through the names
array. According to our condition, all elements containing the letter B
will exist added to the namesWithB
list.
Usage with numbers
We can utilise the range
method in listing comprehension like so:
numbers = [i for i in range(ten)] print(numbers)
Find that in this example, we don't have a conditional statement. This means that conditions are optional.
This snippet of code will employ a condition to get the list of even numbers between 0 and ix:
while
loops
With the while
loop, we can execute a block of code as long as a condition
is true
.
Syntax
while <condition>: <loop body>
In a while
loop, the condition
is first checked. If information technology is true
, the code in loop body
is executed. This process will repeat until the condition
becomes imitation
.
Looping with numbers
This piece of code prints out integers betwixt 0
and 9
.
northward = 0 while n < ten: # while n is less than 10, print(north) # print out the value of n n += 1 #
Here's what'due south happening in this instance:
- The initial value of
n
is0
. The program start checks whethern
is more than10
. Since this istrue
, the loop body runs - Within the loop, we are first printing out the value of
n
. After on, we are incrementing information technology by1
. - When the body of the loop has finished, program execution evaluates the condition again. Because it is notwithstanding truthful, the body executes over again.
- This continues until
n
exceedsx
. At this signal, when the expression is tested, it isimitation
, and the loop halts.
Looping with lists
Nosotros can use a while
cake to iterate through lists similar and so:
numbers = [0, 5, 10, 6, 3] length = len(numbers) # go length of assortment. n = 0 while n < length: # loop status print(numbers[northward]) northward += one
Here'south a breakup of this programme:
- The
len
function returns the number of elements present in thenumbers
array - Our
while
statement first checks whetherdue north
is less than thelength
variable. Since this is true, the program will impress out the items in thenumbers
list. In the end, we are incrementing then
variable - When
n
exceedslength
, the loop halts
Loop control statements
There are three loop command statements:
-
break
: Terminates the loop if a specific condition is met -
continue
: Skips one iteration of the loop if a specified condition is met, and continues with the next iteration. The departure betweencontinue
andsuspension
is that thebreak
keyword will "bound out" of the loop, butcontinue
will "jump over" one bicycle of the loop -
laissez passer
: When you don't desire any command or code to execute.
We can apply all of these in both while
and for
loops.
1. break
The break
argument is useful when you want to exit out of the loop if some condition is true
.
Here is the interruption
keyword in activity:
names = ["Neb Gates", "Billie Eilish", "Mark Zuckerberg", "Hussain"] for name in names: if proper name == "Mark Zuckerberg": print("loop go out here.") intermission # finish this loop if condition is true. print(proper name) print("Out of the loop")
A few inferences from this code:
- The plan start iterates through the
names
array - During each cycle, Python checks whether the current value of
name
isMark Zuckerberg
- If the above condition is satisfied, the program will tell the user that it has halted the loop
- Yet, if the condition is
false
, the programme will impress the value ofname
2. continue
The continue
statement tells Python to skip over the current iteration and motility on with the next.
Here is an example:
names = ["Neb Gates", "Billie Eilish", "Mark Zuckerberg", "Hussain"] for proper noun in names: if proper noun == "Mark Zuckerberg": impress("Skipping this iteration.") continue # Skip iteration if truthful. impress(proper name) print("Out of the loop")
Here is a breakup of this script:
- Go through the
names
array - If the app encounters an element that has the value
Mark Zuckerberg
, apply thego on
statement to jump over this iteration - Otherwise, print out the value of our loop counter,
name
three. pass
Use the pass
statement if you don't want any control to run. In other words, pass
allows yous to perform a "null" functioning. This tin can be crucial in places where your code will go but has not been written withal.
Here is a simple case of the pass
keyword:
names = ["Beak Gates", "Billie Eilish", "Mark Zuckerberg", "Hussain"] for proper noun in names: if proper noun == "Marking Zuckerberg": print("Just passing by...") pass # Move on with this iteration print(name) print("Out of the loop")
This will be the output:
4. The else
clause
Python allows us to append else
statements to our loops as well. The code inside the else
block executes when the loop terminates.
Here is the syntax:
# for 'for' loops for i in <drove>: <loop torso> else: <lawmaking block> # will run when loop halts. # for 'while' loops while <condition>: <loop body> else: <code block> # will run when loop halts
Hither, one might think, "Why not put the code in code
block
immediately after the loop? Won't information technology accomplish the same matter?"
At that place is a minor difference. Without else
, lawmaking cake
will run after the loop terminates, no thing what.
However, with the else
argument, code cake
will not run if the loop terminates via the intermission
keyword.
Here is an example to properly understand its purpose:
names = ["Pecker Gates", "Billie Eilish", "Mark Zuckerberg", "Hussain"] print("Else won't run here.") for name in names: if name == "Mark Zuckerberg": print("Loop halted due to break") break # Halt this loop print(proper name) else: # this won't piece of work considering 'suspension' was used. print("Loop has finished") print(" \n Else argument will run here:") for proper name in names: impress(proper name) else: # will work considering of no 'break' argument print("second Loop has finished")
This volition exist the output:
Conclusion
In this article, y'all learned how to use the for
and while
loop in Python programming. Moreover, you also learned almost the fundamentals of list comprehension and loop altering statements. These are crucial concepts that assist yous in increasing your Python skills.
Give thanks you so much for reading!
LogRocket: Total visibility into your web apps
LogRocket is a frontend application monitoring solution that lets y'all replay problems every bit if they happened in your own browser. Instead of guessing why errors happen, or request users for screenshots and log dumps, LogRocket lets you replay the session to chop-chop empathise what went wrong. Information technology works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
In addition to logging Redux actions and country, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the folio, recreating pixel-perfect videos of even the most complex single-page and mobile apps.
Effort it for complimentary.
Source: https://blog.logrocket.com/for-while-loops-python/
0 Response to "Python 3.6 Read File Lines With While Loop"
Post a Comment