Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Programming Entry Level: introduction while loop

Understandingwhile Loops for Beginners

Hey there, future coder! You've probably already learned about how to make your programs do thingsonce. But what if you want them to do somethingrepeatedly? That's where loops come in, and today we're going to tackle one of the most fundamental: thewhile loop.

while loops are super important because they allow you to automate repetitive tasks. They're used everywhere in programming, from games to web applications to data analysis. You'll definitely encounter questions about them in coding interviews, so getting a solid grasp now will really help you down the line!

Understandingwhile Loops

Imagine you're making a cup of tea. You need to boil water, and you keep checking if it's boiling. Youcontinue checkingwhile the water isn't boiling yet. Once it boils, you stop checking.

That's exactly what awhile loop does! It repeatedly executes a block of codeas long as a certain condition is true.

Here's the basic structure:

while (condition is true) {  // Code to be executed repeatedly}
Enter fullscreen modeExit fullscreen mode

Thecondition is an expression that evaluates to eithertrue orfalse. The code inside the curly braces{} (or indented in Python) is executed repeatedlyas long as thecondition remainstrue. Once thecondition becomesfalse, the loop stops, and the program continues with the next line of code after the loop.

Think of it like a gatekeeper. The gatekeeper (thewhile loop) only lets people (the code) pass throughwhile they have a valid ticket (thecondition is true). Once someone doesn't have a ticket, the gatekeeper stops letting people through.

Basic Code Example

Let's look at a simple example in #"Count is:"+count);count=count+1;// Or count++;}console.log("Loop finished!");

Enter fullscreen modeExit fullscreen mode

Let's break this down:

  1. let count = 0; This line initializes a variable calledcount and sets its initial value to 0. This variable will be used to control how many times the loop runs.
  2. while (count < 5) { ... } This is thewhile loop itself. It says: "As long as the value ofcount is less than 5, execute the code inside the curly braces."
  3. console.log("Count is: " + count); This line prints the current value ofcount to the console.
  4. count = count + 1; This line increases the value ofcount by 1. This is crucial! Without this line, thecount would always be 0, and the loop would run forever (we'll talk about that in the "Common Mistakes" section).
  5. console.log("Loop finished!"); This line is executedafter the loop has finished.

This code will print the following to the console:

Count is: 0Count is: 1Count is: 2Count is: 3Count is: 4Loop finished!
Enter fullscreen modeExit fullscreen mode

Now, let's look at the same example in Python:

count=0whilecount<5:print("Count is:",count)count+=1# Equivalent to count = count + 1print("Loop finished!")
Enter fullscreen modeExit fullscreen mode

The logic is exactly the same as the JavaScript example. Python uses indentation to define the code block that belongs to thewhile loop, instead of curly braces.

Common Mistakes or Misunderstandings

Here are some common pitfalls to avoid when working withwhile loops:

1. Infinite Loops

❌ Incorrect code:

letcount=0;while(count<5){console.log("Count is:"+count);// Missing the increment statement!}
Enter fullscreen modeExit fullscreen mode

✅ Corrected code:

letcount=0;while(count<5){console.log("Count is:"+count);count=count+1;}
Enter fullscreen modeExit fullscreen mode

Explanation: If you forget to update the variable that controls the loop (in this case,count), the condition willalways be true, and the loop will run forever. This is called an infinite loop, and it can freeze your program.

2. Off-by-One Errors

❌ Incorrect code:

count=0whilecount<=5:print("Count is:",count)count+=1
Enter fullscreen modeExit fullscreen mode

✅ Corrected code:

count=0whilecount<5:print("Count is:",count)count+=1
Enter fullscreen modeExit fullscreen mode

Explanation: Sometimes you want the loop to run a specific number of times. Using<= instead of< can cause the loop to run one extra time than intended. Pay close attention to your condition!

3. Incorrect Condition

❌ Incorrect code:

letcount=5;while(count>0){console.log("Count is:"+count);count=count-1;}
Enter fullscreen modeExit fullscreen mode

✅ Corrected code:

letcount=5;while(count>0){console.log("Count is:"+count);count=count-1;}
Enter fullscreen modeExit fullscreen mode

Explanation: This examplelooks correct, but if you intended to countdown from 5 to 1, you need to make sure your condition and increment/decrement are aligned. In this case, it's correct, but it's a good habit to double-check.

Real-World Use Case: Simple Number Guessing Game

Let's create a simple number guessing game in Python:

importrandomsecret_number=random.randint(1,10)guess=0whileguess!=secret_number:try:guess=int(input("Guess a number between 1 and 10:"))ifguess<1orguess>10:print("Please enter a number between 1 and 10.")elifguess<secret_number:print("Too low!")elifguess>secret_number:print("Too high!")exceptValueError:print("Invalid input. Please enter a number.")print("Congratulations! You guessed the number:",secret_number)
Enter fullscreen modeExit fullscreen mode

This game generates a random number between 1 and 10. Thewhile loop continues to ask the user for a guess until they guess the correct number. Thetry...except block handles potential errors if the user enters something that isn't a number.

Practice Ideas

Here are a few ideas to practice yourwhile loop skills:

  1. Countdown Timer: Write a program that takes a number as input and counts down to 0, printing each number.
  2. Multiplication Table: Write a program that prints the multiplication table for a given number (e.g., the 5 times table).
  3. Even Number Collector: Write a program that asks the user for numbers until they enter an odd number. Then, print all the even numbers they entered.
  4. Simple Calculator: Create a basic calculator that continues to perform calculations until the user enters "quit".
  5. Rock, Paper, Scissors: Implement a simplified version of Rock, Paper, Scissors where the computer randomly chooses and the user plays until they win.

Summary

Congratulations! You've taken your first steps into the world ofwhile loops. You now understand how to use them to repeat code as long as a condition is true, and you've learned about some common mistakes to avoid.

Don't be afraid to experiment and try different things. The best way to learn is by doing! Next, you might want to explorefor loops, which are another powerful type of loop, or dive deeper into conditional statements. Keep coding, and have fun!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

DevOps Fundamentals

Enjoying our posts?Support us on Ko-fi ❤️

Buy us a coffee

More fromDevOps Fundamentals

Programming Entry Level: learn data structures
#entrylevel#programming#coding#learndatastructures
Programming Entry Level: examples functions
#entrylevel#programming#coding#examplesfunctions
NodeJS Fundamentals: HTTPS
#runtime#programming#javascript#https
DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp