在Python 2.7中,我的函數pop(y,p)
的代碼可以很好地工作,但函數aveChange(p,y)
返回多條打印的線條,我只需要打印1行來說明每年人口變化的平均值。Python 2.7使用列表運行函數的問題
,功能change(p,y,b)
只是說:
NameError: name 'b' is not defined
到目前爲止我的代碼如下:
def biggerThan():
l=raw_input('Enter a list of numbers, separate each number with a comma:').split(',')
a=map(int,l)
n=int(raw_input('Enter another number:'))
a2=[i for i in a if i>n]
print a2
p = [151868, 153982, 156393, 158956, 161884, 165069, 168088,
171187, 174149, 177135, 179979, 182992, 185771, 188483,
191141, 193526, 195576, 197457, 199399, 201385, 203984,
206827, 209284, 211357, 213342, 215465, 217563, 219760,
222095, 224567, 227225, 229466, 231664, 233792, 235825,
237924, 240133, 242289, 244499, 246819, 249623]
y1=1950
y2=1991
y=range(y1,y2)
def pop(y,p):
fmt='{:<8}{:<20}{}'
print(fmt.format('', 'Year', 'Population'))
for i, (year, pop) in enumerate(zip(y, p)):
print(fmt.format(i, year, pop))
def aveChange(p,y):
p = [151868, 153982, 156393, 158956, 161884, 165069, 168088,
171187, 174149, 177135, 179979, 182992, 185771, 188483,
191141, 193526, 195576, 197457, 199399, 201385, 203984,
206827, 209284, 211357, 213342, 215465, 217563, 219760,
222095, 224567, 227225, 229466, 231664, 233792, 235825,
237924, 240133, 242289, 244499, 246819, 249623]
y1=1950
y2=1991
y=range(y1,y2)
yearly_change = []
change=0.0
total_change=0
average_change=0
for i in range(len(p)):
p[i] = float(p[i])
#calculate the change in population size for each two years
for i in xrange(1,len(p)):
change = p[i] - p[i-1]
yearly_change.append(change)
total_change = float(sum(yearly_change))
average_change = total_change/40
print "The average annual change in population during the time period is",average_change
def change(p,y,b):
p = [151868, 153982, 156393, 158956, 161884, 165069, 168088,
171187, 174149, 177135, 179979, 182992, 185771, 188483,
191141, 193526, 195576, 197457, 199399, 201385, 203984,
206827, 209284, 211357, 213342, 215465, 217563, 219760,
222095, 224567, 227225, 229466, 231664, 233792, 235825,
237924, 240133, 242289, 244499, 246819, 249623]
y1=1950
y2=1991
y=range(y1,y2)
yearly_change = []
newchange=0.0
greatest_increase=0
smallest_increase=0
greatest_year=0
smallest_year=0
BASE_YEAR=1950
for i in range(1,len(p)):
newchange = p[b] - p[b-1]
yearly_change.append(newchange)
if b==1:
greatest_increase = newchange
smallest_increase = newchange
greatest_year = 1
smallest_year = 1
else:
if newchange>greatest_increase:
greatest_increase = newchange
greatest_year = b
elif newchange<smallest_increase:
smallest_increase = newchange
smallest_year = b
print("The year with the greatest increase in population was",
BASE_YEAR+greatest_year)
print("The year with the smallest increase in population was",
BASE_YEAR+smallest_year)
在您的文章中是否也有代碼中的行被中斷? – kpie
執行此操作確實不會爲我引發任何'NameError'。 –
也許你需要符合小隻縮進'print' – furas