python 常用小程序汇总

1、生成指定位数的随机字符串

# -*- coding:utf-8 -*-
import random
def my_char(length):
    s=" abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKL MNOPQRSTUVIXYZ!aN$x*6*( )?"
    p = "" .join(random.sample(s,length ))
    return p

a = my_char(5)
print(a)



2、猜数字游戏

在这个游戏中,任务是创建一个脚本,能够在一个范围内生成一个随机数。如果用户在三次机会中猜对了数字,那么用户赢得游戏,否则用户输。

import random
number = random.randint(1, 20)
print(number)

for i in range(0, 3):
    user = int(input("guess the number:
"))
    if user ==number:
        print("Nice")
        print("you guess the number right it's {}".format(number))
    elif user > number:
        print("you guess is too high")
    elif user < number:
        print("you guess is too low")
else:
    print("没机会了...")


3、已知一个字符串 "hello_world_test" ,如何得到一个列表 ["hello","world","test"]

使用split方法:
在Python的高级特性里有切片(split)操作符,可以对字符串进行截取。

语法
看一下源码:

    def split(self, *args, **kwargs): # real signature unknown
        """
        Return a list of the words in the string, using sep as the delimiter string.
        # 使用sep作为分隔符字符串,返回字符串中的单词列表
        # 有两个参数:sep, maxsplit
          sep
            The delimiter according which to split the string.  # 用于拆分字符串的分隔符。
            None (the default value) means split according to any whitespace,
            and discard empty strings from the result.
          maxsplit
            Maximum number of splits to do.
            # 分割次数
            -1 (the default value) means no limit.
        """
        pass

例子1

t = "Baidu JD Taobao Facebook"
print(t.split())

# 结果:
# ['Baidu', 'JD', 'Taobao', 'Facebook']

结论:当不带参数时,默认是以空字符作为参数进行分割,空字符全部被分割。

例子2

t = "Baidu JD Taobao Facebook"
print(t.split(" ", 1))

# 结果:
# ['Baidu', 'JD Taobao Facebook']

结论: 以 空格 为分隔符,指定第二个参数为 1,返回两个参数列表。

所以题目的答案:

test = "hello_world_test"
print(test.split("_"))

# 结果:
# ['hello', 'world', 'test']


4、编程输出1/1+1/3+1/5...1/99的和

#coding=utf-8
def mysum(num):
    sum=0
    for i in range(num):
        if(i%2) == 1:
            sum=sum+1/i
    return sum

if __name__=='__main__':
    res=mysum(100)
原文地址:https://www.cnblogs.com/wwho/p/15393929.html