We’ll want to watch out for a common mistake:forgetting to initialize variables. With the else statement we will run a block of code once when the condition not is true:Įxample # 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 With the continue statement we will stop the present iteration, and continue with the next:Įxample # 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 break statement we will stop the loop albeit the while condition is true:Įxample # Exit the loop once I is 3: i = 1 while i < 6: print(i) if i = 3: break i += 1 The continue Statement Once the statement is no longer true, the loop exist and the next line of the code will be executed.Įxample: username = get_username() while not valid_username(username): print(“Invalid username”) username = get_username() The break Statement What sets a while loop apart, however, is that this code block will keep executing as long as the evaluation statement is true. Similar to an if statement, the code in the body will only be executed if the comparison is evaluated to be true. On the next line is the code block to be executed. It begins with a keyword while, followed by a comparison to be evaluated, then a colon. A while loop will continuously execute code depending on the value of a condition.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |