1.求下列數奇偶分數:app
list1 = [1,2,3,4,5,6,7,8,9,10]orm
# 先建立兩個空列表對象
jishu = []input
oushu = []it
# 使用for循環迭代list1一一取出進行判斷io
for i in list1:for循環
# 取出的數除以2的餘數等於0加入偶數列表,不然是奇數form
if i % 2 == 0: class
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())