python笔记(三)

例一:

x=''
while
x!='q':
    print 'ok'
    
x=raw_input("please input something,q forquit:")
    if not x:
        break

结果:please input something,q forquit:a

ok

please input something,q forquit:b

ok

please input something,q forquit:

 

Process finished with exit code 0

例二:

x=''
while
x!='q':
    print 'ok'
    
x=raw_input("please input something,q forquit:")
    if not x:
        break
    if
x=='c':
        continue
    print 'one more time'
else
:
    print 'end'

结果:

ok

please input something,q forquit:a

one more time

ok

please input something,q forquit:c

ok

please input something,q forquit:q

one more time

End

例三:

a=100
def fun():
    if False:
        print 'good'
    print
a          #这是一个自定义的函数
if fun():
    print 'ok'

结果:100   为什么不显示OK   下面会讲解。

 

例四:

a=100
def fun(x): #定义函数时,括号里面的是形参。传递的是实参
    
print 'i get a :',x

s=raw_input('input something:')
fun()

错误:Traceback (most recent call last):

  File "D:/Python/Python ����/test.py", line 8, in

    fun()

TypeError: fun() takes exactly 1 argument (0 given)

原因:没有给fun()函数一个值。改为funs)就正确了

例五:

a=100
def fun(x,y ): #定义函数时,括号里面的是形参。传递的是实参
    
if x==y:
        print x,'=',y
    else:
        print x,'!=',y

#s1=raw_input('input something:')
#s2=raw_input('input something:')
#fun(s1,s2 )

def machine(y,x=10):
    print '有一个',x,'',y,''
machine('')  #不传值使用默认


global 强制声明为全局变量

函数必须被申明才会有意义。没有调用的话不显示。

例六:x='i am a goog male'
def
fun(): #定义函数时,括号里面的是形参。传递的是实参
    
global y
    y=200

    global x
    x=100
fun()
print y
print x

Fun()print x的先后位置不一样,得到的结果也不相同。

Fun()在前时:x=100.   Print在前时   得到:x='i am a goog male'

 

返回值:

def f(x,y):
   if x>y:
       return 1
   if x        return 0
   return -1
a=f(2,1)
print a

结果为:1

例七:

def f(x):
    print x
f('hello')
f([1,2,3])
l=range(10)
f(l)

结果:hello

[1, 2, 3]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

例八:t=('name','sex')
def f(x,y):
    print '%s : %s' % (x,y)

f(*t)

结果:name sex

例九:

d={'age':30,'name':'male'}
def f(name='name',age=20):
    print 'name:%s' % name
    print 'age %s' % age
f(**d)

处理多余实参:

def f(x,*args):
    print x
    print args
f(1,2,3,4,5)

结果:

1

(2, 3, 4, 5)

 

例十:

def f(x,*args,**b):
    print x
    print args
    print b
f(1,2,3,4,12,y=20)

结果:1

(2, 3, 4, 12)

{'y': 20}

你可能感兴趣的:(python)