1. python中的几种分支结构及其执行过程;
- if:
a=1
b=2
if a<b
print "a<b"
- if…else…
- if…elif…else…
-注意:在python里面不支持switch语句,如果想实现switch的效果,第一种方法就是使用if…elif…elif…else…;
2. python中的几种循环结构及其执行过程
2.1.for循环
- range(m,n,x):从m起始到n-1结束(不包含n),x代表步长;
for item in range(m.n,x):
循环的语句
for item in 可迭代的类型(eg:字符串.....):
循环的语句
- 两个关键字:
- break:跳出循环,不再执行循环;
- continue:跳出本次循环,继续执行下一个循环;
2.2.while循环
2.2.1while
while 表达式(或者True,False):
循环的语句
In [29]: num =1
In [30]: while num<4:
....: print num
....: num+=1
....:
1
2
3
2.2.2 while … else …..
while 表达式:
循环语句
In [43]: while trycount<3:
...: print "login"
...: trycount+=1
...: else:
...: print "bigger than 3"
...:
3.编程实例
3.1.处理字符串”1Xa7YzU”,最终分别打印数字,大写字母和小写字母;
#!user/bin/env python
#coding:utf-8
"""
file: sort.py
date: 2017-08-25 3:38 PM
author: fang
version: 1.0
desc:
"""
line=raw_input("please input your string:")
nu=""
up=""
low=""
other=""
for num in line:
if num.isdigit():
nu=nu+num
elif num.isupper():
up=up+num
elif num.lower():
low=low+num
else:
other=other+num
print """
number is :{}
upper is :{}
lower is :{}
others is :{}""".format(nu,up,low,other)
upper1=low.upper()
lower1=up.lower()
3.2. 用户输入一个数字,判断是否为质数;
#!/usr/bin/env python
#coding:utf-8
"""
Name:"for"
Date:"2017"-"08"-"24" "9:38 PM"
Author:fang
Vertion:1.0
"""
while 1:
judge=raw_input("请选择检测还是退出(C & Q):")
if judge.lower()=="c":
num=raw_input("请输入一个数字: ")
print "结果输出".center(40,"*")
if num.isdigit():
num = int(num)
if num<1:
print "您输入的数值小于1"
continue
else:
for i in range(2, num):
if (num % i) == 0:
print "{}不是质数".format(num)
print "因为{}×{}={}".format(i,num // i,num)
break
else:
print"{}是质数".format(num)
else:
print "您输入的不是数字,请输入数字"
continue
elif judge.lower()=="q":
break
else:
print "您的输入有误,请重新输入"
3.3. 编写一个python脚本,判断用户输入的变量名是否合法?
(首位为字母或下划线,其他为数字,字母或下划线)
#!/usr/bin/env python
#coding:utf-8
"""
Name:"Judge_name"
Date:"2017"-"08"-"25" "8:19 PM"
Author:fang
Vertion:1.0
"""
import re
import string
def chechead(pwd):
return pwd[0] in string.letters+"_"
def checkothers(pwd):
for i in pwd[1:]:
if i in string.letters+"_"+string.digits:
return True
else:
return False
def checkname(pwd):
# 判断开头是否合法
headOK = chechead(pwd)
# 判断其他是否合法
othersOK = checkothers(pwd)
if headOK:
print "变量名开头检测通过"
if othersOK:
print "变量名其他检测通过"
else:
print "变量名其他检测未通过"
else:
print "变量名开头检测未通过"
return (headOK and othersOK)
def main():
nameinput=raw_input("请输入您需要检测的变量名:")
if checkname(nameinput):
print'您输入的变量名检测通过'
else:
print'您输入的变量名检测未通过'
if __name__ == '__main__':
main()