1.冒泡排序
a = [25,15,47,36,44,455,67,234,7,8,-47]
def sortport():
for i in range(len(a)-1):
for j in range (len(a)-1-i):
if a[j]>a[j+1]:
a[j],a[j+1] = a[j+1],a[j]
return a
if __name__ == '__main__':
sortport()
print(a)

输出

[-47, 7, 8, 15, 25, 36, 44, 47, 67, 234, 455]

Process finished with exit code 0

2.计算X的n次方

def power(x,n):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
print(power(2,4))#输出16

3.计算a*a+b*b+c*c...

def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n*n
return sum
print(calc(2,3,4))#输出29

4.计算阶乘n!

方法一:

def fac():
num = int(input("请输入一个数字:"))
factorial = 1
#查看数字是负数,0或者正数
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))
if __name__=='__main__':
fac()#请输入一个数字:5 5的阶乘为120

方法二:

def fac():
num = int(input("请输入一个数字:"))
# 查看数字是负数,0或者正数
if num < 0:
print("负数没有阶乘")
elif num == 0:
print("0的阶乘为1")
else:
print("%d的阶乘为%d" % (num, factorial(num)))
def factorial(n):
result = n
for i in range(1,n):
result = result * i
return result
if __name__=='__main__':
fac()

方法三:

def fac():
num = int(input("请输入一个数字:"))
# 查看数字是负数,0或者正数
if num < 0:
print("负数没有阶乘")
elif num == 0:
print("0的阶乘为1")
else:
print("%d的阶乘为%d" % (num, fact(num)))
def fact(n):
if n == 1:
return 1
return n * fact(n - 1)
if __name__=='__main__':
fac()

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

import os
for d in os.listdir('.'):
print(d)
#;另外列表推导式代码:
[d for d in os.listdir('.')]

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

L =  ['Hello','World','IBM','Apple']
for s in L:
s = s.lower()
print(s)#将list中的每个字符串都变成小写,返回每个字符串

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

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

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) #如果是目录,使用递归方法
filepath = 'C:/PyProject'
show_dir(filepath)

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)
filepath = 'C:'
print_dir(filepath)

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

dict1 = {"A":"a","B":"b","C":"c"}
dict2 = {y:x for x,y in dict1.items()}
print(dict2)#输出结果{'a': 'A', 'c': 'C', 'b': 'B'}

11.打印九九乘法表

for i in range(1,10):
for j in range(1,i+1):
print('%d*%d=%d '%(j,i,i*j),end='')#通过指定end参数的值,可以取消在末尾输出回车符,实现不换行
print()

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

num = ["hello","estate",3,34,45,47,53,26,83,3,3,87,35,63]
print(num.count(3))
print(num.index(3))
for i in range(num.count(3)): #获取3出现的次数
ele_index = num.index(3) #获取首次出现3的坐标
num[ele_index]='3a' #修改3为3a
print(num)

13.打印每个名字

L = ["Estate","Shell","Jenny"]
for i in range(len(L)):
print("Hello,%s"%L[i])

14.合并去重

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

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)
import random,string
str1 = ""
str2 = string.ascii_letters # string.ascii_letters 包含所有字母(大写或小写)的字符串
str3 = str1+str2
ma1 = random.sample(str3,6) #多个字符中选取特定数量的字符
ma1 = ''.join(ma1) #使用join拼接转换为字符串
print(ma1) #通过引入string模块和random模块使用现有的方法

16.随机数字小游戏

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))

17.计算平方根

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

18.判断字符串是否只由数字组成

方法一:
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
t = "d473q"
print(is_number(t)) 方法二:
t = "d547"
print(t.isdigit())#检测字符串是否只由数字组成 #方法三:
t = ""
print(t.isnumeric())#检测字符串是否只由数字组成,这种方法只针对unicode对象

19.判断奇偶数

方法一:
num = int(input('请输入一个数字:'))
if (num % 2) == 0:
print("{0}是偶数".format(num))
else:
print("{0}是奇数".format(num)) 方法二:
while True:
try:
num = int(input('请输入一个整数:'))#判断输入是否为整数,不是纯数字需要重新输入
except ValueError:
print("输入的不是整数!")
continue
if (num % 2) == 0:
print("{0}是偶数".format(num))
else:
print("{0}是奇数".format(num))
break

20.判断闰年

方法一:
year = int(input("请输入一个年份:"))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0}是闰年".format(year))#整百能被400整除的是闰年
else:
print("{0}不是闰年".format(year))
else:
print("{0}是闰年".format(year))
else:
print("{0}不是闰年".format(year)) 方法二:
year = int(input("请输入一个年份:"))
if (year % 4) == 0 and (year % 100) != 0 or (year % 400) == 0:
print("{0}是闰年".format(year))
else:
print("{0}不是闰年".format(year)) 方法三:
import calendar
year = int(input("请输入一个年份:"))
check_year = calendar.isleap(year)
if check_year == True:
print("%d是闰年"%year)
else:
print("%d是平年" % year)

21.获取最大值

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)) N = int(input('输入需要对比大小的数字的个数:\n'))
num = [int(input('请输入第%d个数字:\n'%i))for i in range(1,N+1)]
print('您输入的数字为:',num)
print('最大值为:',max(num))

22.斐波那契数列

斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13;特别指出:
第0项是0,第1项是第一个1。从第三项开始,每一项都等于前两项之和。
判断输入的值是否合法
if nterms <= 0:
print("请输入一个正整数。")
elif nterms == 1:
print("斐波那契数列:")
print(n1)
else:
print("斐波那契数列:")
print(n1,",",n2,end=",")
while count < nterms:
nth = n1 + n2
print(n1+n2,end=",")
#更新值
n1 = n2
n2 = nth
count +=1

23.十进制转二进制、八进制、十六进制

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

24.最大公约数

def hcf(x,y):
"""该函数返回两个数的最大公约数"""
#获取最小值
if x > y:
smaller = y
else:
smaller = x
for i in range(1,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))

25.最小公倍数

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
return lcm
#获取用户输入
num1 = int(input("输入第一个数字:"))
num2 = int(input("输入第二个数字:"))
print(num1,"和",num2,"的最小公倍数为",lcm(num1,num2))

26.简单计算器

定义函数
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 == '':
print(num1,"+",num2,"=",add(num1,num2))
elif choice == '':
print(num1,"-",num2,"=",subtract(num1,num2))
elif choice == '':
print(num1,"*",num2,"=",multiply(num1,num2))
elif choice == '':
if num2 != 0:
print(num1, "/", num2, "=", divide(num1, num2))
else:
print("分母不能为0")
else:
print("非法输入")

27.生成日历

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

28.文件IO

Write a file
with open("test.txt","wt") as out_file:
out_file.write("你好,2019!")
#Read a file
with open("test.txt","rt") as in_file:
text = in_file.read()
print(text)

29.字符串判断

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

30.字符串大小写转换

str = "https://www.cnblogs.com/Estate-47/"
print(str.upper()) # 把所有字符中的小写字母转换成大写字母
print(str.lower()) # 把所有字符中的大写字母转换成小写字母
print(str.capitalize()) # 把第一个字母转化为大写字母,其余小写
print(str.title()) # 把每个单词的第一个字母转化为大写,其余小写

31.计算每个月天数

import calendar
monthRange = calendar.monthrange(2019,1)
print(monthRange)

32.获取昨天的日期

import datetime
def getYesterday():
today = datetime.date.today()
oneday = datetime.timedelta(days=1)
yesterday = today - oneday
return yesterday print(getYesterday())

整理来源于公众号python那些事

python常见用法的更多相关文章

  1. python中os模块和sys模块的常见用法

    OS模块的常见用法 os.remove()   删除文件 os.rename()   重命名文件 os.walk()    生成目录树下的所有文件名 os.chdir()    改变目录 os.mkd ...

  2. python map 常见用法

    python map 常见用法2017年02月01日 19:32:41 淇怪君 阅读数:548版权声明:欢迎转载,转载请注明出处 https://blog.csdn.net/Tifficial/art ...

  3. python之模块pprint之常见用法

    # -*- coding: cp936 -*- #python 27 #xiaodeng #python之模块pprint之常见用法 import pprint data = [(1,{'a':'A' ...

  4. python之模块poplib之常见用法

    # -*- coding: cp936 -*- #python 27 #xiaodeng #python之模块poplib之常见用法 ''' 所以,收取邮件分两步: 第一步:用poplib把邮件的原始 ...

  5. 【python库模块】Python subprocess模块功能与常见用法实例详解

    前言 这篇文章主要介绍了Python subprocess模块功能与常见用法,结合实例形式详细分析了subprocess模块功能.常用函数相关使用技巧. 参考 1. Python subprocess ...

  6. Shell常见用法小记

    shell的简单使用 最近发现shell脚本在平常工作中简直算一把瑞士军刀,很多场景下用shell脚本能实现常用的简单需求,而之前都没怎么学习过shell,就趁机把shell相关的语法和常见用法总结了 ...

  7. Python常见的错误汇总

    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 错误: [错误分析]第二个参数必须为类,否则会报TypeError,所以正确的应 ...

  8. Python高级用法总结

    Python很棒,它有很多高级用法值得细细思索,学习使用.本文将根据日常使用,总结介绍Python的一组高级特性,包括:列表推导式.迭代器和生成器.装饰器. 列表推导(list comprehensi ...

  9. python3 字典常见用法总结

    python3 字典常见用法总结 Python字典是另一种可变容器模型,且可存储任意类型对象,如字符串.数字.元组等其他容器模型. 一.创建字典 字典由键和对应值成对组成.字典也被称作关联数组或哈希表 ...

随机推荐

  1. Saiku本地编译运行后Debug调试(十二)

    Saiku源码拉下来在本地编译通过,然后想进行单元测试 发现不知道怎么写测试类了... 幸好有同事大佬的帮助,教了一招哈哈哈哈... 1.将本地编译通过的Saiku打包好(mvn clean inst ...

  2. Mac系统在Pycharm中切换解释器

    1. 2. 3. 4. 5.

  3. cerebro 配置

    cerebro 是 elastic search 的 监控平台 # Authentication auth = { type: ldap settings: { url = "ldap:// ...

  4. linux curl http get 请求中带有中文参数或者特殊字符处理

    在使用c++去请求http服务的时候,使用的是著名的curl工具提供的类库 libcurl,但是在使用的过程中发现,如果请求的参数值带了空格或者是参数是中文,会导致响应的回调函数没有被执行,虽然cur ...

  5. python 安装scrapy need vistual c++ 14.0 的正面解法

    为什么一堆教程里面,都是侧面的. 因为需要你自己去正面刚 正题: 这个问题要的是 build tools 人(控制台)说的很清楚了, 给的链接不是直接解决问题的链接(我安装了 vs_redis.exe ...

  6. java基础学习之接口

    接口可以说是一个特殊的抽象类,接口里的方法都是抽象方法, 接口的特点: 1.一个类可以实现多个接口,也可以在继承一个类后继续实现多个接口(多实现间接支持了类的多继承) 2.接口可以继承另一个接口,并且 ...

  7. 一十九条优雅Python编程技巧

    1.交换赋值 #不推荐 temp = a a = b b = a #推荐 a , b = b , a #先生成一个元组(tuple)对象,然后在unpack 2.Unpacking #不推荐 l = ...

  8. 剑指Offer 50. 数组中重复的数字 (数组)

    题目描述 在一个长度为n的数组里的所有数字都在0到n-1的范围内. 数组中某些数字是重复的,但不知道有几个数字是重复的.也不知道每个数字重复几次.请找出数组中任意一个重复的数字. 例如,如果输入长度为 ...

  9. QT | QT MSVC 2015 + VS 2015开发环境配置及GIT设置

    1.下载: 所有Qt版本的下载地址: http://download.qt.io/archive/qt/ 实际使用了http://download.qt.io/archive/qt/5.7/5.7.1 ...

  10. python2.7安装pip遇到ImportError: cannot import name HTTPSHandle

    python2.7,报错如下: Traceback (most recent call last): File "/usr/local/bin/pip", line 9, in & ...