Python 脚本中全局声明的语法错误

问题描述 投票:0回答:1

我正在使用 Pandas 在 Python 中开发库存管理系统,分为两个文件:

Inventory_mng.py
Product0.py
Product0.py
包含
Product
类,
Inventory_mng.py
管理库存操作。但是,我遇到了与使用
SyntaxError
关键字相关的
global

以下是文件内容:

Inventory_mng.py:

import pandas as pd
from Product0 import Product
 
# Initialize the DataFrame for inventory
inventory_df = pd.DataFrame(columns=['product_id', 'name', 'price', 'quantity'])
 
def add_product():
    product_id = input("Enter product ID: ")
    if product_id.isdigit() and int(product_id) not in inventory_df['product_id'].values:
        name = input("Enter product name: ")
        price = input("Enter product price: ")
        quantity = input("Enter product quantity: ")
 
        try:
            product_id = int(product_id)
            price = float(price)
            quantity = int(quantity)
            new_product = pd.DataFrame({
                'product_id': [product_id],
                'name': [name],
                'price': [price],
                'quantity': [quantity]
            })
 
            global inventory_df
            inventory_df = pd.concat([inventory_df, new_product], ignore_index=True)
            print("Product added successfully.")
 
        except ValueError:
            print("Invalid input types. Please ensure price and quantity are correct.")
    else:
        print("Invalid product ID or already exists. Enter a unique numeric ID.")
 
def remove_product():
    product_id = input("Enter product ID to remove: ")
    if product_id.isdigit():
        product_id = int(product_id)
 
        global inventory_df
        if product_id in inventory_df['product_id'].values:
            inventory_df = inventory_df[inventory_df['product_id'] != product_id]
            print("Product removed successfully.")
        else:
            print("No product found with the specified ID.")
    else:
        print("Invalid product ID. Please enter a numeric ID.")
 
def update_product():
    product_id = input("Enter product ID to update: ")
    if product_id.isdigit():
        product_id = int(product_id)
 
        if product_id in inventory_df['product_id'].values:
            choice = input("Update (1) Quantity or (2) Price? Enter 1 or 2: ")
            if choice == '1':
                new_qty = input("Enter new quantity: ")
                if new_qty.isdigit():
                    inventory_df.loc[inventory_df['product_id'] == product_id, 'quantity'] = int(new_qty)
                    print("Quantity updated successfully.")
                else:
                    print("Invalid quantity. Please enter a numeric value.")
            elif choice == '2':
                new_price = input("Enter new price: ")
                try:
                    inventory_df.loc[inventory_df['product_id'] == product_id, 'price'] = float(new_price)
                    print("Price updated successfully.")
                except ValueError:
                    print("Invalid price. Please enter a numeric value.")
            else:
                print("Invalid choice. Please enter 1 or 2.")
        else:
            print("No product found with the specified ID.")
    else:
        print("Invalid product ID. Please enter a numeric ID.")
 
def display_inventory():
    if not inventory_df.empty:
        print(inventory_df)
    else:
        print("No products in inventory.")
 
def main():
    while True:
        print("\n1. Add Product")
        print("2. Remove Product")
        print("3. Update Product")
        print("4. Display Inventory")
        print("5. Exit")
        choice = input("Enter your choice: ")
 
        if choice == '1':
            add_product()
        elif choice == '2':
            remove_product()
        elif choice == '3':
            update_product()
        elif choice == '4':
            display_inventory()
        elif choice == '5':
            print("Exiting program.")
            break
        else:
            print("Invalid choice. Please select a valid option.")
 
if __name__ == "__main__":
    main()

产品0.py:

class Product:
    def __init__(self, product_id, name, price, quantity):
        self.product_id = product_id
        self.name = name
        self.price = price
        self.quantity = quantity
 
    def display_info(self):
        return f"Product ID: {self.product_id}, Name: {self.name}, Price: {self.price:.2f}, Quantity: {self.quantity}"

错误信息:

C:\Users\quest3\Desktop\venv\Scripts\python.exe C:\Users\quest3\Desktop\Inventory_mng.py
 

  File "C:\Users\quest3\Desktop\Inventory_mng.py", line 27
    global inventory_df
    ^^^^^^^^^^^^^^^^^^^
SyntaxError: name 'inventory_df' is used prior to global declaration
Process finished with exit code 1

我尝试了几种排列来修复

global inventory_df
声明,但无济于事。我该如何解决这个问题
SyntaxError

python class inventory-management
1个回答
0
投票

您可以按如下方式将

global inventory_df
移至顶部并重试吗?

    def add_product():
        product_id = input("Enter product ID: ")
        global inventory_df
        if product_id.isdigit() and int(product_id) not in inventory_df['product_id'].values:
            name = input("Enter product name: ")
            price = input("Enter product price: ")
            quantity = input("Enter product quantity: ")
     
            try:
                product_id = int(product_id)
                price = float(price)
                quantity = int(quantity)
                new_product = pd.DataFrame({
                    'product_id': [product_id],
                    'name': [name],
                    'price': [price],
                    'quantity': [quantity]
                })

                inventory_df = pd.concat([inventory_df, new_product], ignore_index=True)
                print("Product added successfully.")

© www.soinside.com 2019 - 2024. All rights reserved.