python 30个基础操作

运行环境 : python 3.6.0

 

今天来一个基础操作 ...

1、冒泡排序 

lis = [56, 12, 1, 8, 354, 10, 100, 34, 56, 7, 23, 456, 234, -58]
def sortport():
    for i in range(len(lis)-1):
        for j in range(len(lis)-1-i):
            if lis[j] > lis[j+1]:
                lis[j],lis[j+1] = lis[j+1],lis[j]
    return lis

# 输出
"""
[-58, 1, 7, 8, 10, 12, 23, 34, 56, 56, 100, 234, 354, 456]
"""

2、计算x的n次方的方法 

def power(x, n):
    s = 1
    while n > 0:
    n = n - 1
    S = S * x
    return S


# 输出
"""
power(2, 10) -> 1024
"""

3、计算a*a + b*b + c*c + …… 

def calc(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum

# 输出
"""
calc(1, 2, 3, 4, 5) -> 55
"""

4、计算阶乘 n! 

def fac():
    num = int(input("请输入一个数字: "))
    factorial = 1

    #查看数字是负数,8或正数
    if num < 0:
        print( "抱歉 , 负数没有阶乘")
    elif num == 0:
        print("0 的阶乘为 1")
    else:
        for i in range(1, num + 1):
            factorial = factorial * i
        print("%d 的阶乘为 %d" % (num, factorial))


# 输出
"""
请输入一个数字: 5
5的阶乘为120
"""
def factorial(n):
    result = n
    for i in range(1, n):
        result *= i
    return result


# 输出
"""
factorial(5) -> 120
"""

 5、列出当前目录下的所有文件和目录名

import os

def get_list_dirs():
    dirs = [d for d in os.listdir('.')]
    return dirs

# 输出
"""
['1.jpg', 'captcha1.png', 'test.py', 'test.txt', '__init__.py']
"""

 6、把一个list中所有的字符串变成小写:

def list_string_to_lower(L):
    L = [s.lower() for s in L]
    return L

# 输出
"""
list_string_to_lower(['Hello', 'World', 'IBM', 'Apple']) -> ['hello', 'world', 'ibm', 'apple']
"""

 7、输出某个路径下的所有文件和文件夹的路径

def print_dir():
    filepath = input("请输入一个路径: ")
    if filepath == "":
        print("请输入正确的路径")
    else:
        for i in os.listdir(filepath):  # 获取目录中的文件及子目录列表
            print(os.path.join(filepath,i))  # 把路径组合起来

# 输出
"""
请输入一个路径: E:\Python\Projects\不是闹着玩儿嘞\example\test
E:\Python\Projects\不是闹着玩儿嘞\example\test\1.jpg
E:\Python\Projects\不是闹着玩儿嘞\example\test\captcha1.png
E:\Python\Projects\不是闹着玩儿嘞\example\test\test.py
E:\Python\Projects\不是闹着玩儿嘞\example\test\test.txt
E:\Python\Projects\不是闹着玩儿嘞\example\test\__init__.py
"""

8、输出某个路径及其子目录下的所有文件路径 

import os

def show_dir(filepath):
    for i in os.listdir(filepath):
        path = (os. path. join(filepath, i))
        print(path)
        if os.path. isdir(path):  # isdir()判断是否是目录
            show_dir(path)  # 如果是目录,使用递归方法

# 输出
"""
show_dir(r'E:\Python\Projects\不是闹着玩儿嘞\example\test')

E:\Python\Projects\不是闹着玩儿嘞\example\test\1.jpg
E:\Python\Projects\不是闹着玩儿嘞\example\test\captcha1.png
E:\Python\Projects\不是闹着玩儿嘞\example\test\test.py
E:\Python\Projects\不是闹着玩儿嘞\example\test\test.txt
E:\Python\Projects\不是闹着玩儿嘞\example\test\__init__.py
"""

 9、输出某个路径及其子目录下所有以.html为后缀的文件

import os

def print_dir(filepath):
    for i in os.listdir(filepath):
        path = os.path.join(filepath, i)
        if os.path.isdir(path):
            print_dir(path)
        if path.endswith(".html"):
            print(path)

# 输出
"""
print_dir(r'E:\Python\Projects\不是闹着玩儿嘞\example\test')

E:\Python\Projects\不是闹着玩儿嘞\example\test\test.html
"""

 10、把原字典的键值对颠倒并生产新的字典

dict1 = {"A": "a", "B": "b", "C": "c" }
dict2 = {y: x for x, y in dict1.items()}
print (dict2)

# 输出
"""
E:\Python\Python36\python.exe E:/Python/Projects/不是闹着玩儿嘞/example/test/test.py
{'a': 'A', 'b': 'B', 'c': 'C'}
"""

11、打印九九乘法表 

for i in range(1, 10):
    for j in range(1, i+1):
        print("%d*%d=%-2d\t" % (i, j, i*j), end='')
    print()

# 输出

"""
1*1=1 	
2*1=2 	2*2=4 	
3*1=3 	3*2=6 	3*3=9 	
4*1=4 	4*2=8 	4*3=12	4*4=16	
5*1=5 	5*2=10	5*3=15	5*4=20	5*5=25	
6*1=6 	6*2=12	6*3=18	6*4=24	6*5=30	6*6=36	
7*1=7 	7*2=14	7*3=21	7*4=28	7*5=35	7*6=42	7*7=49	
8*1=8 	8*2=16	8*3=24	8*4=32	8*5=40	8*6=48	8*7=56	8*8=64	
9*1=9 	9*2=18	9*3=27	9*4=36	9*5=45	9*6=54	9*7=63	9*8=72	9*9=81	
"""

通过指定end参数的值,可以取消在末尾输出回车符,实现不换行。 

s = "\n".join(["\t".join(["%d*%d=%-2d" % (i, j, i*j) for j in range(1, i+1)]) for i in range(1, 10)])
print(s)


# 输出
"""
1*1=1 
2*1=2 	2*2=4 
3*1=3 	3*2=6 	3*3=9 
4*1=4 	4*2=8 	4*3=12	4*4=16
5*1=5 	5*2=10	5*3=15	5*4=20	5*5=25
6*1=6 	6*2=12	6*3=18	6*4=24	6*5=30	6*6=36
7*1=7 	7*2=14	7*3=21	7*4=28	7*5=35	7*6=42	7*7=49
8*1=8 	8*2=16	8*3=24	8*4=32	8*5=40	8*6=48	8*7=56	8*8=64
9*1=9 	9*2=18	9*3=27	9*4=36	9*5=45	9*6=54	9*7=63	9*8=72	9*9=81
"""

12、替换列表中所有的3为3a 

num = ["harden", "lampard", 3, 34, 45, 56, 76, 87, 78 , 45, 3, 3, 3, 87686, 98, 76]
for i in range (num. count(3)):  # 获取3出现的次数
    ele_index = num . index(3)  # 获取首次3出现的坐标
    num[ele_index] = "3a"  # 修改3为3
print(num)

# 输出
"""
['harden', 'lampard', '3a', 34, 45, 56, 76, 87, 78, 45, '3a', '3a', '3a', 87686, 98, 76]
"""

13、打印每个名字 

L = [" James" , "Meng", "Xin"]
for i in range(len(L)):
    print("Hello,%s" % L[i])

# 输出
"""
Hello, James
Hello,Meng
Hello,Xin
"""

善于使用 range() ,会使问题变得简单 

14、合并去重

list1=[2,3,8,4,9,5,6]
list2 = [5, 6, 10, 17, 11, 2]
list3 = list1 + list2
print(list3)  # 不去重只进行两个列表的组合
print(set(list3))  # 去重,类型为set需要转换成list
print(list(set(list3)))

# 输出
"""
[2, 3, 8, 4, 9, 5, 6, 5, 6, 10, 17, 11, 2]
{2, 3, 4, 5, 6, 8, 9, 10, 11, 17}
[2, 3, 4, 5, 6, 8, 9, 10, 11, 17]
"""

15、随机生成验证码的两种方式 

import random
list1=[ ]
for i in range(65,91):
    list1. append(chr(i)) #通过 for循环遍历asii追加到空列表中
for j in range(97,123):
    list1. append(chr(j))
for k in range(48,58):
    list1. append(chr(k))
ma = random. sample(list1,6)
print (ma)  # 获取到的为列表
ma = "".join(ma)  # 将列表转化为字符串
print(ma)

# 输出
"""
['D', 'a', '3', 'k', '1', '8']
Da3k18
"""
import random, string
str1 = "0123456789"
str2 = string.ascii_letters  # string.ascii letters 包含所有字母(大写或小写)的字符串
str3 = str1 + str2
mal = random. sample(str3,6)  # 多个字符中选取特定数量的字符
mal = ''.join(mal)  # 使用join拼接转换为字符串
print (mal)  # 通过引入string模快和random模决使用现有的方法

# 输出
"""
GpcOhC
"""
#随机数字小游戏
import random
i = 1
a = random. randint(0, 100)
b = int( input('请输入 0-100 中的一个数字\n然后查看是否与电脑一样: '))
while a != b:
    if a > b:
        print('你第 %d 输入的数字小于电脑随机数字' % i)
        b = int(input('请再次输入数字: '))
    else:
        print('你第 %d 输入的数字大于电脑随机数字' % i)
        b = int(input('请再次输入数字: '))
    i+=1
else:
    print('恭喜你,你第 %d 次输入的数字与电脑的随机数字%d-样' % (i, b))

# 输出
"""
请输入 0-100 中的一个数字
然后查看是否与电脑一样: 50
你第 1 输入的数字小于电脑随机数字
请再次输入数字: 75
你第 2 输入的数字大于电脑随机数字
请再次输入数字: 67
你第 3 输入的数字大于电脑随机数字
请再次输入数字: 58
你第 4 输入的数字小于电脑随机数字
请再次输入数字: 62
你第 5 输入的数字小于电脑随机数字
请再次输入数字: 65
你第 6 输入的数字大于电脑随机数字
请再次输入数字: 64
你第 7 输入的数字大于电脑随机数字
请再次输入数字: 63
恭喜你,你第 8 次输入的数字与电脑的随机数字63-样
"""

16、计算平方根 

num = float(input( '请输入一个数字: '))
num_sqrt = num ** 0.5
print('%.2f 的平方根为 %8.2f' % (num ,num_sqrt))

# 输出
"""
请输入一个数字: 3.7
3.70 的平方根为     1.92
"""

17、判断字符串是否只由数字组成 

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass
    try:
        import unicodedata
        unicodedata. numeric(s)
        return True
    except (TypeError, ValueError):
        pass
        return False
# 输出
"""
is_number("123456as") -> False
"""
chri = "123456"
print (chri.isdigit())  # 检测字符串是否只由数字组成
print(chri.isnumeric())  # 检测字符串是否只由数字组成,这种方法是只针对unicode对象

# 输出
"""
True
True
"""

 18、判断奇偶数

num = int(input("输入一个数字: "))
if (num % 2) == 0:
    print("{0} 是偶数".format(num))
else:
    print("{0} 是奇数".format(num))

# 输出
"""
输入一个数字: 3
3 是奇数
"""
while True :
    try:
        num = int(input('输入一个整数: '))  # 判断输入是否为整数
    except ValueError:  # 并不是纯数字需要重新输入
        print("输入的不是整数! ")
        continue
    if num % 2 == 0:
        print('偶数')
    else:
        print('奇数')
    break


# 输出
"""
输入一个整数: 3
奇数
"""

 19、判断闰年

year = int(input("输入一个年份: "))
if(year%4)==0:
    if (year % 100) == 0:
        if (year % 400) == 0:
            print("{0}是闰年".format(year))  # 整百年能被40整除的是闰年
        else:
            print("{0}不是闰年".format(year))
    else:
        print("{0}是闰年".format(year))  # 非整百年能被4整除的为闰年
else:
    print("{0}不是闰年".format(year))

# 输出
"""
输入一个年份: 2019
2019不是闰年
"""
year = int(input("请输入一个年份: "))
if (year % 4) == 0 and (year % 100) != 0 or (year % 400) == 0:
    print("{0} 是闰年".format(year))
else:
    print("{0} 不是闰年".format(year))

# 输出
"""
请输入一个年份: 2020
2020 是闰年
"""
import calendar
year = int(input("请输入年份: "))
check_year=calendar.isleap(year)
if check_year == True:
    print("%d是闰年" % year)
else:
    print("%d是平年" % year)

# 输出
"""
请输入年份: 2021
2021是平年
"""

20、获取最大值 

N = int(input( '输入需要对比大小数字的个数: '))
print("请输入需要对比的数字: ")
num = []
for i in range(1, N+1):
    temp = int(input('输入第 %d 个数字: ' % i))
    num.append(temp)
print('您输入的数字为: ',num)
print('最大值为:', max(num))

# 输出
"""
输入需要对比大小数字的个数: 3
请输入需要对比的数字: 
输入第 1 个数字: 5
输入第 2 个数字: 4
输入第 3 个数字: 8
您输入的数字为:  [5, 4, 8]
最大值为: 8
"""
N = int(input( '输入需要对比大小数字的个数: '))
num = [int(input('请输入第 %d个对比数字: ' % i)) for i in range(1,N+1)]
print('您输入的数字为: ', num)
print('最大值为: ', max(num))

# 输出
"""
输入需要对比大小数字的个数: 3
请输入第 1个对比数字: 8
请输入第 2个对比数字: 7
请输入第 3个对比数字: 3
您输入的数字为:  [8, 7, 3]
最大值为:  8
"""

21、斐波那契数列

斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13;特别指出:第0项是0,第1项是第一个1。从第三项开始,每一项都等于前两项之和。 

nterms = int(input("please a number >> "))
n1 = 0
n2 = 1
count = 0
#判断输入的值是否合法
if nterms <= 0:
    print("请输入一个正整数。")
elif nterms == 1:
    print( "斐波那契数列: ")
    print(n1)
else:
    print("斐波那契数列: ")
    print(n1, ",", n2, end=" , ")
    while count+2 < nterms:  # +2 是因为已经输出过两个了
        nth=n1+n2
        print(n1+n2, end=" , ")
        # 更新值
        n1 = n2
        n2 = nth
        count += 1

# 输出
"""
please a number >> 5
斐波那契数列: 
0 , 1 , 1 , 2 , 3 , 
"""
import sys
sys.stdout.flush()  # 强制把放在缓冲区的输出内容推入CPU, 强制刷新

L = [0, 1]
num = int(input("please input a num >> "))
if num <= 0:
    print("你有毒 , 请好好输入 !")
elif num <= 2:
    print("斐波那契数列:", L[:num])
else:
    # for i in range(2, num):
    #     next_number = L[i-2] + L[i]
    #     L.append(next_number)
    # print(L)
    print("斐波那契数列:", L[0], ',', L[1], end=', ')
    for i in range(2, num+1):
        next_number = L[i-2] + L[i-1]
        L.append(next_number)
        if i % 5 == 0:
            print()
        print(next_number, end=", ")

# 输出
"""
please input a num >> 10
斐波那契数列:
 0 , 1, 1, 2, 3, 
5, 8, 13, 21, 34, 
"""

22、十进制转二进制、八进制、十六进制 

#获取输入十进制数
dec = int(input( "输入数字: "))
print("+进制数为:", dec)
print("转换为二进制为:", bin(dec))
print("转换为八进制为:", oct(dec))
print("转换为十六进制为: ", hex(dec))

# 输出
"""
输入数字: 14
+进制数为: 14
转换为二进制为: 0b1110
转换为八进制为: 0o16
转换为十六进制为:  0xe
"""

23、最大公约数

def hcf(x, y):
    """该函数返回两个数的最大公约数"""
    #获取最小值
    if x > y:
        smaller = y
    else:
        smaller = x
    for i in range(2, smaller + 1):
        if ((x % i == 0) and (y % i == 0)):
            hcf = i
            return hcf

#用户输入两个数字
num1 = int(input("输入第一个数字: "))
num2 = int(input("输入第二个数字: "))
print(num1,"和", num2, "的最大公约数为", hcf(num1, num2))

# 输出
"""
输入第一个数字: 3
输入第二个数字: 6
3 和 6 的最大公约数为 3
"""

23、最小公倍数 

#定义函数
def lcm(x, y):
    #获取最大的数
    if x> y:
        greater = x
    else:
        greater = y
    while(True):
        if((greater % x == 0) and (greater % y == 0)):
            lcm = greater
            break
        greater += 1
    return lcm

#获取用户输入
num1 = int(input("输入第一个数字: "))
num2 = int(input( "输入第二个数字: "))
print( num1, "和", num2, "的最小公倍数为", lcm(num1, num2))

# 输出
"""
输入第一个数字: 10
输入第二个数字: 15
10 和 15 的最小公倍数为 30
"""

24、简单计算器 

#定义函数
def add(x, y):
    """ 相加 """
    return x + y
def subtract(x, y):
    """ 相减 """
    return x - y
def multiply(x, y):
    """ 相乘 """
    return x * y
def divide(x, y):
    """ 相除 """
    return x / y

#用户输入
print("选择运算: ")
print("1、相加")
print("2、相减")
print("3、相乘")
print("4、相除")
choice = input("输入你的选择(1/2/3/4):")
num1 = int(input("输入第一个数字:"))
num2 = int(input("输入第二个数字:"))

if choice == '1':
    print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
    print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
    print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
    if num2 != 0:
        print(num1, "/", num2, "=", divide(num1, num2))
    else:
        print("分母不能为0")
else:
    print("非法输入")

# 输出
"""
选择运算: 
1、相加
2、相减
3、相乘
4、相除
输入你的选择(1/2/3/4):3
输入第一个数字:5
输入第二个数字:3
5 * 3 = 15
"""

25、生成日历 

#引入日历模块
import calendar
#输入指定年月
yy = int(input("输入年份: "))
mm = int(input("输入月份: "))
#显示日历
print (calendar . month(yy, mm))

# 输出
"""
输入年份: 2019
输入月份: 8
    August 2019
Mo Tu We Th Fr Sa Su
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

"""

26、文件IO 

# 写文件
with open("test.txt", "wt" ) as out_file:
    out_file.write("该文本会写入到文件中\n看到我了吧! ")
# Readafile
with open("test.txt", "rt") as in_file:
    text = in_file.read()
print(text)

# 输出
"""
该文本会写入到文件中
看到我了吧! 
"""

27、字符串判断 

#测试实例一
print("测试实例一")
str = "runoob.com"
print("'"+str+"'", "isalnum :", str.isalnum())  # 判断所有字符都是数字或者字母
print("'"+str+"'", "isalpha :", str.isalpha())  # 判断所有字符都是字母
print("'"+str+"'", "isdigit :", str.isdigit())  # 判断所有字符都是数字
print("'"+str+"'", "islower :", str.islower())  # 判断所有字符都是小写
print("'"+str+"'", "isupper :", str.isupper())  # 判断所有字符都是大写
print("'"+str+"'", "istitle :", str.istitle())  # 判断所有单词都是首字母大写,像标题
print("'"+str+"'", "isspace :", str.isspace())  # 判断所有字符都是空白字符、\t、 \n、\r
print("----------------------")

#测试实例二
print("测试实例二")
str = "Bake corN"
print("'"+str+"'", "isalnum :", str.isalnum())
print("'"+str+"'", "isalpha :", str.isalpha())
print("'"+str+"'", "isdigit :", str.isdigit())
print("'"+str+"'", "islower :", str.islower())
print("'"+str+"'", "isupper :", str.isupper())
print("'"+str+"'", "istitle :", str.istitle())
print("'"+str+"'", "isspace :", str.isspace())

# 输出
"""
测试实例一
'runoob.com' isalnum : False
'runoob.com' isalpha : False
'runoob.com' isdigit : False
'runoob.com' islower : True
'runoob.com' isupper : False
'runoob.com' istitle : False
'runoob.com' isspace : False
----------------------
测试实例二
'Bake corN' isalnum : False
'Bake corN' isalpha : False
'Bake corN' isdigit : False
'Bake corN' islower : False
'Bake corN' isupper : False
'Bake corN' istitle : False
'Bake corN' isspace : False
"""

28、字符串大小写转换 

str = "https://blog.csdn.net/qq_39377418"
print("'"+str+"'", "upper :", str.upper())         # 把所有字符中的小写字母转换成大写字母
print("'"+str+"'", "lower :", str.lower())        # 把所有字符中的大写字母转换成小写字母
print("'"+str+"'", "capitalize :", str.capitalize())    # 把第一个字母转化为大写字母,其余小写
print("'"+str+"'", "title :", str.title())         # 把每个单词的第个字母转化为大写, 其余小写

# 输出
"""
'https://blog.csdn.net/qq_39377418' upper : HTTPS://BLOG.CSDN.NET/QQ_39377418
'https://blog.csdn.net/qq_39377418' lower : https://blog.csdn.net/qq_39377418
'https://blog.csdn.net/qq_39377418' capitalize : Https://blog.csdn.net/qq_39377418
'https://blog.csdn.net/qq_39377418' title : Https://Blog.Csdn.Net/Qq_39377418
"""

29、计算每个月天数 

import calendar
monthRange = calendar.monthrange(2016, 9)
print(monthRange)

# 输出
"""
(3, 30)
"""

 30、获取昨天的日期

#引入datetime模块
import datetime
def getYesterday():
    today = datetime.date.today()
    oneday = datetime.timedelta( days=1)
    yesterday = today - oneday
    return yesterday


print(getYesterday())

# 输出
"""
2019-07-31
"""

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值