python 练习2
2017-08-26 00:12
148 查看
练习题
1.用户输入一个数字,判断是否为质数#!/usr/bin/env python #coding:utf-8 """ file:.py date:2017/8/25 21:34 author: peak description: """ while True: Num=input("please input a number :") if Num <=1 : print "it is not a prime number !" elif Num == 2: print "it is a prime number : 2" for i in range(2,Num): if Num % i == 0 : print "it is not a prime number : {} * {} ={}" .format(i,Num/i,Num) break else : print "it is a prime number: {} % {} != 0" .format(Num,i) break Choose=raw_input("do you want to continue to judge prime? (yes/no) :") if Choose == "no": break
– 运行结果:
2.处理字符串”1Xa7YzU”,最终分别打印数字,大写字母和小写字母;
代码:
#!/usr/bin/env python #coding:utf-8 """ file:.py date:2017/8/25 22:11 author: peak description: """ Upper="" Lower="" Digit="" Str=raw_input("please input a string that you want to sort :") for i in Str: if i.islower(): Lower += i elif i.isupper(): Upper += i elif i.isdigit(): Digit += i print "Lower of string are : {}" .format(Lower) print "Upper of string are : {}" .format(Upper) print "Digit of string are : {}" .format(Digit)
运行结果:
- 3.编写一个python脚本,判断用户输入的变量名是否合法? (首位为字母或下划线,其他为数字,字母或下划线)
#!/usr/bin/env python #coding:utf-8 """ file:.py date:2017/8/25 22:25 author: peak description: """ import string Vari=raw_input("please input the variants name : ") Length=len(Vari) Length1=len(string.letters+"_") count=0 count1=0 for n in string.letters + "_" : if Vari[0]== n: for i in Vari : for m in string.letters + "_" + string.digits: if i == m : count+=1 if count == Length: print "the variants'name is legal ! " else : print "the variants'name is illegal ! " else: count1+=1 if count1==53: print "the variants'name is illegal ! "
结果:
问答题:
- 写出python中的几种分支结构,并解释其执行过程;
(1) if:
if 表达式: #条件
语句 #输出
(2)if…else…
if 表达式: #条件
语句 #输出
else: #其他条件
语句 #其他输出
(3)if…elif…else…
if 表达式: #条件1
语句 #输出1
elif 表达式: #条件2
语句 #输出2
else:
语句 #其他输出
2.写出python中的几种循环结构,并解释其执行过程;
(1)for循环
for i in range(m.n,x):
循环的语句 #条件
语句 #输出
(2)while循环
while 表达式(或者True,False):
循环的语句 #条件
语句 #输出
(2)while … else …..
while 表达式:
循环语句 #条件1
语句 #输出1
else:
语句 #输出2
3.python中是否支持switch语句?
在python里面不支持switch语句,如果想实现switch的效果,就是使用if…elif…elif…else…语句
相关文章推荐
- python 练习 4
- 练习使用Python post请求爬取数据,并用mySQL数据库进行存储
- python小练习---TCP服务器端
- Python练习3
- 笨办法学 Python · 续 练习 32:扫描器
- python基础练习——求“完数”
- learning python in the hard way习题6~10的附加题练习
- python练习(五)
- learning python in the hard way习题11~15的附加题练习
- 11-22 Python数字运算练习
- datetime模块练习Python3
- Python的list和tuple小练习
- Python爬虫练习:爬取csdn极客的更新文章
- Python入门练习0008:输出整数a在二进制表示下1的个数
- python的登录验证练习
- Python3 字典及三级菜单练习
- 【Python 练习】随机显示不重复的单词
- python练习题目
- python练习4
- python matplotlib 用极坐标绘制球员能力图(综合练习)