#列表重写
[root@ftp day01]# vi 5.py
1 #!/usr/bin/env python
2 print [i for i in range(1,11)]
3
4 print '*'*30
5 print [i*2 for i in range(1,11)]
6
7 print '*'*30
8 print [i for i in range(1,11) if i%2==0]
9 print '*'*30
10 for i in [i**2 for i in range(1,11) if i%2 !=0]:
11 print i,
执行结果如下:
[root@ftp day01]# python 5.py
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
******************************
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
******************************
[2, 4, 6, 8, 10]
******************************
1 9 25 49 81
#xrange测试的是一个对象,遍历时才把值放进内存里面,建议以后所有xrange,以下是求
#1+2+3+....+100的和
[root@ftp day01]# vi 6.py
1 #!/usr/bin/env python
2 sum=0
3 for i in range(1,101):
4 sum += i
5 print sum
6
7 print '#'*20
8 sum = 0
9 for k in xrange(1,101):
10 sum += k
11 print sum
执行结果如下:
[root@ftp day01]# python 6.py
5050
####################
5050
#打印乘法口诀表
[root@ftp day01]# vi 7.py
1 #!/urs/bin/env python
2 for i in xrange(1,10):
3 for j in xrange(1,i+1):
4 print "%sx%s=%s" %(j,i,j*i),
5 print
执行结果如下:
[root@ftp day01]# python 7.py
1x1=1
1x2=2 2x2=4
1x3=3 2x3=6 3x3=9
1x4=4 2x4=8 3x4=12 4x4=16
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81
#continue , break中断语句的使用 ,用pass占位
root@ftp day01]# vi 8.py
1 #!/usr/bin/env python
2 import time
3 for i in xrange(10):
4 if i==3:
5 continue
6 elif i==5:
7 break
8 elif i==6:
9 pass
10 print i
11 else:
12 print "main end"
[root@ftp day01]# vi 8.1.py
1 #!/usr/bin/env python
2 import time
3 import sys
4 for i in xrange(10):
5 time.sleep(1)
6 if i==3:
7 continue
8 elif i==6:
9 pass
10 elif i==8:
11 sys.exit()
12 print i
13 else:
14 print "main end"
执行结果如下:
[root@ftp day01]# python 8.1.py
0
1
2
4
5
6
7
#用户登录
[root@ftp day02]# vi login.py
1 #!/usr/bin/env python
2
3 import getpass
4
5 username = raw_input("username: ")
6 password = getpass.getpass("password: ")
7
8 if username == "bob" and password =="123456":
9 print "Login successful!"
10 else:
11 print "Login incorrect!"
执行结果如下:
[root@ftp day02]# python login.py
username: bob
password:
Login successful!
#成绩查询
[root@ftp day02]# vi grade.py
1 #!/usr/bin/env python
2 # coding: utf-8
3 number = int(raw_input("please input 0-100: "))
4 if number >= 90:
5 print "优秀"
6 elif number >= 80:
7 print "好"
8 elif number >= 70:
9 print "良"
10 elif number >= 60:
11 print "及格"
12 else:
13 print "你要努力了!"
执行结果如下:
[root@ftp day02]# python grade.py
please input 0-100: 90
优秀
[root@ftp day02]# python grade.py
please input 0-100: 50
你要努力了!
[root@ftp day02]# python grade.py
please input 0-100: 70
良
阅读(1589) | 评论(0) | 转发(0) |