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

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…语句
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: