Reputation: 47
I am new to python script. I was script two script one contains all the def module and in second script i am importing the first script
In Second script i have so many variable defined and these variable is also defined in first script. Could you please let me know how to use second script variable in first script without giving argument.
Here is the code:
script1.py:
import os
import re
def one():
print("First Name"+name+"\n")
print("Last Name "+last+"\n")
print("Occupation:"+job+"\n")
script2.py:
import os
import re
import script1
name = "Rob"
last = "Sussian"
occupation = "Unemployee"
print(script1.one())
Thanks in Advance
Upvotes: 0
Views: 380
Reputation: 31389
You are trying to solve a problem that all beginner programmers run into sooner rather than later. You'll find that global variables seem to be the solution, but you can save yourself a lot of unlearning of bad habits later by looking at function parameters right away:
script1.py:
def one(name, last, job):
print("First Name"+name+"\n")
print("Last Name "+last+"\n")
print("Occupation:"+job+"\n")
script2.py:
import script1
name = "Rob"
last = "Sussian"
occupation = "Unemployee"
print(script1.one(name, last, occupation))
Your function one()
has been given three parameters, which it will expect to be assigned arguments as the function is called, which is exactly what happens in script2.py
.
Note that I left the names unchanged, but the value of the variables name
etc. is passed in the call, so that fact that the global variable name
gets assigned to the parameter name
of the function one()
has nothing to do with the names. They could be named differently, and things would work as well - you can tell from job
and occupation
.
(Note that I changed the indentation on your function to be 4 instead of 3, which is standard for Python - a good habit as well)
(Another note, the print()
around the call to the function will only print the return value of None
- you don't need to print the result of a function that does the printing itself)
If you're trying to avoid passing arguments because you're operating on values that you will be reusing for other functions as well, consider using a class:
script1.py:
class Person:
def __init__(self, name, last, job):
self.name = name
self.last = last
self.job = job
def one(self):
print("First Name"+self.name+"\n")
print("Last Name "+self.last+"\n")
print("Occupation:"+self.job+"\n")
script2.py:
import script1
rob = Person('Rob', 'Sussian', 'Unemployee')
rob.one()
Upvotes: 2