假設有 x = 3 y = 4 求 2x + y 為多少? |
1 2 3 4 5 6 7 8 9 10 11 | # 注意:透過 input 所接收的內容, Python 都視為是 "字串" # 需藉由 int() 將文字轉換成可運算的數字; int 就是英文的 整數(integer) 的縮寫 x = int ( input ( '請輸入 x 的值:' )) y = int ( input ( '請輸入 y 的值:' )) # 為了讓人閱讀舒服,在螢幕上輸出一行空白 print ( '\n' ) print ( '2x + y = ' , 2 * x + y) |
D:\practice>python practice3.py 請輸入 x 的值:3 請輸入 y 的值:7 2x + y = 13 |
1 2 3 4 5 6 7 8 | name = input ( '請輸入名字:' ) age = int ( input ( '請輸入年齡:' )) # 為了讓人閱讀舒服,在螢幕上輸入一行空白 print ( '\n' ) print ( '10 年後, ' + name + ' 將是 ' + str (age + 10 ) + ' 歲' ) # str() 將數字轉換成字串; str 就是英文的 字串(string) 的縮寫 |
D:\practice>python practice4.py 請輸入名字:john 請輸入年齡:18 10 年後, john 將是 28 歲 |
1 2 3 4 5 6 7 8 | name age Age AGE _tel HomeTel # 也可以用幾個字組成一個變數名稱, 一目瞭然, 知道其所代表的意思 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | age = 1 Age = 2 AGE = 3 print ( 'age 的值為 ' + str (age)) print ( 'Age 的值為 ' + str (Age)) print ( 'AGE 的值為 ' + str (AGE)) # 執行結果 age 的值為 1 Age 的值為 2 AGE 的值為 3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | str1 = 'abc' str2 = 'def' # 字串的相加就是把兩個字串連接起來 print ( 'str1 + str2 的結果為 ' + (str1 + str2)) print ( '\n' ) # 將兩個字串相加的結果存入新的變數 str3 str3 = str1 + str2 print ( 'str3 的值為 ' + str3) print ( '\n' ) # 字串的乘法 str3 = str1 * 4 print ( 'str1 * 4 = ' + str3) print ( '\n' ) # 字串的第一個字,也就是起始位置是 0 str4 = 'abcdefghijk' print ( 'str4 的第 1 個字是 ' + str4[ 0 ]) print ( 'str4 的第 5 個字是 ' + str4[ 4 ]) # 取出第 1~6 個字 print ( 'str4 的第 1~6 個字是 ' + str4[: 6 ]) # 取出第 7 個字到最後一個字 print ( 'str4 的第 7 個字到最後一個字是 ' + str4[ 6 :]) # 取出第 4~8 個字 print ( 'str4 的第 4~8 個字是 ' + str4[ 3 : 8 ]) print ( '\n' ) # 字串的運算沒有 減法, 下面的寫法會出錯 str3 = str1 - str2 # 在程式出錯的地方之後的程式碼, 都不會被 Python 執行 print ( '程式有錯誤喔' ) |
D:\practice>python practice5.py str1 + str2 的結果為 abcdef str3 的值為 abcdef str1 * 4 = abcabcabcabc str4 的第 1 個字是 a str4 的第 5 個字是 e str4 的第 1~6 個字是 abcdef str4 的第 7 個字到最後一個字是 ghijk str4 的第 4~8 個字是 defgh Traceback (most recent call last): File "practice5.py" , line 32, in <module> ← 可以從錯誤警示知道有問題的程式碼在哪一行 str3 = str1 - str2 TypeError: unsupported operand type (s) for -: 'str' and 'str' </module> |
False class finally is return None continue for lambda try True def from nonlocal while and del global not with as elif if or yield assert else import pass break except in raise |
1 2 3 4 5 | PI = 3.14159 # 圓周率 ABSOLUTE_ZERO = - 273.15 # 絕對零度 |