HW01 Python 環境建立和Hello World 1. NotebookLM 2. 3. 學習卡 和測驗 4. 這裡有一個最基礎、非常適合入門的 Python 程式: 猜數字小遊戲 。 這個程式結合了 變數 、 條件判斷 (if/else) 、 迴圈 (while) 以及 模組引用 (import) 等核心概念: Python import random # 產生一個 1 到 100 之間的隨機整數 answer = random.randint( 1 , 100 ) count = 0 print( "=== 猜數字遊戲開始!===" ) print( "我已經想好了一個 1 到 100 之間的數字,來猜猜看吧!\n" ) while True : try : # 取得使用者輸入的數字 guess = int ( input ( "請輸入一個數字:" )) count += 1 # 判斷結果 if guess < answer: print( "太小囉!再試一次。" ) elif guess > answer: print( "太大囉!再試一次。" ) else : print( f"恭喜你答對了!答案就是 {answer} 。" ) print( f"你總共猜了 {count} 次。" ) break # 猜對了,跳出迴圈結束程式 except ValueError: print( "請輸入有效的整數數字!" ) 程式重點解析: import random :載入 Python 內建的隨機函式庫,用來產生隨機數字。 input() :讓使用者從終端機輸入資料。預設輸入會是文字型態,所以用 int() 將它轉成整數。 while True: :建立一個持續運行...
這個網誌中的熱門文章
HW02 運算子表達式 1. NotebookLM 2. 3. 學習卡 和測驗 4.115103122%7+1=2 # 🔢 4-Digit Number Digit Sum Calculator A lightweight, beginner-friendly Python script that prompts the user for a 4-digit integer, extracts each individual digit using basic mathematical operators, and calculates their sum. --- ## 🚀 Features * **Mathematical Extraction:** Uses modulo (`%`) and integer division (`//`) to isolate each digit without converting the number into a string. * **Interactive Prompt:** Takes live user input via the console. * **Instant Calculation:** Computes and displays the sum of all four digits immediately. --- ## 💻 Code ```python num = eval(input('Enter 4 digit number: ')) print('Entered number is:', num) r1 = num % 10 q1 = num // 10 r2 = q1 % 10 q2 = q1 // 10 r3 = q2 % 10 q3 = q2 // 10 r4 = q3 % 10 print('Sum of all the digits within number', num, 'is :', (r1 + r2 + r3 + r4))



留言
張貼留言