说明

代码片段来自网上搬运的或者自己写的

华氏温度转摄氏温度

f = float(input('请输入华氏温度: '))
c = (f - 32) / 1.8
print('%.1f华氏度 = %.1f摄氏度' % (f, c))

输入圆的半径计算计算周长和面积

import mathradius = float(input('请输入圆的半径: '))
perimeter = 2 * math.pi * radius
area = math.pi * radius * radius
print('周长: %.2f' % perimeter)
print('面积: %.2f' % area)

输入年份判断是不是闰年

year = int(input('请输入年份: '))
# 如果代码太长写成一行不便于阅读 可以使用\或()折行
is_leap = (year % 4 == 0 and year % 100 != 0 oryear % 400 == 0)
print(is_leap)

英制单位与公制单位互换

value = float(input('请输入长度: '))
unit = input('请输入单位: ')
if unit == 'in' or unit == '英寸':print('%f英寸 = %f厘米' % (value, value * 2.54))
elif unit == 'cm' or unit == '厘米':print('%f厘米 = %f英寸' % (value, value / 2.54))
else:print('请输入有效的单位')

掷骰子决定做什么

from random import randintface = randint(1, 6)
if face == 1:result = '唱首歌'
elif face == 2:result = '跳个舞'
elif face == 3:result = '学狗叫'
elif face == 4:result = '做俯卧撑'
elif face == 5:result = '念绕口令'
else:result = '讲冷笑话'
print(result)

百分制成绩转等级制


score = float(input('请输入成绩: '))
if score >= 90:grade = 'A'
elif score >= 80:grade = 'B'
elif score >= 70:grade = 'C'
elif score >= 60:grade = 'D'
else:grade = 'E'
print('对应的等级是:', grade)

输入三条边长如果能构成三角形就计算周长和面积

import matha = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))
if a + b > c and a + c > b and b + c > a:print('周长: %f' % (a + b + c))p = (a + b + c) / 2area = math.sqrt(p * (p - a) * (p - b) * (p - c))print('面积: %f' % (area))
else:print('不能构成三角形')

上面的代码中使用了math模块的sqrt函数来计算平方根。用边长计算三角形面积的公式叫做海伦公式。

实现一个个人所得税计算器

salary = float(input('本月收入: '))
insurance = float(input('五险一金: '))
diff = salary - insurance - 3500
if diff <= 0:rate = 0deduction = 0
elif diff < 1500:rate = 0.03deduction = 0
elif diff < 4500:rate = 0.1deduction = 105
elif diff < 9000:rate = 0.2deduction = 555
elif diff < 35000:rate = 0.25deduction = 1005
elif diff < 55000:rate = 0.3deduction = 2755
elif diff < 80000:rate = 0.35deduction = 5505
else:rate = 0.45deduction = 13505
tax = abs(diff * rate - deduction)
print('个人所得税: ¥%.2f元' % tax)
print('实际到手收入: ¥%.2f元' % (diff + 3500 - tax))

输入一个数判断是不是素数

from math import sqrtnum = int(input('请输入一个正整数: '))
end = int(sqrt(num))
is_prime = True
for x in range(2, end + 1):if num % x == 0:is_prime = Falsebreak
if is_prime and num != 1:print('%d是素数' % num)
else:print('%d不是素数' % num)

输入两个正整数,计算最大公约数和最小公倍数

x = int(input('x = '))
y = int(input('y = '))
if x > y:(x, y) = (y, x)
for factor in range(x, 0, -1):if x % factor == 0 and y % factor == 0:print('%d和%d的最大公约数是%d' % (x, y, factor))print('%d和%d的最小公倍数是%d' % (x, y, x * y // factor))break

打印三角形图案

row = int(input('请输入行数: '))
for i in range(row):for _ in range(i + 1):print('*', end='')print()for i in range(row):for j in range(row):if j < row - i - 1:print(' ', end='')else:print('*', end='')print()for i in range(row):for _ in range(row - i - 1):print(' ', end='')for _ in range(2 * i + 1):print('*', end='')print()

实现计算求最大公约数和最小公倍数的函数

def gcd(x, y):(x, y) = (y, x) if x > y else (x, y)for factor in range(x, 0, -1):if x % factor == 0 and y % factor == 0:return factordef lcm(x, y):return x * y // gcd(x, y)

实现判断一个数是不是回文数的函数

def is_palindrome(num):temp = numtotal = 0while temp > 0:total = total * 10 + temp % 10temp //= 10return total == num

实现判断一个数是不是素数的函数

def is_prime(num):for factor in range(2, num):if num % factor == 0:return Falsereturn True if num != 1 else False

写一个程序判断输入的正整数是不是回文素数

if __name__ == '__main__':num = int(input('请输入正整数: '))if is_palindrome(num) and is_prime(num):print('%d是回文素数' % num)

在屏幕上显示跑马灯文字

import os
import timedef main():content = '北京欢迎你为你开天辟地…………'while True:# 清理屏幕上的输出os.system('cls')  # os.system('clear')print(content)# 休眠200毫秒time.sleep(0.2)content = content[1:] + content[0]if __name__ == '__main__':main()

设计一个函数产生指定长度的验证码,验证码由大小写字母和数字构成

import randomdef generate_code(code_len=4):"""生成指定长度的验证码:param code_len: 验证码的长度(默认4个字符):return: 由大小写英文字母和数字构成的随机验证码"""all_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'last_pos = len(all_chars) - 1code = ''for _ in range(code_len):index = random.randint(0, last_pos)code += all_chars[index]return code
# 生成随机字符串
def random_str(random_length=8):str = ''# 生成字符串的可选字符串chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'length = len(chars) - 1random = Random()for i in range(random_length):str += chars[random.randint(0, length)]return str

设计一个函数返回给定文件名的后缀名

def get_suffix(filename, has_dot=False):"""获取文件名的后缀名:param filename: 文件名:param has_dot: 返回的后缀名是否需要带点:return: 文件的后缀名"""pos = filename.rfind('.')if 0 < pos < len(filename) - 1:index = pos if has_dot else pos + 1return filename[index:]else:return ''

设计一个函数返回传入的列表中最大和第二大的元素的值

def max2(x):m1, m2 = (x[0], x[1]) if x[0] > x[1] else (x[1], x[0])for index in range(2, len(x)):if x[index] > m1:m2 = m1m1 = x[index]elif x[index] > m2:m2 = x[index]return m1, m2

计算指定的年月日是这一年的第几天

def is_leap_year(year):"""判断指定的年份是不是闰年:param year: 年份:return: 闰年返回True平年返回False"""return year % 4 == 0 and year % 100 != 0 or year % 400 == 0def which_day(year, month, date):"""计算传入的日期是这一年的第几天:param year: 年:param month: 月:param date: 日:return: 第几天"""days_of_month = [[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]][is_leap_year(year)]total = 0for index in range(month - 1):total += days_of_month[index]return total + datedef main():print(which_day(1980, 11, 28))print(which_day(1981, 12, 31))print(which_day(2018, 1, 1))print(which_day(2016, 3, 1))if __name__ == '__main__':main()

打印杨辉三角

def main():num = int(input('Number of rows: '))yh = [[]] * numfor row in range(len(yh)):yh[row] = [None] * (row + 1)for col in range(len(yh[row])):if col == 0 or col == row:yh[row][col] = 1else:yh[row][col] = yh[row - 1][col] + yh[row - 1][col - 1]print(yh[row][col], end='\t')print()if __name__ == '__main__':main()

双色球选号

from random import randrange, randint, sampledef display(balls):"""输出列表中的双色球号码"""for index, ball in enumerate(balls):if index == len(balls) - 1:print('|', end=' ')print('%02d' % ball, end=' ')print()def random_select():"""随机选择一组号码"""red_balls = [x for x in range(1, 34)]selected_balls = []for _ in range(6):index = randrange(len(red_balls))selected_balls.append(red_balls[index])del red_balls[index]# 上面的for循环也可以写成下面这行代码# sample函数是random模块下的函数# selected_balls = sample(red_balls, 6)selected_balls.sort()selected_balls.append(randint(1, 16))return selected_ballsdef main():n = int(input('机选几注: '))for _ in range(n):display(random_select())if __name__ == '__main__':main()

可以使用random模块的sample函数来实现从列表中选择不重复的n个元素。

约瑟夫环问题

"""《幸运的基督徒》
有15个基督徒和15个非基督徒在海上遇险,为了能让一部分人活下来不得不将其中15个人扔到海里面去,有个人想了个办法就是大家围成一个圈,由某个人开始从1报数,报到9的人就扔到海里面,他后面的人接着从1开始报数,报到9的人继续扔到海里面,直到扔掉15个人。由于上帝的保佑,15个基督徒都幸免于难,问这些人最开始是怎么站的,哪些位置是基督徒哪些位置是非基督徒。"""def main():persons = [True] * 30counter, index, number = 0, 0, 0while counter < 15:if persons[index]:number += 1if number == 9:persons[index] = Falsecounter += 1number = 0index += 1index %= 30for person in persons:print('基' if person else '非', end='')if __name__ == '__main__':main()

数字时钟

from time import sleepclass Clock:"""[数字时钟]Args:"""def __init__(self, hour=0, minute=0, second=0):"""[初始化时间]hour (int, optional): Defaults to 0. [Representing hour]minute (int, optional): Defaults to 0. [Representing minute]second (int, optional): Defaults to 0. [Representing second]"""self._hour = hourself._minute = minuteself._second = seconddef run(self):"""[走字]Bad:1. 面条代码(spagetti code)"""while True:print(self)self._second += 1if self._second == 60:self._second = 0self._minute += 1if self._minute == 60:self._minute = 0self._hour += 1if self._hour == 24:self._hour = 0sleep(1)def __str__(self):"""[显示时间]"""return '%02d:%02d:%02d' % (self._hour, self._minute, self._second)def main():"""[主程序入口]"""clock = Clock(9, 11, 57)clock.run()if __name__ == '__main__':main()

二维坐标

from math import sqrtclass Point:"""[二维坐标,用(x,y)表示]"""def __init__(self, x=0, y=0):"""[坐标构造函数]x (int, float, optional): Defaults to 0. [坐标x]y (int, float, optional): Defaults to 0. [坐标y]"""self.x = xself.y = ydef move_to(self, x, y):"""[移动到指定位置]Args:x ([int, float]): [新的坐标x]y ([int, float]): [新的坐标y]"""self.x = xself.y = y def moved_by(self, dx, dy):"""[移动指定的增量]Args:dx ([int, float]): [坐标x的增量]dy ([int, float]): [坐标y的增量]"""self.x += dxself.y += dydef distance_to(self, other):"""[计算到另一个坐标的距离]Args:other ([class Point]): [另一个坐标]"""dx = self.x - other.xdy = self.y - other.yreturn sqrt(dx ** 2 + dy ** 2)def __str__(self):"""[调用print()的时候,调用此方法,for users!]"""return '(%s, %s)' % (str(self.x), str(self.y))def main():p1 = Point(3, 5)p2 = Point()print(p1)print(p2)p2.moved_by(-1, 2)print(p2)print(p1.distance_to(p2))if __name__ == '__main__':main()

用装饰器模拟session,或者说用装饰器实现验证功能

user_session = {'username': None, 'login_status': False}def login_required(func):def wrapper(*args, **kwargs):if user_session['username'] and user_session['login_status']:func(*args, **kwargs)else:print('没有足够权限')return wrapperdef auth_func(func):def wrapper(*args, **kwargs):username = input('用户名: ').strip()password = input('密码: ').strip()if username == 'sb' and password == '123':user_session['username'] = usernameuser_session['login_status'] = passwordfunc(*args, **kwargs)else:print('用户名或者密码错误')return wrapper@auth_func
def index():print('欢迎来到京东')@login_required
def home(name):print('欢迎回家%s' % name)@login_required
def shopping_cart():print('购物车里有 [%s,%s,%s]' % ('袜子', '鞋子', '娃娃'))index()
home('allen')
shopping_cart()

判断是否属于类的方法(method)

def hasmethod(obj, name):return hasattr(obj, name) and isinstance(getattr(obj, name), types.MethodType)

BeautifulSoup提取优化

def get_sub_soup(soup, rules):if isinstance(rules, (list, tuple)):for rule in rules:soup = get_sub_soup(soup, rule)next_sibling = rule.pop("find_next_sibling", None)if soup and next_sibling:soup = soup.find_next_sibling(next_sibling)elif isinstance(rules, dict):temp = rules.pop("find_next_sibling", None)if soup:soup = soup.find(**rules)rules.update(find_next_sibling=temp)return soupdef ismethod(obj, name):return hasattr(obj, name) and isinstance(getattr(obj, name), types.MethodType)def get_soup_attr(obj, attrs):if isinstance(attrs, (list, tuple)):result = objfor attr in attrs:result = get_soup_attr(result, attr)else:if isinstance(obj, dict):result = obj.get(attrs)elif ismethod(obj, attrs):result = getattr(obj, attrs)()elif isinstance(obj, Tag):result = getattr(obj, attrs)else:return objreturn resultdef parse_soup(soup, rules, attrs, default_result=None):""":param soup: soup:param rules: [{'name': 'div'}, {'name': 'a'}]:param attrs: "text" or ["text"] or ["attrs", "href"]:param default_result: '' or []:return:"""result = default_resultsoup = get_sub_soup(soup, rules)if soup:result = get_soup_attr(soup, attrs)return result

完全去除空格

class SpacesRemover(object):"""去除空格"""def __call__(self, s):return ''.join(s.split())def __ror__(self, s):return self(s)remove_spaces = SpacesRemover()

转载于:https://www.cnblogs.com/allen2333/p/9190811.html

Python - 代码片段,Snippets,Gist相关推荐

  1. 13 个非常有用的 Python 代码片段,建议收藏

    大家好,今天我主要来介绍程序当中的通用 Python 代码片段,大家可以收藏.点赞.关注,一起进步吧 废话不多说,我们开始吧,技术交流文末获取 我们先从最常用的数据结构列表开始 №1:将两个列表合并成 ...

  2. 13 个非常有用的 Python 代码片段,建议收藏!

    作者 | 周萝卜 来源 | 萝卜大杂烩 今天我们主要来介绍应用程序当中的通用 Python 代码片段,一起进步吧 Lists Snippets 我们先从最常用的数据结构列表开始 №1:将两个列表合并成 ...

  3. 201207-四步十秒通过VSCode创建Python代码片段Snippet

    如何操作: Step 1: 安装插件Snippet Creator Step 2: 在py文件中编辑好并选中需要的python代码片段 Step 3: 调出控制台,并输入Create Snippet ...

  4. python语言代码片段-有用的Python代码片段

    我列出的这些有用的Python代码片段,为我节省了大量的时间,并且我希望他们也能为你节省一些时间.大多数的这些片段出自寻找解决方案,查找博客和StackOverflow解决类似问题的答案.下面所有的代 ...

  5. 初学者怎样看懂python代码_新手入门必看,最常用的Python代码片段

    对于编程开发人员来讲,Python语法一开始可能看起来很奇怪.如果我们看到Python使用其他编程语言(例如Java)完成常见的工作,那会不会很意思?我们常见的代码片段称为"代码惯用法&qu ...

  6. 运行Python代码片段

    Python自带了一个在终端窗口中运行的解释器,让你无需保存并运行整个程序就能尝试运行Python代码片段. 本文将以如下方式列出代码片段: >>>print("Hello ...

  7. 超常用的Python代码片段 | 备忘单

    「2019 Python开发者日」7折票限时开售!这一次我们依然"只讲技术,拒绝空谈",除了10余位一线Python技术专家的演讲外 ,大会还安排了深度培训实操环节,为开发者们带来 ...

  8. web简易计算器代码_30秒内便能学会的30个超实用Python代码片段

    许多人在数据科学.机器学习.web开发.脚本编写和自动化等领域中都会使用Python,它是一种十分流行的语言. Python流行的部分原因在于简单易学. 本文将简要介绍30个简短的.且能在30秒内掌握 ...

  9. 13个非常有用的Python代码片段

    1:将两个列表合并成一个字典 假设我们在 Python 中有两个列表,我们希望将它们合并为字典形式,其中一个列表的项作为字典的键,另一个作为值.这是在用 Python 编写代码时经常遇到的一个非常常见 ...

最新文章

  1. mac镜像cdr格式_设计常用文件格式!萌新必备
  2. dns-sd._udp.domain. 域名发现 本质和MDNS同
  3. 漫谈WinCE输入法的编写(四)
  4. 判断字符串格式_Blind_pwn之格式化字符串
  5. 以列表形式输出_04 Python之列表、集合和字典的推导式
  6. SAP 电商云 Spartacus UI added-to-cart 的端到端测试源代码解析
  7. 探索 .NET Core 依赖注入的 IServiceProvider
  8. aws ec2 php,如何使用php aws sdk启动和停止ec2实例
  9. Android相关sdk使用
  10. 不要束缚:为什么我们会错过GitHub条纹
  11. Topic model相关文章总结
  12. c语言输入字符串smallbig,为什么输出不了small,这里big和small都是一样的操
  13. k8s中实现自动数据库初始化(mysql,postgresql)
  14. php strpbrk,PHP 字符串
  15. Intellij idea创建(包、文件)javaWeb以及Servlet简单实现(Tomcat)
  16. java页面标签span_span标签跳转新页面
  17. 全连MGRE与星型拓扑MGRE
  18. 自己收藏的两款夹娃娃PHP源码
  19. 弘辽科技:淘宝悄悄公布新规,在电商赛道小步快跑。
  20. button按钮居中

热门文章

  1. ip addr 和 ifconfig
  2. 基于java的摄影爱好者交流网站
  3. Unity 渲染路径理解
  4. 同济大学博士/硕士学位论文LaTex模板的软件安装与环境配置
  5. windows常用快捷命令
  6. 是时候做点东西出来了.
  7. 动联出席2015中国(广州)国际POS机展顶级盛会
  8. 百度地图api result = {“status“:230,“message“:“APP Mcode码校验失败“
  9. Centos7中使用parted快速分区挂载磁盘
  10. python能编plc吗_基于Python的丰炜系列PLC与PC串行通信的实现