Day 5: Mastering Loops, Conditions, and Password Generation in Python


Hello, Python Enthusiasts!
Welcome to Day 5 of my 100 Days of Python journey! Today was all about loops, conditional statements, and creating a fun program to generate random passwords. These tools are fundamental to programming and open up endless possibilities for problem-solving. Let’s explore what I learned.
1. For Loops and While Loops
Loops are used to execute a block of code repeatedly, either for a fixed number of iterations (using for
) or while a condition is true (using while
).
Example:
# Using a for loop to iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I love {fruit}!")
# Using a while loop
count = 5
while count > 0:
print(f"Countdown: {count}")
count -= 1
These loops help automate repetitive tasks efficiently.
2. Nested Loops and Conditional Logic
Nested loops allow you to execute a loop within another loop, and combining them with conditions adds powerful logic.
Example:
# Nested loop with conditional logic
for i in range(1, 4):
for j in range(1, 4):
if i == j:
print(f"Match found: i = {i}, j = {j}")
else:
print(f"i = {i}, j = {j} are not equal")
Nested loops can be used to solve complex problems like matrix operations or generating combinations.
3. Password Generator Project
Today’s highlight was building a program to generate random passwords. This project combined randomness, loops, and list manipulations.
Example:
import random
import string
# Define the password length
password_length = int(input("Enter the desired password length: "))
# Create a pool of characters
characters = string.ascii_letters + string.digits + string.punctuation
# Generate a random password
password = "".join(random.choice(characters) for _ in range(password_length))
print(f"Your generated password is: {password}")
This simple program ensures strong and secure passwords with a mix of letters, numbers, and symbols.
Daily Reflections
What I Learned: I gained confidence in using loops and conditions to build logic. The password generator project was enjoyable and gave me practical insights.
Challenges I Faced: Debugging a nested loop can be tricky, especially when tracking variables across iterations. Writing clear comments and using print statements helped a lot.
Plan to Move Forward: Tomorrow, I will explore functions and how to modularize my code for better organization.
Join Me!
I’d love to hear how you use loops and conditions in your projects! Drop your thoughts in the comments, and let’s learn from each other.
Until tomorrow, happy coding! 😊
Subscribe to my newsletter
Read articles from Ayushi singla directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
