python的小程式 一些基礎的python小程式

2021-10-10 10:51:30 字數 1965 閱讀 3197

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:

else:

# 列印新列表

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

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:

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練習小程式

程式1 輸出某個範圍內的阿姆斯特朗數 阿姆斯特朗數,乙個n位數的每位數字的n次方相加等於此數,例如153是個3位數,1的3次方加5的3次方加3的3次方等於153 while true num low int input 請輸入範圍下限 範圍下限 num hig int input 請輸入範圍上限 範...

一些C 的小程式(一)

輸出hello word include using namespace std int main 查詢int的空間大小 include using namespace std int main 定義列舉型別,輸出比賽結果 include using namespace std enum gamer...

一些C C 的演算法小程式

1,列印ascii字元 include include using namespace std class table void ascii protected int i void table ascii printf the number of 0 in the end of 100 is d....