https://imbooz.com/im-blog-data-science/04-python-while-loops/
Python While Loops
In Python, a while
loop is used to execute a block of code repeatedly as long as a certain condition is true. The syntax for a while
loop is as follows:
while condition:
# block of code to be executed while the condition is true
In each iteration of the loop, the condition is checked. If the condition is true, the block of code inside the loop is executed. Then the condition is checked again, and if it is still true, the block of code is executed again, and so on, until the condition becomes false.
Here is an example of a while
loop that counts from 1 to 5:
Python Code:
count = 1
while count <= 5:
print(count)
count += 1
Python While Loops
In this example, the loop will execute as long as the value of count
is less than or equal to 5. In each iteration of the loop, the current value of count
is printed and then count
is incremented by 1 using the +=
operator. The loop will terminate when count
becomes 6, at which point the condition count <= 5
will be false.
Here is another example of a while
loop that prompts the user to enter a number between 1 and 10:
Python Code:
num = 0
while num < 1 or num > 10:
num = int(input(“Enter a number between 1 and 10: “))
print(“You entered”, num)
Python While Loops
In this example, the loop will prompt the user to enter a number repeatedly until the user enters a number between 1 and 10 (inclusive). The condition num < 1 or num > 10 will be true as long as the user enters a number outside that range. Once the user enters a valid number, the loop will terminate and the program will print a message confirming the number that was entered.
while loops can be useful in many situations where you need to repeat a block of code until a certain condition is met. However, you need to be careful when using while loops, as it is easy to create an infinite loop if you do not update the condition correctly within the loop.
Python While Loops Python Code:
i = 1
while i <= 10:
print(i*i, end='t')
i += 1
149162536496481100
Python Code:
i = 1
while i <= 10:
print(i, end=' + ')
i += 1
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + Python Code:
i = 1
while i <= 10:
if i < 10:
print(i, end=" + ")
else:
print(i)
i += 1
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 Python Code:
i = 1
while i <= 10:
print(i,'/',i*i, end='t')
i += 1
1 / 12 / 43 / 94 / 165 / 256 / 367 / 498 / 649 / 8110 / 100 Python Code:
temp_v = 1
while temp_v <= 10:
print(temp_v,end='/')
print(temp_v*temp_v, end = 't')
temp_v += 1
1/12/43/94/165/256/367/498/649/8110/100