跳轉到內容

程式設計基礎/變數示例 Python

來自華夏公益教科書

以下示例演示了 Python 中的資料型別、算術運算和輸入。

資料型別

[編輯 | 編輯原始碼]
 # This program demonstrates variables, literal constants, and data types.
 
 i = 1234567890
 f = 1.23456789012345
 s = "string"
 b = True
 
 print("Integer i =", i)
 print("Float f =", f)
 print("String s =", s)
 print("Boolean b =", b)
Integer i = 1234567890
Float f = 1.23456789012345
String s = string
Boolean b = true

每個程式碼元素代表

  • # 開始註釋
  • i = , d = , s =, b = 將字面值分配給相應的變數
  • print() 呼叫 print 函式
 # This program demonstrates arithmetic operations.
 
 a = 3
 b = 2
 
 print("a =", a)
 print("b =", b)
 print("a + b =", (a + b))
 print("a - b =", (a - b))
 print("a * b =", a * b)
 print("a / b =", a / b)
 print("a % b =", (a % b))
a = 3
b = 2
a + b = 5
a - b = 1
a * b = 6
a / b = 1.5
a % b = 1

每個新的程式碼元素代表

  • +, -, *, /, and % 分別代表加法、減法、乘法、除法和模運算。
 # This program converts an input Fahrenheit temperature to Celsius.
 
 print("Enter Fahrenheit temperature:")
 fahrenheit = float(input())
 
 celsius = (fahrenheit - 32) * 5 / 9
 
 print(str(fahrenheit) + "° Fahrenheit is " + str(celsius) + "° Celsius")
Enter Fahrenheit temperature:
 100
100.0° Fahrenheit is 37.77777777777778° Celsius

每個新的程式碼元素代表

  • input() 從標準輸入讀取下一行
  • float() 將輸入轉換為浮點數

參考文獻

[編輯 | 編輯原始碼]
華夏公益教科書