Python 教程 - 第五部分
函数
- 定义函数
- 示例代码
#无返回值
def sayHelloTo(username):
print("Hello.%s" % username)
#有1个返回值
def getWelcomeMsg(username):
msg="Welcome to my tutorial,%s" % username
return msg
#有多个返回值
def calculateByFourOperations(n1,n2):
sum=n1+n2
sub=n1-n2
multi=n1*n2
div="Illegal divisor:0"
if n2!=0 :
div=n1/n2
return sum,sub,multi,div
username=input("Please input your name:")
sayHelloTo(username)
welcomeMsg=getWelcomeMsg(username)
print("Welcome msg=%s." % welcomeMsg)
n1Str=input("Please input operation number 1:")
n2Str=input("Please input operation number 2:")
n1=int(n1Str)
n2=int(n2Str)
sum,sub,multi,div=calculateByFourOperations(n1,n2)
print("sum=%d,sub=%d,multi=%d" %(sum,sub,multi))
print("div=",div)
- 练习题
- 题目
请定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程:ax2 + bx + c = 0的两个解。
提示:计算平方根可以调用math.sqrt()函数。
- 解答
import math
def calculateDiv(a,b):
result="Illegal divisor:0"
if b!=0 :
result=a/b
return result
def quadratic(a,b,c):
result=[]
if a==0 :
return calculateDiv(-c,b)
else :
delta=b*b-4*a*c
if delta<0 :
pass
elif delta==0:
solution1=-b/(2*a)
result=[solution1]
else:
solution1=(-b+math.sqrt(delta))/(2*a)
solution2=(-b-math.sqrt(delta))/(2*a)
result=[solution1,solution2]
return result
a=int(input("Please input a:"))
b=int(input("Please input b:"))
c=int(input("Please input c:"))
result=quadratic(a,b,c)
print("%d^2+%dx+%d=%s" % (a,b,c,result))
文件读写
- 写文件
f = open('testFileIO.txt', 'w')
f.write("This is the content\n")
f.close()