我對編碼相當陌生,目前正在使用「Learn Python the Hard Way」一書學習我的第一語言(python),但這不是書中的特定練習,而我正在練習閱讀代碼練習23,我目前我只是想弄清楚,如果這甚至有可能...如何從導入的文件中的raw_input導入已定義的變量?
我的第一個文件是pr1.py:
def func():
a = float(raw_input("Enter Your Age:"))
b = float(raw_input("Enter Your Weight:"))
c = float(raw_input("Enter Your Height:"))
age = "a"
weight = "b"
height = "c"
if __name__ == "__main__":
print("This is pr1.py")
else:
print("%s is being imported to another file") % __name__
我的第二個文件是pr2.py
import pr1
def func():
x = raw_input("Enter Your Race:")
y = raw_input("Enter Your Gender:")
z = raw_input("Enter Your Language:")
print "Lets find your numbers"
pr1.func()
print "Lets find your identity"
func()
race = "x"
gender = "y"
language = "z"
if __name__ == "__main__":
print("This is pr2.py")
else:
print("%s is being imported into another file") % __name__
這是我的第三文件pr3.py
import pr1
print "%s = a %s = b %s = c" % (age, weight, height)
import pr2
print "%s = x, %s = y, %s = z" % (race, gender, language)
當我運行pr3.py並註釋掉腳本來「打印」 3號線和7號線這是我得到:
python pr3.py
pr1 is being imported to another file
Lets find your numbers
Enter Your Age:25
Enter Your Weight:224
Enter Your Height:76
Lets find your identity
Enter Your Race:white
Enter Your Gender:male
Enter Your Language:english
pr2 is being imported into another file
我期待pr3.py文件用先前定義的變量來打印這些語句。
,而是談到了這個錯誤:
pr1 is being imported to another file
Traceback (most recent call last):
File "pr3.py", line 3, in <module>
print "%s = a %s = b %s = c" % (age, weight, height)
NameError: name 'age' is not defined
現在,當我的命令來運行我的最後一個文件,我期待它導入之前的2個文件,這樣我就可以輸入數據,我把到raw_input中,然後在其他文件中使用它......但是好像一旦兩個文件都被導入並且我將數據輸入到它們各自的raw_input中,看起來好像pr3.py忘記了原始輸入和它們相應的變量。
請原諒我,如果我完全缺乏可以解決所有這些問題的明顯知識,但是我對編碼非常陌生,甚至在一個月前,我甚至都不知道您可以在終端中創建一個目錄。
感謝您的閱讀,我將不勝感激任何幫助。
感謝您抽出寶貴深入解釋的時間,真的幫助了很多! – Niles
@Niles你很好。 – EL3PHANTEN