DEV Community

Cover image for 🎁Learn Python in 10 Days: Day 3
William
William

Posted on

🎁Learn Python in 10 Days: Day 3

Today, we're continuing our 10-day journey to learn Python, kicking off Day 3's lesson. If you haven't checked out Day 1 yet, you can find it here: 🎁Learn Python in 10 Days: Day 1

Hey there! Let's dive into loops in Python, using some everyday examples and some hands-on coding. Here's a breakdown of the main points, all formatted nicely for you.

Day 3: Loop Statements 🎉

Loops are everywhere in our daily lives, and just like that, they play a crucial role in programming as well. Let's get down to the basics of loops in Python! 🐍✨

1. Basic Syntax of the while Loop

Basic while Loop in Python:

i = 0
while i < 100:
    print("Hello, world!")
    i += 1
Enter fullscreen mode Exit fullscreen mode
  • Explanation:
    1. The while loop continues as long as the condition is True.
    2. You need to set a condition to stop the loop, like i += 1 paired with i < 100 to avoid an infinite loop.
    3. Indentation is crucial, just like with if statements.

Example: Sum of Numbers from 1 to 100

i = 1
total = 0
while i <= 100:
    total += i
    i += 1
print(f"The total sum is: {total}")
Enter fullscreen mode Exit fullscreen mode

Example: Guess the Number Game

import random

num = random.randint(1, 100)
count = 0
flag = True

while flag:
    guess_num = int(input("Guess the number: "))
    count += 1
    if guess_num == num:
        print("Congratulations! You guessed it!")
        flag = False
    elif guess_num > num:
        print("Too high!")
    else:
        print("Too low!")

print(f"You guessed it in {count} tries.")
Enter fullscreen mode Exit fullscreen mode

2. Nested while Loops

Example: Sum of Factorials from 1 to 100

i = 1
total_sum = 0

while i <= 100:
    fact = 1
    j = 1
    while j <= i:
        fact *= j
        j += 1
    total_sum += fact
    i += 1

print(total_sum)
Enter fullscreen mode Exit fullscreen mode

Example: Multiplication Table (9x9)

i = 1
while i <= 9:
    j = 1
    while j <= i:
        print(f"{i}*{j}={i*j}\t", end='')
        j += 1
    i += 1
    print()  # New line after each row
Enter fullscreen mode Exit fullscreen mode

3. Basic Syntax of the for Loop

  • Unlike while, for loops are used for iterating over a sequence (like a list, tuple, dictionary, set, or string).

Example: Iterating Over a String

name = "Bob"
for char in name:
    print(char, end='')
Enter fullscreen mode Exit fullscreen mode

Example: Counting Occurrences of 'a' in a String

sample_str = "abcdefaac"
count = 0
for char in sample_str:
    if char == 'a':
        count += 1
print(count)
Enter fullscreen mode Exit fullscreen mode

range() Function:

  • Syntax 1: range(num) generates numbers from 0 to num-1.
  • Syntax 2: range(start, end) generates numbers from start to end-1.
  • Syntax 3: range(start, end, step) uses a step value.

Example: Counting Even Numbers

num = int(input("Enter a number: "))
count = 0

for x in range(1, num):
    if x % 2 == 0:
        count += 1

print(count)
Enter fullscreen mode Exit fullscreen mode

4. Nested for Loops

Example: Multiplication Table (9x9) with for Loops

for i in range(1, 10):
    for j in range(1, i+1):
        print(f"{i}*{j}={i*j}\t", end='')
    print()  # New line after each row
Enter fullscreen mode Exit fullscreen mode

5. Loop Control Statements: break and continue

  • continue: Skips the rest of the code inside the loop for the current iteration only.
  • break: Terminates the loop.

Example: Payroll with Performance Check

money = 10000

for num in range(1, 21):
    grade = random.randint(1, 10)
    if grade < 5:
        print(f"Employee {num} has a performance score below 5. No salary issued.")
        continue

    if money >= 1000:
        money -= 1000
        print(f"Employee {num} meets performance criteria. Company balance: {money}")
    else:
        print(f"Insufficient funds. Balance: {money}")
        break
Enter fullscreen mode Exit fullscreen mode

Top comments (0)