🔧 Python While Loop tutorial
Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to
The while loop in Python allows you 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
The block of code will be executed as long as the condition
is true. Once the condition
becomes false, the program will move on to the next line of code after the while loop.
Example - Counting with a While Loop
One common use case for a while loop is to count up to a certain number. Here's an example:
count = 1
while count <= 5:
print(count)
count += 1
In this example, we initialize the count
variable to 1
. Then, we enter a while loop with the condition count <= 5
. As long as count
is less than or equal to 5
, the block of code will execute.
Inside the block, we print the current value of count
and then increment it by 1 using the +=
operator. When count
becomes 6, the condition becomes false and the program exits the while loop.
The output of this program will be:
1
2
3
4
5
Example - User Input with a While Loop
Another use case for a while loop is to repeatedly ask the user for input until they provide a valid response. Here's an example:
name = ""
while not name:
name = input("What is your name? ")
print("Hello, " + name + "!")
In this example, we initialize the name
variable to an empty string. Then, we enter a while loop with the condition not name
. As long as name
is an empty string, the block of code will execute.
Inside the block, we use the input()
function to ask the user for their name. If the user enters a non-empty string, the condition not name
becomes false and the program exits the while loop.
Finally, we print a greeting message using the name
variable.
The output of this program will depend on the user's input.
...
🔧 Python While Loop Tutorial #Day3
📈 32.19 Punkte
🔧 Programmierung
🔧 Python While Loop Tutorial #Day3
📈 32.19 Punkte
🔧 Programmierung
🔧 Python While Loop tutorial
📈 32.19 Punkte
🔧 Programmierung
🔧 Python One Line While Loop
📈 23.97 Punkte
🔧 Programmierung
🐧 Python: While-Loop
📈 23.97 Punkte
🐧 Server
🔧 Python While Loop Examples
📈 23.97 Punkte
🔧 Programmierung
🔧 Python While Loop Examples
📈 23.97 Punkte
🔧 Programmierung
🔧 Day 16 - Slicing,for loop and nested loop
📈 19.65 Punkte
🔧 Programmierung
🔧 No more for/while loop in JavaScript
📈 18.81 Punkte
🔧 Programmierung
🔧 While Loop
📈 18.81 Punkte
🔧 Programmierung
🔧 while loop - task
📈 18.81 Punkte
🔧 Programmierung
🔧 do while loop
📈 18.81 Punkte
🔧 Programmierung
🔧 While loop.
📈 18.81 Punkte
🔧 Programmierung
🔧 31.do while Loop
📈 18.81 Punkte
🔧 Programmierung
🔧 While loop C++
📈 18.81 Punkte
🔧 Programmierung