Skip to main content

What Are Python While Loops?

 What Are Python While Loops?

What Are Python While Loops?

Anatomy of a While loop

A while loop will continuously execute code depending on the value of a condition. It begins with a keyword while, followed by a comparison to be evaluated, then a colon. On the next line is the code block to be executed . Indented to the right . Similar to an if statement, the code in the body will only be executed if the comparison is evaluated to be true. What sets a while loop apart, however, is that this code block will keep executing as long as the evaluation statement is true. Once the statement is no longer true, the loop exist and the next line of the code will be executed.

Example:

username = get-username()

while not valid_username(username):

        print("Invalid username")

        username = get_username() 

The break Statement

With the break statement we will stop the loop albeit the while condition is true:
Example

Exit the loop once I is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1

The continue Statement

With the continue statement we will stop the present iteration, and continue with the next:
Example

Continue to subsequent iteration if i is 3:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)

The else Statement

With the else statement we will run a block of code once when the condition not is true:
Example
Print a message once the condition is false:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is not any longer but 6")

While Loop inside a function

def attempts(n):

    x+=1

    while x<=n:

print("Attempt"+Str(x))

print("Done")

attempts(5)

Common Pitfalls with Variable Initialization

We'll want to watch out for a common mistake:forgetting to initialize variables. If we try to use a variable without first initializing it, we'll run into a NameError. This is the Python interpreter catching the mistake and telling us that we're using an undefined variable. The fix is pretty simple:initialize the variable by assigning the variable a value before we use it.

Another common mistake to watch out for that can be a little trickier to spot is forgetting to initialize variables with the correct value. If we use a variable earlier in our code and then reuse it later in a loop without first setting the value to something we want, our code may wind up doing something we didn't expect. Don't forget to initialize our variables before using them.

Why initializing Variables Matters

while my_variable<10:

    print("Hello")

my_variable+=1

(NameError)

my_variable = 5

while my_variable<10:

    print("Hello")

my_variable+=1

Infinite Loops and Code Blocks

Another easy mistake that can happen when using loops is introducing an infinite loop. An infinite loop means the code block in the loop will continue to execute and never stop. This can happen when the condition being evaluated in a while loop doesn't change. Pay close attention to the variables and what possible values they can take. Think about unexpected values, like zero. We may see an error message that reads "Evaluation took more than 5 seconds to complete".  This means that the code encountered an infinite loop, and it timed out after 5 seconds. We should take a closer look at the code and variables to spot where the infinite loop is.

More about Python

Using Python on our own

The best way to learn any programming language is to practice it on our own as much as we can. If we have Python installed on our computer, we can execute the interpreter by running the Python3 command (or just python on Windows), and we can close it by typing exit() or Ctrl-D.

If we don't already have Python installed on our machine, that's alright.  We can still practice by using one of the many online Python interpreters or codepads available online. There's not much difference between an interpreter and a codepad. An interpreter is more interactive than codepad, but they both let us execute code and see the results.

Below find links to some of the most popular online interpreters and codepads. Give them a go to find our favorite.

  • https://www.python.org/shell/
  • https://www.onlinegdb.com/online_python_interpreter
  • https://repl.it/languages/python3
  • https://tutorialspoint.com/execute_python3_online_php
  • https://rextester.com/I/python3_online_compiler
  • https://trinket.io/python3

Additional Python resources

Some great ways to help us find additional info:

  • Read the official Python documentation.
  • Search for answers or ask a question on Stack Overflow.
  • Subscribe to the Python tutor mailing list, where we can ask questions and collaborate with other Python learners.
  • Subscribe to the Python-announce mailing list to read about the latest updates in the language.

Popular posts from this blog

What is Internet of Things (IoT)?

 What is Internet of Things (IoT)?    The internet of Things, or IoT, refers to the billions of physical devices  round the  world that are now connected to  the web  , collecting, sharing and analyses  of knowledge  . It presents and provides the explanation of the network of physical things which is embedded with software , sensors,  and other technologies for the benefit of connecting and exchanging data with other devices and systems on the internet   . Due to the cheap processors and wireless networks, it's possible to  means  anything, from a pill to an aero plane to a self-driving car into  an area  of the IoT. Overview IoT will control the Fourth  technological revolution  . The Fourth  technological revolution  is changing the very software-defined automation allows manufacturers to link all stages of  the worth  chain, rapidly adapt to changing markets , and make highly personalized products on a mass scale. The opportunities provided by this revolution are authenticated

What is Rust Borrowing?

What is Rust Borrowing? Borrowing We call having references as function parameters borrowing. As in real world , if an individual owns something, we 'll borrow it from them . Whenever we’re done, we 've got to offer it back. Referencing  The reference is that the act of consulting somebody or something so as to urge information We would  declare reference in terms of Rust programing as if we are taking a replica of it without damaging or taking its ownership. ‘&’ symbol is employed to pass the reference Have a look that  how ‘&’ symbol is employed in code. fn main() { let s1 = String::from("hello"); let len = calculate_length(&s1); println!("The length of {} is {}.", s1, len); } fn calculate_length(s: &String) -> usize { s.len()} Mutable References The actual concept of mutable reference is same as we use mutable variable When  we  need to  modify  mutable reference is employed once   the worth we make regard to.

Kubernetes Readiness Probes

 Kubernetes Readiness Probes Description We understand that liveness probes and the way they assist keep our apps healthy by ensuring unhealthy containers are restarted automatically. Same like liveness probes, Kubernetes permit us to also define a readiness looked for our pod. The readiness probe is deployed periodically and examines whether the precise pod should receive client requests or not. Whenever a container’s readiness probe returns back success, it’s signaling that the container is ready to simply accept requests. This notion of being prepared is clearly something that’s specific to every container. Almost as liveness probe Kubernetes sends requests to container and supported the result either successful or unsuccessful response it decides container is prepared to require traffic or still preparing for that. The liveness probes not like, if a container fails the readiness check, it won’t be killed or restarted.   This is a very good practice to