Python coding practice

1. Random Password Generator: Generates secure passwords using letters, numbers, and symbols.
Skills: randomness, strings.

2. To-Do List (Console App): Add, remove, and list tasks — stored in a text file.
Skills: file handling, loops.

3. Number Guessing Game: The computer picks a number and you try to guess it with hints.
Skills: conditionals, loops.

4. Basic Calculator: Add, subtract, multiply, divide with user input.
Skills: functions, input validation.

5. Simple Contact Book: Store names, phone numbers, and emails in a file.
Skills: dictionaries, file I/O.

6. Weather Checker (Using API) : Fetches real-time weather for a city using an online API.
Skills: requests, APIs, JSON.

7. Rock–Paper–Scissors Game: Play against the computer.
Skills: randomness, game logic.

8. Stopwatch / Timer : Start, pause, and stop a timer.
Skills: time module, simple UI (optional).

9. Alarm Clock: Set a time, and Python plays a sound or prints a message.
Skills: datetime, scheduling.

10. Word Counter : Ask for a sentence and count words, characters, or frequencies.
Skills: strings, lists, dictionaries.

1. Random Password Generator

Here is min code

import random
import string
def strong_password_generator(password_length = 10):
    random_string = ''.join(random.choices(string.ascii_letters + string.digits + string.punctuation, k=password_length))
    print("Random string : ", random_string)
    
def main():
    to_continue = True
    while to_continue:
        try:
            user_input = input("Enter the minimum password length: ")
            min_length = int(user_input)
            if min_length < 10:
                print("Please enter a minimum of 10 characters for the random password generator.")
                continue  # Skip the rest of the loop n start over

            # Call your password generator function here
            strong_password_generator(min_length)

            is_exit = input("Do you want to continue? Enter 'y' or 'yes': ")
            if is_exit != 'y' and is_exit != 'yes':
                to_continue = False
        except ValueError:
            print("Please enter a valid number.")


if __name__ == "__main__":
    main()

    

Here, I learned about the random and string modules.

  • The string module provides constants like:
    • string.ascii_letters: Contains all lowercase and uppercase letters ('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').
    • string.digits: Contains all digits ('0123456789').
    • string.punctuation: Contains all punctuation characters (!'#$%&'()*+,-./:;<=>?@[\]^_{|}~`).

I also learned about:

  • random.choices(): A function that returns a list of randomly selected elements from a sequence (e.g., random.choices('abc', k=2) returns ['a', 'b']). where k is number of character output by defualt 1.
  • random.randint(a, b): A function that returns a random integer between a and b (inclusive).

Examples:

  • print(random.choice('sdfgfhf')) generates one random character from the string (e.g., 'f').
  • print(random.randint(1, 9)) generates a random integer between 1 and 9 (e.g., 5).

Technical Notes:

  1. string.ascii_letters, string.digits, and string.punctuation are constants, not methods.
  2. random.choice() (singular) selects one random element from a sequence, while random.choices() (plural) selects multiple elements (with replacement).

What random.choice() and secrets.choice() do

Both of them:

👉 Take a sequence (like a string, list, or tuple)
👉 Return exactly ONE random element from that sequence

if the sequence is a string like "ABCDE" — the function will return 1 random character.

secrets.choice(string.ascii_uppercase) #return one uppercase char
secrets.choice(string.digits) #0 to 9

Chatgpt suggestion – Improvements You Can Make

1. Avoid printing inside functions

  • Functions should return values instead of printing.
  • Printing inside a function reduces reusability.

2. Ensure at least one letter, digit, and symbol :
Your generator can accidentally generate a password with no digits or no punctuation, etc. Better to guarantee:

  • at least 1 uppercase
  • at least 1 lowercase
  • at least 1 digit
  • at least 1 symbol

3. Use secrets instead of random

For passwords, Python recommends:

import secrets

because it’s cryptographically secure.

4. Use .lower() for user input

So "Yes", "YES", "y" all work.

import secrets
import string

def strong_password_generator(length=10):
    # Character sets
    uppercase = string.ascii_uppercase
    lowercase = string.ascii_lowercase
    digits = string.digits
    symbols = string.punctuation

    # Ensure at least one of each
    password = [
        secrets.choice(uppercase),
        secrets.choice(lowercase),
        secrets.choice(digits),
        secrets.choice(symbols),
    ]

    # Fill the rest
    all_chars = uppercase + lowercase + digits + symbols
    password += [secrets.choice(all_chars) for _ in range(length - 4)]

    # Shuffle to avoid predictable patterns
    secrets.SystemRandom().shuffle(password)

    # Return final password string
    return "".join(password)


def main():
    while True:
        try:
            min_length = int(input("Enter the password length (min 10): "))

            if min_length < 10:
                print("Password must be at least 10 characters.")
                continue

            password = strong_password_generator(min_length)
            print("Generated Password:", password)

            user_choice = input("Generate another? (yes/no): ").lower()
            if user_choice not in ("y", "yes"):
                print("Goodbye!")
                break

        except ValueError:
            print("Please enter a valid number.")


if __name__ == "__main__":
    main()

Note : password += [secrets.choice(all_chars) for _ in range(length – 4)] once we reach this stage we already had 4 character in password and, if length is 10, then we still need 6 more character to generate from all_chars and that we are doing 4 loops via for _ in range(length – 4)

Scroll to Top