While Loop in Python
While Loop
While loop is entry control loop.Disadvantage of “For” loop is we cannot use condition in the loop. In python , if we need a loop which works on condition then we go with while loop. Also if we need an infinite loop we can use while loop.
While Loop in Python
A while loop in Python is used to repeatedly execute a block of code as long as a specified condition is True. The loop continues executing as long as the condition remains True, and it terminates when the condition becomes False.
Syntax of While loop
while(condition):
#statements
Syntax of infinite while loop
while(True):
#statements
(or)
while(1):
#statements
Working
- Step 1: Take while loop with a condition
- Step 2: Evaluate expression in Boolean form
- Step 3: If boolean condition is True then it go inside the loop , if boolean condition is False then it terminates the loop
- Step 4: It execute the statements inside the loop
- Step 5: Step 3 is repeated until the condition becomes False.
Python Code:
a=1 b=10 #loop with True condition while(a<=b): print(a,end=" ") a+=1 #for incrementing a print("\nValues at the point of terminating loop are : a={} and b={}".format(a,b))
Output: 1 2 3 4 5 6 7 8 9 10 Values at the point of terminating loop are : a=11 and b=10
Nested While loop
#printing a box pattern using nested while loop i,n=0,5 while(i < n): j=0 while(j < n): print("*",end=" ") j+=1 i+=1 print()
Output: * * * * * * * * * * * * * * * * * * * * * * * * *
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment