函数定义
#函数 def hello(): print('123') print('456') hello() hello()
变元参数应用
def he(name): #name is 变元 ,返回后数据丢失 print('hello '+ name) he('alice') #print(name) last number is can not be remembered he('lindar') end : hello alice hello lindar
函数调用
import random def getn(an) : if an==1: return 1 elif an==2: return 2 elif an==3 : return 3 elif an==4: return 4 elif an==5 : return 5 elif an==6 : return 6 r=random.randint(1,6) #产生随机数 f=getn(r) print(f) print(random.randint(1,6))
#多行连接
print('li') print('nk') #多行连接 print('lin',end='') #关键语句 print('dar') ''' li nk lindar '''
# 同行显示
print(1,2,3) print('he','ll','o') #字符串专用'' print('he','ll','o',sep=',') ''' 1 2 3 he ll o he,ll,o '''
局部变量与全局变量
# print(eggs) #can not run ,局部变量不能被全局调用
#同名的局部变量在不同的函数中定义了,其值与其他函数中值隔离def sp(): eggs=12 new() print(eggs) def new(): eggs=16 sp() #end is 12 # print(eggs) #can not run ,局部变量不能被全局调用 #同名的局部变量在不同的函数中定义了,其值与其他函数中值隔离 '''
#名称相同的变量,局部变量不被全局变量改变
def sp(): new() print(eggs) def new(): eggs=16 eggs=100 sp() #end is 100 #名称相同的变量,局部变量不被全局变量改变
global 语句,全局变量,不再创建局部变量
#global 变量 def sp(): global eggs eggs =15 eggs=3 eggs= 'global' sp() print(eggs) #end is15 '''
#异常处理:可由 try 和except语句处理,遇到错误可跳过到except继续执行
#异常处理:可由 try 和except语句处理 def sp(div): return 10/div try: print(sp(5)) print(sp(0)) print(sp(2)) except ZeroDivisionError: # 库函数自带 print('err0: div--------------0') print(666) ''' 2.0 err0: div--------------0 666 '''
猜数字游戏
import random sen=random.randint(1,20) print('guess a number') for guess_get in range(1,6): print("guess quickly") guess=int(input()) if guess<sen: print("lower!!!!!!!!") elif guess>sen: print('bigger!!!!!!!') else : break if guess==sen : print('good! you guess my n in '+str(guess_get)+' guess!!!') else : print('no! thinking is '+str(guess_get))
数字游戏
def col(x): if x%2==0 : print(x//2) return x else : print(3*x +1 ) try : v=int(input()) except ValueError: print('please reat input ,can not input a string') v=int(input()) col(v)