Python programming exercises (5)

1. Write a decimal number and convert it into a binary number (using the function method)

def Dec2Bin(dec):
    result = ''

    if dec:
        result = Dec2Bin(dec // 2)
        return result + str(dec % 2)
    else:
        return result


print(Dec2Bin(15))

 2. Write a decimal number, convert it to a hexadecimal number, and use the hex() function

decimal = 123456
hexadecimal = hex(decimal)[2:]
print(hexadecimal)

3. Write a program to display all leap years from 2001 to 2100. Each line displays 10 leap years. These years are separated by a space.

cont = 0
print('21世纪中的闰年有:')
for i in range(2001, 2101):
    if i % 4 == 0 and i % 100 != 0 or i % 400 == 0:
        print(i, end=' ')
        cont = cont + 1
        if cont % 10 == 0:
            print('\n')

 4. Write a function to calculate the sum of each digit of an integer.

def sumDigits(n):
    num = 0
    for i in range(len(str(n))):
        num += n % 10
        n = n // 10
    return num


print(sumDigits(234))

 5. Convert between Celsius and Fahrenheit

c = float(input("请输入摄氏温度:"))
f = c*1.8+32
print(f"对应的华氏温度为:{f:.1f}")

f = float(input("请输入华氏温度:"))
c = 5.0/9.0*(f-32)
print(f"对应的摄氏温度为:{c:.1f}")

 6. Write a function to display an integer in reverse

def reverse_int(num):
    return int(str(num)[::-1])


print(reverse_int(3456))

 7. Write a function to calculate the following sequence m(i)=1/2+2/3+....+i/(i+1)

def caculate(n):
    sum = 0
    for x in range(n, 0, -1):
        sum = sum + x / (x + 1)

    print("sum=", sum)


caculate(20)

 8. Use the def area function to write a program, input the values ​​of the three sides of the triangle, and calculate the area if the input is valid, otherwise the input is invalid.

a = float(input("输入第一条边长:"))
b = float(input("输入第二条边长:"))
c = float(input("输入第三条边长:"))


def area(a, b, c):
    p = (a + b + c) / 2
    area = (p * (p - a) * (p - b) * (p - c)) ** 0.5
    return area


if a + b < c or a + c < b or b + c < a:
    print("输入无效,请重新输入")
else:
    print("三角形的面积为: %0.2f" % area(a, b, c))

 

9. Determine whether an integer is a palindrome

number = int(input("输入一个整数:"))


def isPalindrome(number):
    revNum = reverse(number)
    return number == revNum


def reverse(number):
    revNum = 0
    while number != 0:
        revNum = revNum * 10 + number % 10
        number //= 10
    return revNum


print(isPalindrome(number))

 

 

Guess you like

Origin blog.csdn.net/weixin_62304542/article/details/130250712