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

Python脚本 基础脚本训练

2016-04-14 14:31 639 查看

Python 基础脚本

1>random:随机数模块,首先import random模块

1、random.random() 生成[0.0,1.0)的随机浮点数

>>> int(random.ran
4000
dom()*100+1)

2、random.randint(x,y)生成(x,y)指定区间的随机整数

>>>random.randint(1,100)

3、random.unfiorm(x,y)生成(x,y)之间的随机浮点数

>>>random.uniform(10,20)

4、random.randrange(start,stop,[step])生成一个指定步进的随机整数

>>>random.randrange(10,100,10)

5、random.choice(sequence)随机抽取序列类型中的一个元素

>>>number= [1,3,4,5,6,8,0,15,56,763]
>>>random.choice(number)

6、random.sample(sequence,n)生成随机从sequence中抽取n个元素组合的新的List对象

>>>nameList=["Jimmy","xiao","miao","bao","hello","world"]
>>>random.sample(nameList,2)

7、random.shuffle(List)打乱一个List对象中元素的顺序

>>>random.shuffle(number)

2>“stars”脚本

vim /opt/workspace/Pyhon/stars.py
#!/usr/bin/env python

#conding=utf8

n = 20

m = 0

for x in range(0,20):

    print ' '*m + (2*n-1)*'*'

    m += 1

    n -= 1

3>随机数比较大小

vim /opt/workspace/Pyhon/numberAnd.py
#!/src/bin/env python

#coding=utf8

number1 = 10

number2 = int(raw_input("Pls neter a number: "))

print "number1 value:%d"  %  (number1)

if number2 > number1:

    print "number2 > number1"

    print "Done test"

elif number2 < number1:

    print "number2 < number1"

    print "Done test"

else:

    print "number2 = number1"
print "Done all test."

4>修改密码

vim /etc/opt/Python/passwd.py
#!/usr/bin/env python

def doubleCheckInput(input1,input2="Jimmy"):

    if input1 == input2:

        print "The password is right!"

        print "Value of input2:%s" % input2

        return 1

    else:

        print "Pls check the passwork and enter again."

        return 0

def changeThePwd(input1,input2):

    if input1 == input2:

        print "The pwd setup successfully"

        return 1

    else:

        print "Error:Pls check the enter and enter again!"

        return 0

if __name__ == '__main__':

    oldPwd1 = raw_input("Pls enter the PWD:")

    reslove = doubleCheckInput(oldPwd1)

    if reslove == 1:

        newPwd1 = raw_input("Pls enter the new PWD:")

        newPwd2 = raw_input("Pls enter the new PWD again:")

        changePwdReslove = changeThePwd(newPwd1,newPwd2)

        if changePwdReslove == 1:

            print "Change Done"

        else:print "Error:Change Failed"

    else:

        print "The PWD is worng"

    print "Done"

5>1-100能被5整除的数显示出来

vim /etc/opt/Python/five.py
#!/usr/bin/env python

#coding=utf8

import sys

i = 101

count = 0

while(i>0):

    i -= 1

    if i%5:

        continue

    print i,

    count += 1

print "Done"

print "Execution times:%d" % count

6>查询是否存在nameList中

vim /etc/opt/Python/nameList.py
#!/src/bin/env python

nameList = ['Jimmy','Mikey','Wen','Pan']

classMateName = raw_input("Pls enter the classMateName: ")

if classMateName in nameList:

    print "The %s in the class" % classMateName

else:

    print "Not in"

print "Done all"


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息