Category: Coding

  • Number guessing 2

    This entry is part 2 of 2 in the series Number Guessing
    1
    Python
    import random
    
    def number_guessing_game():
        print("πŸŽ‰ Welcome to the Number Guessing Game!")
        print("I'm thinking of a number between 1 and 100...")
    
        # Generate a random number between 1 and 100
        secret_number = random.randint(1, 100)
        attempts = 0
    
        while True:
            try:
                guess = int(input("Enter your guess: "))
                attempts += 1
    
                if guess < 1 or guess > 100:
                    print("🚫 Please enter a number between 1 and 100.")
                    continue
    
                if guess < secret_number:
                    print("πŸ“‰ Too low! Try again.")
                elif guess > secret_number:
                    print("πŸ“ˆ Too high! Try again.")
                else:
                    print(f"βœ… Congratulations! You guessed it in {attempts} attempts.")
                    break
    
            except ValueError:
                print("⚠️ Please enter a valid number.")
  • Number guessing 1

    This entry is part 1 of 2 in the series Number Guessing
  • Importing packages into Python

    In Python, the import statement is used to bring in modules and their functionality so you can use them in your code. There are several variations of the import statement, each serving different purposes depending on what and how you want to import.

    1. Basic Import

    import math

    This imports the entire math module. You access its functions with the module name:

    math.sqrt(16)

    2. Import with Alias

    import numpy as np

    This imports the module and gives it a shorter alias (np), which is useful for long module names or common conventions.

    3. Import Specific Functions or Classes

    from math import sqrt, pi

    This imports only the specified items from the module. You can use them directly:

    sqrt(25)

    4. Import All (Not Recommended)

    from math import *

    This imports everything from the module into the current namespace. It’s discouraged because it can lead to name conflicts and makes code harder to read.

    5. Dynamic Import (Using __import__)

    module_name = “math”

    math_module = __import__(module_name)

    This is useful when the module name is determined at runtime.

    6. Import from a Package

    If you have a package with submodules:

    from mypackage import submodule

    Or even deeper:

    from mypackage.submodule import myfunction

    7. Relative Imports (Used in Packages)

    from . import sibling_module

    from ..parent_package import parent_module

    These are used within packages to refer to other modules relative to the current module’s location.