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

时间:2020-08-03 09:12:11

标签: python function parameters return-value

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

我试图将变量'specificitem'调用到函数AddItem()

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中的变量来编辑数量,例如,当用户输入一个值时,它将其添加到文件购物车中,如果您要从文件库存中“减去”,则无法使用global由于我只会被记下来。我已经坚持了两天了

1 个答案:

答案 0 :(得分:-1)

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