Description
Code snippets from the Internet or written by yourself.
Fahrenheit temperature to Celsius
"""将华氏温度转换为摄氏温度F = 1.8C + 32Version: 0.1Author: 骆昊Date: 2018-02-27"""f = float(input(‘请输入华氏温度: ‘))c = (f - 32) / 1.8print(‘%.1f华氏度 = %.1f摄氏度‘ % (f, c))
Calculate the perimeter and area of the radius of the input circle
"""输入半径计算圆的周长和面积Version: 0.1Author: 骆昊Date: 2018-02-27"""import mathradius = float(input(‘请输入圆的半径: ‘))perimeter = 2 * math.pi * radiusarea = math.pi * radius * radiusprint(‘周长: %.2f‘ % perimeter)print(‘面积: %.2f‘ % area)
Enter the year to determine if it is a leap
"""输入年份 如果是闰年输出True 否则输出FalseVersion: 0.1Author: 骆昊Date: 2018-02-27"""year = int(input(‘请输入年份: ‘))# 如果代码太长写成一行不便于阅读 可以使用\或()折行is_leap = (year % 4 == 0 and year % 100 != 0 or year % 400 == 0)print(is_leap)
Imperial units are interchangeable with metric units
"""英制单位英寸和公制单位厘米互换Version: 0.1Author: 骆昊Date: 2018-02-28"""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(‘请输入有效的单位‘)
Roll the dice decide what to do
"""掷骰子决定做什么事情Version: 0.1Author: 骆昊Date: 2018-02-28"""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)
Percentile grade system
"""百分制成绩转等级制成绩90分以上 --> A80分~89分 --> B70分~79分 --> C60分~69分 --> D60分以下 --> EVersion: 0.1Author: 骆昊Date: 2018-02-28"""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)
Enter three sides long if you can make a triangle, calculate the perimeter and area.
"""判断输入的边长能否构成三角形如果能则计算出三角形的周长和面积Version: 0.1Author: 骆昊Date: 2018-02-28"""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) / 2 area = math.sqrt(p * (p - a) * (p - b) * (p - c)) print(‘面积: %f‘ % (area))else: print(‘不能构成三角形‘)
The above code uses the SQRT function of the math module to calculate the square root. The formula for calculating the triangular area with the edge length is called the Helen formula.
Implement a personal income tax calculator
"""输入月收入和五险一金计算个人所得税Version: 0.1Author: 骆昊Date: 2018-02-28"""salary = float(input(‘本月收入: ‘))insurance = float(input(‘五险一金: ‘))diff = salary - insurance - 3500if diff <= 0: rate = 0 deduction = 0elif diff < 1500: rate = 0.03 deduction = 0elif diff < 4500: rate = 0.1 deduction = 105elif diff < 9000: rate = 0.2 deduction = 555elif diff < 35000: rate = 0.25 deduction = 1005elif diff < 55000: rate = 0.3 deduction = 2755elif diff < 80000: rate = 0.35 deduction = 5505else: rate = 0.45 deduction = 13505tax = abs(diff * rate - deduction)print(‘个人所得税: ¥%.2f元‘ % tax)print(‘实际到手收入: ¥%.2f元‘ % (diff + 3500 - tax))
Enter a number to determine if it is prime
"""输入一个正整数判断它是不是素数Version: 0.1Author: 骆昊Date: 2018-03-01"""from math import sqrtnum = int(input(‘请输入一个正整数: ‘))end = int(sqrt(num))is_prime = Truefor x in range(2, end + 1): if num % x == 0: is_prime = False breakif is_prime and num != 1: print(‘%d是素数‘ % num)else: print(‘%d不是素数‘ % num)
Enter two positive integers to calculate greatest common divisor and least common multiple
"""输入两个正整数计算最大公约数和最小公倍数Version: 0.1Author: 骆昊Date: 2018-03-01"""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
Print triangle pattern
"""打印各种三角形图案*************** * ** *** ********* * *** ***** ****************Version: 0.1Author: 骆昊Date: 2018-03-01"""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()
The function of calculating greatest common divisor and least common multiple
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)
A function that determines whether a number is a palindrome number
def is_palindrome(num): temp = num total = 0 while temp > 0: total = total * 10 + temp % 10 temp //= 10 return total == num
A function that determines whether a number is prime
def is_prime(num): for factor in range(2, num): if num % factor == 0: return False return True if num != 1 else False
Write a program to determine if the positive integer input is a palindrome
if __name__ == ‘__main__‘: num = int(input(‘请输入正整数: ‘)) if is_palindrome(num) and is_prime(num): print(‘%d是回文素数‘ % num)
Display marquee text on the screen
import osimport 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()
Design a function to generate a specified length of the verification code, the verification code is composed of uppercase and lowercase letters and numbers
import randomdef generate_code(code_len=4): """ 生成指定长度的验证码 :param code_len: 验证码的长度(默认4个字符) :return: 由大小写英文字母和数字构成的随机验证码 """ all_chars = ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ‘ last_pos = len(all_chars) - 1 code = ‘‘ for _ in range(code_len): index = random.randint(0, last_pos) code += all_chars[index] return code
Design a function to return the suffix name of the given file name
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 + 1 return filename[index:] else: return ‘‘
Design a function to return the value of the largest and second most important elements in the passed-in list
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 = m1 m1 = x[index] elif x[index] > m2: m2 = x[index] return m1, m2
Calculates the day of the year that is specified
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 = 0 for 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()
Print Yang Hui triangle
def main(): num = int(input(‘Number of rows: ‘)) yh = [[]] * num for 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] = 1 else: yh[row][col] = yh[row - 1][col] + yh[row - 1][col - 1] print(yh[row][col], end=‘\t‘) print()if __name__ == ‘__main__‘: main()
Color Ball Select number
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()
You can use the sample function of the random module to implement selecting N elements from a list that are not duplicates.
Joseph Ring Question
"""《幸运的基督徒》有15个基督徒和15个非基督徒在海上遇险,为了能让一部分人活下来不得不将其中15个人扔到海里面去,有个人想了个办法就是大家围成一个圈,由某个人开始从1报数,报到9的人就扔到海里面,他后面的人接着从1开始报数,报到9的人继续扔到海里面,直到扔掉15个人。由于上帝的保佑,15个基督徒都幸免于难,问这些人最开始是怎么站的,哪些位置是基督徒哪些位置是非基督徒。"""def main(): persons = [True] * 30 counter, index, number = 0, 0, 0 while counter < 15: if persons[index]: number += 1 if number == 9: persons[index] = False counter += 1 number = 0 index += 1 index %= 30 for person in persons: print(‘基‘ if person else ‘非‘, end=‘‘)if __name__ == ‘__main__‘: main()
Python-code snippet, snippets,gist