import random
def count_even_digits(student_id):
digits = str(student_id)[1:5] # 取得學號第2到第5位的數字
random_digits = random.sample(digits, k=3) # 從這些數字中隨機取樣3個數字
even_count = sum(int(digit) % 2 == 0 for digit in random_digits) # 計算偶數的個數
return even_count
student_id = input("請輸入您的8位數學號:")
even_count = count_even_digits(student_id)
print("隨機產生的數字中含有", even_count, "個偶數")
import random
class Module:
def __init__(self, student_id: str) -> None:
self.student_id = student_id
def get_random_value(self) -> str:
return random.choice(self.student_id[1:5])
def get_numbers_even(self) -> int:
even_count = sum(1 for digit in self.student_id if int(digit) % 2 == 0)
return even_count
M = Module('12345678') # 輸入自己的學號
random_value = M.get_random_value()
nums_even = M.get_numbers_even()