程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python tips

編輯:Python

1. Simple exception handling

def division(a,b):
try:
res = round(a/b,2)
except Exception as e:
print(f" because {
e}, So it can't run ")
else:
print(f"{
a}/{
b}={
res}")
finally:
print("*"*20," End of calculation ")
if __name__ == '__main__':
division(3,5)
division(3,0)

Running results :

3/5=0.6
******************** End of calculation
because division by zero, So it can't run
******************** End of calculation

2. Representation and operation of fractions

from fractions import Fraction
""" Addition and multiplication of fractions Fraction( molecular , The denominator )"""
print(Fraction(1,2)+Fraction(1,4),end="\t\t")
print(Fraction(1,2)*Fraction(1,4))
""" 1. Sum of fractional sequence """
def fraction_sum(num):
sum1 = 0
first1 = ""
for k in range(2, num+2, 2):
sum1 = sum1+Fraction(1, k)
first1 = first1+"+"+str(Fraction(1, k))
first1 = first1[1:]
print(f"{
first1} = {
sum1}")
if __name__ == '__main__':
fraction_sum(4)
fraction_sum(6)

Running results :

3/4 1/8
1/2 + 1/4 = 3/4
1/2 + 1/4 + 1/6 = 11/12

3. String de duplication and sorting

def str_distinct_sort(str1):
list2 = list(str1)# Convert to list 
print(list2)
list1 = list(set(list2))# List element de duplication 
print(list1)
list1.sort()# Sort list elements 
print(list1)
str2 = "".join(list1)# List to string 
print(" final result {}".format(str2))
if __name__ == '__main__':
str_distinct_sort("Welcome to Python!")

Running results :

['W', 'e', 'l', 'c', 'o', 'm', 'e', ' ', 't', 'o', ' ', 'P', 'y', 't', 'h', 'o', 'n', '!']
['t', ' ', 'h', 'n', 'c', 'o', 'P', '!', 'e', 'y', 'm', 'W', 'l']
[' ', '!', 'P', 'W', 'c', 'e', 'h', 'l', 'm', 'n', 'o', 't', 'y']
final result !PWcehlmnoty

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved