尝试将变量从一个函数调用到另一个函数

2024-06-20 15:15:30 发布

您现在位置:Python中文网/ 问答频道 /正文

def editselection():
  #this converts the text in the files into a list in a list
  with open("stocks", "r") as stocks:
    for line in stocks:
      stripped_line = line.strip()
      line_list = stripped_line.split()
      list_of_items.append(line_list)
    itemselection = input('Choice: ')
    if itemselection.isalpha() == True:
      ManageStock()
    elif itemselection == '':
      ManageStock()
  itemselection = int(itemselection)
  os.system('clear')
  #the square brackets are the indexes so for example if they select 0, the first item turned into a list would be known as specific item
  specificitem = list_of_items[itemselection]
  changeitem(specificitem)
  return specificitem

我正在尝试调用函数AddItem()的变量'specificitem'

def AddToCart(specificitem): 
  os.system('clear')
  number = 0
  os.system('clear')
  print ("""Here is the current stock 
--------------------------
Name, Price, Quantity
--------------------------
""")
  with open ('stocks', 'r') as stocks:
    for i in stocks:
      number = str(number)
      print (number+'.' , i)
      number = int(number)
      number = number + 1
  #this converts the text in the files into a list in a list
  with open("stocks", "r") as stocks:
    for line in stocks:
      stripped_line = line.strip()
      line_list = stripped_line.split()
      list_of_items.append(line_list)
    itemselection = input('Choice: ')
    if itemselection.isalpha() == True:
      AddToCart()
    if itemselection == '':
      MakeASale()
  itemselection = int(itemselection)
  #the square brackets are the indexes so for example if they select 0, the first item turned into a list would be known as specific item
  quantity = input('How many would you like? ')
  chosenitem2 = list_of_items[itemselection]
  with open ('cart' , 'a') as cart:
    chosenitem2 = str(chosenitem2)
    cart.write(chosenitem2 + '\n')
  with open("cart", "r") as cart:
    for line in cart:
      stripped_line = line.strip()
      line_list = stripped_line.split()
      list_of_cart.append(line_list)
    with open ("cart" , "r+") as cart:
      data = cart.read()
      data = data.replace(chosenitem2[2], quantity) 
      cart.close
      cart = open('cart' , 'wt')
      cart.write(data)
      cart.close()
    with open ("stocks" , "r+") as stocks:
      data = stocks.read()
      data = data.replace(specificitem[2], chosenitem2[2]) 
      stocks.close
      stocks = open('stocks' , 'wt')
      stocks.write(data)
      stocks.close()
    print(chosenitem2)

虽然它提供了AddToCart()缺少1个必需的位置参数:“specificitem”

我试图使用editselection中的变量来编辑数量,例如,当用户输入一个值时,它会将其添加到文件购物车中,如果要从文件库存中“减去”,则无法使用全局变量,因为我只会被标记。我已经被困在这两天了


1条回答
网友
1楼 · 发布于 2024-06-20 15:15:30

在第一个函数中写入(function name)editselection.(variable name)specificitem=(value)list_of_items[itemselection] 在第二个函数中调用变量,例如: print(editselection.specificitem) 这将打印变量的值。 这称为函数变量(或类似的东西)

相关问题 更多 >