python 练习2

练习题

  • 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…语句
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值