《Python编程快速上手》(三)函数

第三章   函数

3.1 def语句和参数

def hello():    #def语句,定义了一个名为hello()的函数
    print('Howdy!')          #函数体
    print('Howdy!!!')        #函数体
    print('Hello there!')    #函数体

hello()     #调用
hello()     #调用
hello()     #调用
  • 代码在函数调用时被执行,而不是在函数第一次定义时执行

  • 函数的一个目的就是将需要多次执行的代码放在一起,避免复制代码

def hello(name):    #name为hello()函数的参数
    print('Hello '+ name)

hello('Saber')
hello('Arther')

  • 保存在变元中的值,在函数返回后就被丢失了

3.2 返回值和 return 语句

  • 一般来说,函数调用求值的结果,称为函数的“返回值
  • return语句包括:①return关键字;②函数应该返回的值或表达式

3.3 None值

  • None是NoneType数据类型的唯一值
  • 相当于C语言函数返回值为void
  • 对于没有return语句的函数,Python会在末尾加上return None(类似 while或for循环隐式的以continue结尾),如果使用不带值的return语句也返回None

3.4 关键字参数和print()

【例】print()函数中的end,sep

print('Hello')
print('World')

  • print()函数自动在传入的字符串结尾添加了换行符
print('Hello',end='')
print('World')


3.5 局部和全局作用域

3.5.1 局部变量不能在全局作用域内使用

3.5.2 局部作用域不能使用其他局部作用域内的变量

3.5.3 全局变量可以在局部作用域中读取

3.5.4 名称相同的局部变量和全局变量


3.6 global语句


3.7 异常处理

  • try    except


3.8 一个小程序:猜数字

#猜数字
import random
digit=random.randint(1,20)
for i in range(1,7):
    print('input a num')
    num=int(input())
    if num==digit:
        break
    elif num>digit:
        print('too hight')
    elif num<digit:
        print('too low')

if num==digit:
    print('right!count='+str(i))
else:
    print('None'+'right answer is'+str(digit))

3.9 小结

3.10 习题


3.11 实践项目

3.11.1 Collate序列

3.11.2 输入验证

#Collatz序列
def clooatz(number):
    if number%2==0:
        print(str(number//2))
        return number//2
    else:
        print(str(3*number+1))
        return 3*number+1

try:
    number=int(input())
except ValueError:
    print('your input must be intger!')

while number!=1:
    number=clooatz(number)
    

猜你喜欢

转载自blog.csdn.net/qq_40818798/article/details/81627663
今日推荐