Importing functions from another python file and importing variables and inputs from that function.

+1 Denis Balaj · September 19, 2015
Hello dear,

Im trying to import functions from another python file, but is not working.
for example im trying to import all the variables and if in a function.


from registars import *
from regprod import *

menu = print("1.Type l to buy")
menu2 = print("2.Type r to register a product")

def barMain():
enterValue = input("3.Type a letter: ")
if enterValue == "l":
typeCode = input("Enter the barcode: ")
if enterValue == "r":

This file here is correct, not needed to change something,

def registerWay():
barCode = input("Enter barcode of product: ")
productAdd = input("Enter product name: ")
prodinstr = str(productAdd)
registerBars = open("", "a")
registerBars.write("if enter.barMain(typeCode) == " + "'" + barCode + "':" + "\n")
registerBars.write(" print('You bought: " + prodinstr + "'" + ")" + "\n")

and this one here doesnt work when i import functions ( when i want to import a variable and an input from function)

from loginbar import *
if typeCode == '778845':
print('You bought: peanut')

Always show error, and i tried and tried but i cant, im trying to import variables and inputs from a def function.


Post a Reply


Oldest  Newest  Rating
+1 sfolje 0 · September 20, 2015

  • It can be solved in many ways, for example with putting line

global typeCode

somewhere in your barMain() function.
Why it doesnt works is because typeCode is known only to peaple inside barMain function. It's privacy issue. With global typeCode line you make variable named typeCode public (or global), so anyone in the whole world can see it.

  • Second way of solving same problem can be done by returning value at the end of function:

def barMain():
  return typeCode

and instead of line
if typeCode == '778845':

if barMain() == '778845':
0 sfolje 0 · September 19, 2015
I think problem is in local and global variables.
If you call variable inside function, you will get error, because variables in fuction are allways local, except if you specifically declare them as global.
What error do you get?
0 Denis Balaj · September 20, 2015
Yeah, i think really is problem with the local and global variables, im getting this error:

    if typeCode == '778845':

NameError: name 'typeCode' is not defined

I think im gonna using init method.
0 Halcyon Abraham Ramirez · September 20, 2015
what is typeCode? a variable?
0 Denis Balaj · September 21, 2015
Great answer, thanks from you.
0 sfolje 0 · September 24, 2015
thanks for my first +1 !
  • 1



This section is all about snakes! Just kidding.

Bucky Roberts Administrator