python 练习2

来源:互联网 发布:淘宝秒杀白菜群 编辑:程序博客网 时间:2024/06/08 12:24

练习题

  • 1.用户输入一个数字,判断是否为质数
#!/usr/bin/env python#coding:utf-8"""file:.pydate:2017/8/25 21:34author:    peakdescription:"""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:.pydate:2017/8/25 22:11author:    peakdescription:"""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 += iprint "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:.pydate:2017/8/25 22:25author:    peakdescription:"""import stringVari=raw_input("please input the variants name : ")Length=len(Vari)Length1=len(string.letters+"_")count=0count1=0for 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…语句