2012-12-29 82 views
1

我有一个名称列表,例如,木工,工程总共15个。 在下面的代码片段中,我将其称为name1,但是对变量名称没有序列。 而不是写这个代码15次,我怎么可以创建一个函数,每次更改名称时执行相同的条件。使用不同变量创建函数

name1= int(raw_input("Please enter your value for name1: ")) 
if name1 <5: 
status = "nill" 
total = 0 
if name1 >4 and name1 <8: 
status = "valid" 
total=1 
if name1 >7 and name1 <12: 
status = "superb" 
total=5 
if name1 >11: 
status = "over qualified" 
total=10 
print "this is your current status ",status 
print "this equals ",total 
+0

每次不要更改名称。改用字典或列表。 –

+0

@miguel请为您的代码使用正确的格式(缩进)。它是Python,缩进很重要。 – informatik01

回答

1

我相信这是做你正在寻找的。请注意,这可能不是你想要存储的个人状态(一defaultdict可能会更有意义)的方式,但希望这是有道理的,从概念的角度来看:

def comparisons(value): 
    """Only change here is using x <= y < z syntax.""" 
    if value < 5: 
     status = 'nill' 
     total = 0 
    elif 5 <= value < 8: 
     status = 'valid' 
     total = 1 
    elif 8 <= value < 12: 
     status = 'superb' 
     total = 5 
    else: 
     status = 'over-qualified' 
     total = 10 
    # Here we return the status and the total for each item 
    # This may not be what you want, so this can be adjusted 
    return status, total 


# Create a list that will contain your 15 items 
items = ['Engineering', 'Carpentry'] 

# Create a container to hold the results. 
# Note that we don't use different variables names each time - 
# instead, we create an entry in a dictionary corresponding to 
# our 'items' values. 
results = {} 

# Now we iterate through each item in our items list, running 
# our function and storing the results. Note that this is a guess 
# as to how you want to handle 'status' - a more useful solution 
# could be to use a nested dictionary where each item has a dictionary 
# with two sub-fields: 'status' and 'total'. 
for item in items: 
    status, total = comparisons(int(raw_input('{0}: '.format(item)))) 
    results[item] = [status, total] 

# Print out each item 
print '\nIndividual items:' 
for item, values in results.iteritems(): 
    print item, values 

# Example of how you could sum the totals 
print '\nTotal score:' 
print sum((results[x][1] for x in results)) 

输出:

Engineering: 10 
Carpentry: 5 

Individual items: 
Engineering ['superb', 5] 
Carpentry ['valid', 1] 

Total scores: 
6