函数的调用def

目录

  • 背景
  • 定义与调用

背景

之前一直没怎么自己写过函数,后来程序太大了,不用函数分块的话,显得比较乱
问题来了,之前一直停留在理解的层次,只是能够看懂别人写的函数代码,自己亲自动手一写就抓瞎了
昨天晚上反复检查了半天,也没发现问题所在,今天经过师兄的指点,恍然大悟
这个故事告诉我们要是要多多交流,不懂就问,很多时候自己琢磨半天也弄不明白,可能别人指点一下就清楚了。
talk is cheap,show me code

Error : all_opentimes is not defined

定义与调用

#基本的函数框架
def function_1():
	return a
def function_2():
	return b
def function_3():
	return c
if __name__ == '__main__':
	function_1()
	function_2()
	function_3()

上述代码是基本的函数框架,
if name == ‘main’: #这个后面是调用函数的代码行,是主干,依次运行function_1,function_2,function_3
这是一种运行方式

但是我昨天写的代码有点不一样,我的function_2中用到了function_1中的处理结果。但我还是按上述代码写的,自然就运行不了。
需要这样修改

#基本的函数框架
def function_1():
	return a
def function_2():
	a = function_1()
	return b
def function_3():
	return c
if __name__ == '__main__':
	function_1()
	function_2()
	function_3()

需要在function_2中调用function_1,并且需要创建一个变量来储存这个调用值

当然函数还有形参实参的概念,形参就是def function_1() 括号里面的参数,实参是主干中 调用代码行括号里面的参数,比如

#基本的函数框架
def function_1(形参1):
	a = 形参1
	return a
def function_2():
	a = function_1(形参2)
	return b
def function_3(形参3):
	return c
if __name__ == '__main__':
	function_1(实参1)
	function_2(实参2)
	function_3(实参3)

实参是输入的参数,方便我后续随意更改输入参数
形参就是参与这个函数运算的参数,作为一个接口,当没有输入参数时,形参和实参都可以空着

昨日代码

# -*- coding: utf-8 -*-  
import numpy as np
import pandas as pd
import os
from datetime import datetime
import matplotlib.pyplot as plt
import re
import time


def readfile(months,last_days):
	#months = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
	#last_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
	t_start = time.clock()  #起始时间,用于监测代码的运行时间
	# months = ['06']
	# last_days = [30]
	for month,last_day in zip(months,last_days):
		path = 'C:\\Users\\hao\\Desktop\\time开窗模型\\源数据\\48NNJZ03_M_2017-{}.xlsx'.format(month) #
		b_1 = pd.ExcelFile(path)
		Sheet_names = b_1.sheet_names
		place_number = 0 #有开窗记录的地点数目
		all_opentimes = [] #所有的开窗时刻记录 
		all_openstates = [] #所有的开窗状态记录
		for Sheet_name in Sheet_names:
			#if (not re.search('卧', Sheet_name) == None) and (not re.search('窗', Sheet_name) == None) and (re.search('阳台', Sheet_name) == None) and (re.search('客厅', Sheet_name) == None) and (re.search('厨房', Sheet_name) == None):			
			if (not re.search('卧', Sheet_name) == None) and (not re.search('窗', Sheet_name) == None) and (re.search('阳台', Sheet_name) == None) and (re.search('厨房', Sheet_name) == None):
				place_number += 1
				print('有开窗记录的sheet数量:%d次'%place_number)
				df = pd.read_excel(path, sheet_name=Sheet_name)
				temp_columns = ['采集时间', '状态']
				df = df[temp_columns].dropna()
				#all_openstates = df['状态'].tolist()
				all_openstates = np.array(df['状态'])
				#print(df)
				for i in range(len(df['采集时间'])):
					q_1 = str(df.iloc[i, 0])[:10]
					q_1 = q_1.split('-')
					#print(q_1)
					q_2 = str(df.iloc[i, 0])[11:]
					q_2 = q_2.split(':')
					#print(q_2)
					q_3 = q_1[0] + q_1[1] + q_1[2] + q_2[0] + q_2[1] + q_2[2]
					#print(q_3)
					all_opentimes.append(q_3)
					#print(all_opentimes)
			print('all_opentimes:%d长度'%len(all_opentimes))
			#return all_opentimes
			#return all_openstates

		#提取天气栏里面的信息
		weather_times,weather_temps = [],[]  #天气栏中的时刻和温度
		df = pd.read_excel(path, sheet_name='天气')
		temp_columns = ['采集时间', '温度(℃)']
		df = df[temp_columns].dropna()
		#weather_temps = df['温度(℃)'].tolist()
		weather_temps = np.array(df['温度(℃)'])
		for i in range(len(df['采集时间'])):
			q_1 = str(df.iloc[i, 0])[:10]
			q_1 = q_1.split('-')
			#print(q_1)
			q_2 = str(df.iloc[i, 0])[11:]
			q_2 = q_2.split(':')
			#print(q_2)
			q_3 = q_1[0] + q_1[1] + q_1[2] + q_2[0] + q_2[1] + q_2[2]
			#print(q_3)	
			weather_times.append(q_3)
		print('weather_times长度%d'%len(weather_times))	
		#return weather_times,weather_temps			
	t_end = time.clock()
	run_time = t_end - t_start
	print('{}函数耗时:%ds'.format('readfile')%run_time)
	#print(all_opentimes)
	return all_opentimes, all_openstates, weather_times, weather_temps 
	#return all_openstates

def dealwithfile():
	t_start = time.clock()
	all_opentimes, all_openstates, weather_times, weather_temps = readfile(months,last_days)
	#(all_opentimes) = read()
	new_temps, new_humidity = [], [] 
	for all_opentime in all_opentimes:
		break_number = 0
		for weather_time in weather_times:
			if (all_opentime <= weather_time) and (break_number == 0):
				new_temps.append(weather_temps[weather_times.index(weather_time)])
				break_number += 1
	print('new_temps长度%d'%len(new_temps))
	if len(all_opentimes) == len(new_temps) + 1: #防止出现最后一次开窗时间比最后一次温度数据时间更晚
		new_temps.append(weather_temps[-1])
	t_end = time.clock()
	run_time = t_end - t_start
	print('{}函数耗时:'.format('find'), run_time)
	return new_temps, new_humidity

def savefile():
	all_opentimes, all_openstates, weather_times, weather_temps = readfile(months,last_days)
	new_temps, new_humidity = dealwithfile()
	df = pd.DataFrame([all_opentimes, new_temps])
	#df = pd.concat
	df.to_excel(r'C:\Users\hao\Desktop\test.xlsx', index=False)


if __name__ == '__main__':
	months = ['06']
	last_days = [30]	
	# readfile(months, last_days)
	# dealwithfile()
	savefile()

你可能感兴趣的:(报错,基础知识)