一些基础的python小程序

1.求下列数奇偶分数:

list1 = [1,2,3,4,5,6,7,8,9,10]

# 先创建两个空列表

jishu = []

oushu = []

# 使用for循环迭代list1一一取出进行判断

for i in list1:

# 取出的数除以2的余数等于0加入偶数列表,否则是奇数

     if i % 2 == 0: 

         oushu.append(i)

     else:

         jishu.append(i)       

 # 打印新列表

print(jishu)

print(oushu)

 

2.求1-100的偶数和:

sum = 0

for i in range(0,101):

    if i % 2 ==0:

        sum += i

print(sum)

 

3.类和对象 :

class Cat:

     """

     定义一个猫类

     """

     def __init__(self, name, age, color):

         self.name = name

         self.age = age

         self.color = color

         print("大家好,我叫{},我现在{}岁,我的毛色是{}".format(self.name, self.age, self.color))

     def run(self):

         print("我会跑步")

     def sleep(self):

         print("我会睡觉")

     def say(self):

         print("我会叫")

       

a_cat = Cat("小咪", 2, "黑色")

a_cat.run()

a_cat.sleep()

a_cat.say()

 

4.去重 :

# 1.方法一

list1 = [3,3,3,4,5,3]

set1 = set(list1)

print(set1)

# 2.方法2

new_list = [i for i in set1]

print(new_list)

# 3.方法3 

list1 = [3,3,3,4,5,3]

set1 = set(list1)

new_list = []

for i in set1:

     new_list.append(i)

print(new_list)

 

5. if ,elif,else简单使用: 

score = int(input("请输入分数:"))

if score > 90:

     print("A")

 elif score > 80:

     print("B")

elif score > 70:

     print("C")

 elif score > 60:  

     print("D")

 else:

     print("E")

 

 6.算数运算:

class calculation():

         """

         算术运算

         """

         def __init__(self, A, B):

                   self.A = A

                   self.B = B

                  

         def sum(self):

                   """

                   计算加法

                   """

                   return self.A + self.B

        

         def sub(self):

                   """

                   计算减法

                   """

                   return round((self.A - self.B),2)

        

         def multi(self):

                   """

                   计算乘法

                   """

                   return self.A * self.B

        

         def div(self):

                   """

                   计算除法

                   """

                   try:

                            return round((self.A / self.B),2)

                   except ZeroDivisionError:

                            return("0除错误,分母不能为0!")

        

                  

c = calculation(10, 0)

print(c.sum())

print(c.sub())   

print(c.multi())

print(c.div())    

 

 

    

一些基础的python小程序

上一篇:小程序---电影商城---地图组件


下一篇:使用php进行微信小程序图片安全验证