2014-08-29 33 views
-1

我一直在研究元素字典,並且遇到了通過輸入運行外部函數的問題。我需要接受一個輸入並用它來調用具有多個變量的函數。這裏是我的代碼:Python中的外部函數3.4

import atoms 
import time 
print("Hello, and welcome to the element dictionary. This app takes an element symbol") 
print(" and outputs a small amount of data about the element.") 
element=input("please input an elements symbol :") 
(element) 
print('catagory: ',cat) 
print(' atomic number: ',atomn) 
print(' atomic weight: ',atomw) 
print('colour: ',colour) 
print(' phase: ',phase) 
print(' melting point: ',meltpoint) 
print('boiling point: ',boilpoint) 
print('crystal structure: ',cstruc) 
time.sleep(100) 

(element)是其中需要一個外部的功能,和「原子」是其中函數被存儲。

+1

你是什麼意思的「外部功能」? – abarnert 2014-08-29 20:38:52

+0

請提供您的完整代碼。 – 2014-08-29 20:38:58

+0

你只是問如何使用你導入的模塊的名字?如果你輸入os',你可以調用'os.listdir()'。那是你在找什麼? – abarnert 2014-08-29 20:39:23

回答

0

我需要的功能,用戶

我真的不知道,如果這就是你要找的輸入。但是你必須知道Python有所謂的First-class function。也就是說,你可以將一個函數存儲在一個像任何其他值一樣的變量中。在一個可變的字典或字典中。

要與思想熟悉,需要一些時間與這個例子實驗:

def f(): 
    print("This is f") 

def g(): 
    print("This is g") 

def other(): 
    print("Other choice") 

actions = { 
    "f": f, 
    "F": f, 
    "g": g, 
    "G": g 
} 

your_choice=raw_input("Choose f or g: ") 
your_fct = actions.get(your_choice, other) 
#         ^^^^^ 
#        default value 

your_fct() 

當然,你也可以傳遞參數,同時呼籲your_fct就像任何其他的功能。