您的位置:首页 > 编程语言 > Python开发

Python学习笔记

2015-12-22 13:41 796 查看

代码示例

number =23
guess =int(raw_input('enter a integer:'))
if guess==number:
print 'congratulate ,you guessed it'#new block starts here
print 'but you do not win any prize'#new block ends here
elif guess<number:
print 'no it is a little higher than that'#new block starts here
#you can do whatever you want in a block
else:
print 'no,it is a little lower than that'
print 'done'
#this last statesment is always excuted after theif statesment is excuated


python和C代码区别

直接从代码上看,python代码比起C的代码少了大括号和每一行的分号。代码块使用缩进来表示的。

格式化输入

number =23
running=True
while running:
guess =int(raw_input('enter a integer:'))
if guess==number:
print 'congratulate ,you guessed it'#new block starts here
running=False #this causes the while loop to stop
elif guess>number:
print 'no it is a little higher than that'#new block starts here
#you can do whatever you want in a block
else:
print 'no,it is a little lower than that'
else:
print'the while loop is over'
print 'done'
#this last statesment is always excuted after theif statesment is excuated


在这个程序中缩进显得非常重要,要么全部使用空格缩进,要么全部使用TAB键进行缩进

同时在这个程序中还用到了while循环,这里和C有所不同,在while循环中使用了一个else子句。

for i in range(1,5):
print i
else:
print 'Thefor loop is over '


这个便是python的for循环,在C中用的是for(i=1;i<5;i++),在python这里用的就是 i inrange(1,5)更加的直接和简单了

while True:
s=raw_input('enter something:')
if s=='quit':
break
print 'length of the sring is',len(s)
print 'DONE'


break语句,这里跳出循环,在下一段代码中,break和continue的区别更加明显

while True:
s=raw_input('enter something:')
if s=='quit':
break
if len(s)<3:
continue
print'input is of sufficient length'
#do other kinds of processing here


下面是输出结果

enter something:hello world

input is of sufficient length

enter something:he

enter something:he

enter something:quit

Process finished with exit code 0

这里很明显了,continue是跳出本次循环,继续下一次循环,而break是结束循环

关于局部变量和全局变量

这个概念和C语言中的是相同的,这里不用代码验证其作用范围了。

在C语言中打印一个字符串多次,需要用到一个循环,而在我们的Python中,只需要使用print message*5就可以打印5次了

返回参数值,用的也是return

关键参数

如果函数中有许多参数,如果只需要指定其中的一部分,那你可以通过命名来为这些参数————指定参数值

def func(a,b=5,c=10):
print 'a is' ,a and 'b is' ,b,'and c is',c
func(3,7)
func(25,c=24)
func(c=50,a=100)
func(b=10,c=10)


output:

Traceback (most recent call last):

a is b is 7 and c is 10

a is b is 5 and c is 24

a is b is 5 and c is 50

File “C:/Users/Jack_Fu/PycharmProjects/untitled/keyvalue.py”, line 6, in

func(b=10,c=10)

TypeError: func() takes at least 1 argument (2 given)

Process finished with exit code 1

这里有需要执行四次,但是只是执行了三次,最后一次由于没有指定a参数,所以在后面报错了

所以这里需要注意一下,没有指定的函数参数,一定要在调用函数的时候指定参数,否则会报错
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python it