Stopping a while loop mid-way - Python

2024/9/20 12:26:47

What is the best way to stop a 'while' loop in Python mid-way through the statement? I'm aware of break but I thought using this would be bad practice.

For example, in this code below, I only want the program to print once, not twice...

variable = ""
while variable == "" :print("Variable is blank.")# statement should break here...variable = "text"print("Variable is: " + variable)

Can you help? Thanks in advance.

Answer

break is fine, although it is usually used conditionally. Used unconditionally, it raises the question of why a while loop is used at all:

# Don't do this
while condition:<some code>break<some unreachable code># Do this
if condition:<some code>

Used conditionally, it provides a way of testing the loop condition (or a completely separate condition) early:

while <some condition>:<some code>if <other condition>:break<some more code>

It is often used with an otherwise infinite loop to simulate the do-while statement found in other languages, so that you can guarantee the loop executes at least once.

while True:<some code>if <some condition>:break

rather than

<some code>
while <some condition>:<some code>
https://en.xdnf.cn/q/119605.html

Related Q&A

Click on element in dropdown with Selenium and Python

With Selenium and Chrome webdriver on MacOS need to click dropdown element. But always have an error that cant find. Have this html code on a page where it located:<select id="periodoExtrato&qu…

Send cv2 video stream for face recognition

Im struggling with a problem to send a cv2 videostream (webcam) to a server (which shall be used later for face recognition). I keep getting the following error for the server: Traceback (most recent c…

Generate all possible lists from the sublist in python [duplicate]

This question already has answers here:How to get the Cartesian product of multiple lists(20 answers)Closed 7 years ago.Suppose I have list [[a, b, c], [d, e], [1, 2]]I want to generate list where on t…

Time/frequency color map in python

Is there in native Python 3.X library or in scipy/numpy/matplolib libraries a function or their short set which could help me to draw a plot similar to this one(?):What would be an efficient way to ac…

ImageMagick is splitting the NASAs [.IMG] file by a black line upon converting to JPG

I have some raw .IMG format files which Im converting to .jpg using ImageMagick to apply a CNN Classifier. The converted images, however have a black vertical line splitting the image into two. The par…

CV2 - rectangular detecting issue

Im trying to implement an OMR using pythons CV2. As part of the code I need to find the corners of the choices box (rectangulars) however I ran into difficulty causes by the grade sheet template. In th…

Keras/TensorFlow - high acc, bad prediction

Im new to machine learning and Im trying to train a model which detects Prague city in a sentence. It can be in many word forms.Prague, PRAHA, Z Prahy etc...So I have a train dataset which consists of …

Flask-HTTPAuth: how to pass an extra argument to a function decorated with @auth.verify_password?

Heres a small Flask app authenticated with Flask-HTTPAuth. How to pass an argument (such as authentication on/off flag, or verbosity level / debug on/off flag) to a function (such as authenticate below…

AttributeError: numpy.ndarray object has no attribute split

Given a text file with one DNA sequence on each line and joining these together I now want to split the string into 5 sequences (corresponding to each of the 5 rows). This is the file source: http://ww…

How do I determine if a lat/long point is within a polygon?

I have a shapefile of all the counties that make up my state. Using the shapefile (which contains geometric for the district polygons) I was able to use geopandas to plot the shapes in a figure. I have…