python案例

1.针对数值运算符

水仙花数是指一个 3 位数,它的每个位上的数字的 3次幂之和等于它本身。例如:1^3 + 5^3+ 3^3 = 153。

#水仙花数
# 方法一:

for i in range(100, 1000):
    a = i // 100
    b = (i - a * 100) // 10
    c = (i - a * 100 - b * 10)

    if i == pow(a, 3) + pow(b, 3) + pow(c, 3):  # (a * a * a + b * b * b + c * c * c)
        print(i)

# 方法二:

for i in range(1, 10):
    for j in range(0, 10):
        for k in range(0, 10):
            if i * 100 + j * 10 + k == i ** 3 + j ** 3 + k ** 3:
                print(i * 100 + j * 10 + k)

# 四位自幂数:

for i in range(1000, 10000):
    a = int(i / 1000)
    b = int(i % 1000 / 100)
    c = int(i % 100 / 10)
    d = int(i % 10)
    if pow(a, 4) + pow(b, 4) + pow(c, 4) + pow(d, 4) == i:
        print(i)

 

2.针对类的实现

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

students = []
students.append(Student("王一", 18))
students.append(Student("李二", 19))
students.append(Student("王三", 20))
students.append(Student("张四", 21))
students.append(Student("王五", 22))
students.append(Student("赵六", 23))
students.append(Student("王七", 24))
students.append(Student("孙八", 25))
students.append(Student("王九", 26))
students.append(Student("刘十", 27))

wang_students = []
for student in students:
    if student.name.startswith(""):
        wang_students.append(student)

for student in wang_students:
    print(student.name)

 

3.针对字符串

 

进队条

import time
width=50
print("==============================开始下载==============================")
for i in range(101):
    filled_width = int((width * i)/100)
    empth_width=width-filled_width
    bar='*'*filled_width+'.'*empth_width
    print("\r%d%%[%s]"%(i,bar),end='')
    time.sleep(0.1)

 

4.针对函数的自我调用

输出十进制数的相应二进制编码

def change(n):
    result="0"
    if n ==0:
        return result
    else:
        result = change(n//2)
        return result +str(n%2)
num = int(input("请输入一个十进制数字:"))
print(change(num))

 

posted @ 2024-03-24 21:19  szmtjs10  阅读(6)  评论(0编辑  收藏  举报