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