杰瑞科技汇

Light switch Python如何实现智能控制?

Of course! Creating a "Light Switch" program is a fantastic exercise for beginners in Python. It teaches fundamental concepts like variables, conditional logic, and user input.

Light switch Python如何实现智能控制?-图1
(图片来源网络,侵删)

Let's start with a simple version and build up to a more robust and realistic one.

The Simple Version: A Basic On/Off Switch

This is the most straightforward approach. We'll have a variable to track the light's state and a loop to let the user control it.

Code

# --- A Simple Light Switch ---
# 1. Initialize the light's state
# We use a boolean variable: True means ON, False means OFF.
is_light_on = False
print("--- Simple Light Switch ---")
print(f"The light is currently {'ON' if is_light_on else 'OFF'}.")
# 2. Create a loop to keep the program running
while True:
    # 3. Get input from the user
    action = input("Press '1' to toggle the light, or 'q' to quit: ")
    # 4. Check the user's input and act
    if action == '1':
        # Use the 'not' operator to flip the boolean value
        is_light_on = not is_light_on
        print(f"Light is now {'ON' if is_light_on else 'OFF'}.")
    # 5. Allow the user to exit the program
    elif action.lower() == 'q':
        print("Exiting the light switch. Goodbye!")
        break
    # 6. Handle invalid input
    else:
        print("Invalid command. Please try again.")

How It Works

  1. is_light_on = False: We create a variable to hold the state of our light. A boolean (True or False) is perfect for this.
  2. while True:: This creates an infinite loop, so the program keeps running and asking for input until we specifically tell it to stop.
  3. input(...): This function pauses the program and waits for the user to type something and press Enter.
  4. if action == '1':: This checks if the user typed '1'. If they did, we execute the code inside this block.
  5. is_light_on = not is_light_on: This is the core logic. The not operator inverts the boolean value. If it's False, it becomes True. If it's True, it becomes False.
  6. elif action.lower() == 'q':: elif means "else if". This checks if the user typed 'q' (we use .lower() to accept 'q' or 'Q'). If so, we print a goodbye message and break out of the while loop, ending the program.
  7. else:: If the user types anything other than '1' or 'q', this block runs, printing an error message.

An Improved Version: Using a Class

For more complex programs, using classes is a great way to organize your code. A "Light" can be an object with its own properties (like state and brightness) and actions (like turning on or off).

Code

# --- An Improved Light Switch using a Class ---
class Light:
    """A class to represent a physical light switch."""
    def __init__(self, name="Living Room Light"):
        """Initializes the light with a name and sets it to OFF."""
        self.name = name
        self.is_on = False
        self.brightness = 0  # 0 is off, 100 is full brightness
    def turn_on(self):
        """Turns the light on."""
        self.is_on = True
        self.brightness = 100
        print(f"{self.name} is now ON at full brightness.")
    def turn_off(self):
        """Turns the light off."""
        self.is_on = False
        self.brightness = 0
        print(f"{self.name} is now OFF.")
    def toggle(self):
        """Toggles the light's state (ON to OFF, OFF to ON)."""
        if self.is_on:
            self.turn_off()
        else:
            self.turn_on()
    def set_brightness(self, level):
        """Sets the brightness if the light is on."""
        if 0 <= level <= 100:
            if self.is_on:
                self.brightness = level
                print(f"{self.name} brightness set to {level}%.")
            else:
                print(f"Cannot set brightness. {self.name} is OFF.")
        else:
            print("Brightness must be between 0 and 100.")
    def __str__(self):
        """Returns a user-friendly string representation of the light's state."""
        status = "ON" if self.is_on else "OFF"
        return f"{self.name}: {status} (Brightness: {self.brightness}%)"
# --- Main part of the program ---
if __name__ == "__main__":
    # Create an instance of our Light class
    my_light = Light("Kitchen Light")
    print("--- Improved Light Switch ---")
    print(my_light) # Uses the __str__ method
    while True:
        print("\nWhat would you like to do?")
        print("1. Toggle Light")
        print("2. Turn On")
        print("3. Turn Off")
        print("4. Set Brightness (1-100)")
        print("q. Quit")
        action = input("Enter your choice: ")
        if action == '1':
            my_light.toggle()
        elif action == '2':
            my_light.turn_on()
        elif action == '3':
            my_light.turn_off()
        elif action == '4':
            try:
                brightness_level = int(input("Enter brightness level (0-100): "))
                my_light.set_brightness(brightness_level)
            except ValueError:
                print("Invalid input. Please enter a number.")
        elif action.lower() == 'q':
            print("Exiting the light switch. Goodbye!")
            break
        else:
            print("Invalid command. Please try again.")
        # Show the current state after each action
        print("\nCurrent State:")
        print(my_light)

How It Works

  1. class Light:: This defines a new "blueprint" for creating Light objects.
  2. __init__(self, ...): This is the constructor. It runs automatically when you create a new Light object (e.g., my_light = Light(...)). It sets up the initial properties (self.name, self.is_on, self.brightness).
  3. Methods (turn_on, turn_off, etc.): These are functions that belong to the class. They define what a Light object can do. They use self to access and modify the object's own properties.
  4. __str__(self): This is a special "magic method." Python calls it automatically whenever you try to convert the object to a string (like when you use print(my_light)). This lets us define a nice, readable output.
  5. if __name__ == "__main__":: This is standard Python practice. The code inside this block only runs when the script is executed directly (not when it's imported as a module into another script).
  6. my_light = Light(...): This creates an instance of our Light class, which is a real, usable object.

An Advanced Version: Simulating Multiple Switches

This version simulates a more realistic scenario where one light can be controlled by multiple switches (like in a hallway). The light's state depends on the combined state of all its switches.

Light switch Python如何实现智能控制?-图2
(图片来源网络,侵删)

Logic

  • An "up" switch is True, a "down" switch is False.
  • If all switches are in the same position (True/True or False/False), the light is OFF.
  • If the switches are in different positions (True/False or False/True), the light is ON.

Code

# --- Advanced Light Switch with Multiple Switches ---
class AdvancedLight:
    """A light controlled by two 3-way switches."""
    def __init__(self, name="Hallway Light"):
        self.name = name
        self.switch1_up = False  # State of the first switch
        self.switch2_up = False  # State of the second switch
        self.is_on = False       # Derived state of the light
    def flip_switch(self, switch_num):
        """Flips the state of a specific switch and updates the light."""
        if switch_num == 1:
            self.switch1_up = not self.switch1_up
        elif switch_num == 2:
            self.switch2_up = not self.switch2_up
        # The light is ON if the switches are in different positions
        self.is_on = self.switch1_up != self.switch2_up
        # Print the action and the new state
        print(f"Switch {switch_num} was flipped.")
        self.print_status()
    def print_status(self):
        """Prints the detailed status of all switches and the light."""
        s1_pos = "UP" if self.switch1_up else "DOWN"
        s2_pos =
Light switch Python如何实现智能控制?-图3
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇