Python脚本global声明引发SyntaxError的解决方法咨询
解决Pandas库存管理系统中的global关键字语法错误
问题背景
我使用Pandas开发Python库存管理系统,项目分为Inventory_mng.py和Product0.py两个文件:
Product0.py包含Product类,定义产品属性和展示方法Inventory_mng.py负责库存的增删改查操作
运行时触发SyntaxError,错误提示:name 'inventory_df' is used prior to global declaration
相关代码
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()
Product0.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
解决方案
错误原因
Python语法规定:函数内的global声明必须放在该变量第一次被使用之前。在add_product函数中,你先在if判断语句里使用了inventory_df,之后才用global声明它,这直接触发了语法错误。
修复方法
将global inventory_df声明移到每个需要修改全局inventory_df变量的函数的最顶部,确保它在任何使用该变量的代码之前执行:
修复后的add_product函数
def add_product(): global inventory_df # 移到函数最开头 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] }) 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.")
修复后的remove_product函数
def remove_product(): global inventory_df # 移到函数最开头 product_id = input("Enter product ID to remove: ") if product_id.isdigit(): product_id = int(product_id) 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.")
额外优化建议
全局变量在大型项目中容易引发耦合问题,建议采用以下替代方案:
- 将
inventory_df作为参数传递给各个操作函数 - 封装成Inventory类,把库存数据和操作方法整合在一起,更符合面向对象设计规范
内容的提问来源于stack exchange,提问作者ANKIT NAIR
相关产品推荐
相关产品推荐

