variables_operators_basics.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. """variables_operators_basics.py - Python 变量与运算符基础示例
  2. 涵盖:变量定义、命名规则、赋值、类型推断、常见算术运算符、比较运算符、
  3. 逻辑运算符、赋值运算符、成员运算符、身份运算符,以及运算优先级说明。
  4. """
  5. def main():
  6. # 1. 变量:用来存储数据的标识符
  7. name = "Alice"
  8. age = 18
  9. height = 1.72
  10. is_student = True
  11. print("name ->", name)
  12. print("age ->", age)
  13. print("height ->", height)
  14. print("is_student ->", is_student)
  15. # 2. 变量命名规则
  16. # - 只能包含字母、数字、下划线
  17. # - 不能以数字开头
  18. # - 不能使用 Python 关键字
  19. # - 建议使用 snake_case
  20. user_name = "Bob"
  21. max_score = 100
  22. print("user_name ->", user_name)
  23. print("max_score ->", max_score)
  24. # 3. 多变量赋值
  25. a, b, c = 10, 20, 30
  26. print("a, b, c ->", a, b, c)
  27. x = y = 100
  28. print("x == y ->", x == y)
  29. # 4. 动态类型:变量不需要声明类型,赋值时自动决定类型
  30. num = 10
  31. num = "ten"
  32. print("num after reassignment ->", num)
  33. # 5. 算术运算符
  34. print("5 + 3 ->", 5 + 3)
  35. print("5 - 3 ->", 5 - 3)
  36. print("5 * 3 ->", 5 * 3)
  37. print("10 / 3 ->", 10 / 3) # 浮点除法
  38. print("10 // 3 ->", 10 // 3) # 整除
  39. print("10 % 3 ->", 10 % 3) # 取余
  40. print("2 ** 3 ->", 2 ** 3) # 幂运算
  41. # 6. 比较运算符
  42. print("5 > 3 ->", 5 > 3)
  43. print("5 == 3 ->", 5 == 3)
  44. print("5 != 3 ->", 5 != 3)
  45. print("5 >= 3 ->", 5 >= 3)
  46. print("5 <= 3 ->", 5 <= 3)
  47. # 7. 逻辑运算符
  48. print("True and False ->", True and False)
  49. print("True or False ->", True or False)
  50. print("not True ->", not True)
  51. # 8. 赋值运算符
  52. total = 10
  53. total += 5 # total = total + 5
  54. total *= 2 # total = total * 2
  55. print("total ->", total)
  56. # 9. 身份运算符:判断两个对象是否为同一个对象
  57. p = [1, 2]
  58. q = p
  59. r = [1, 2]
  60. print("p is q ->", p is q)
  61. print("p is r ->", p is r)
  62. # 10. 成员运算符:判断元素是否在序列里
  63. fruits = ["apple", "banana", "orange"]
  64. print("'apple' in fruits ->", 'apple' in fruits)
  65. print("'pear' not in fruits ->", 'pear' not in fruits)
  66. # 11. 位运算符(进阶,了解即可)
  67. print("5 & 3 ->", 5 & 3)
  68. print("5 | 3 ->", 5 | 3)
  69. print("5 ^ 3 ->", 5 ^ 3)
  70. print("~5 ->", ~5)
  71. # 12. 运算优先级(从高到低)
  72. # 一般顺序:括号 > 幂运算 > 乘除取模 > 加减 > 比较 > not > and > or
  73. result = 10 + 3 * 2 ** 2
  74. print("10 + 3 * 2 ** 2 ->", result)
  75. # 13. 变量的作用
  76. # - 存储数据
  77. # - 程序中用于表达、计算、判断
  78. # - 让代码更清晰、可维护
  79. # 14. 小结
  80. # Python 中变量没有固定类型,运算符用于进行计算、比较、逻辑判断和赋值。
  81. # 根据需要选择合适的运算符即可。
  82. # if __name__ == '__main__':
  83. # main()
  84. p = [1, 2]
  85. q = p
  86. r = [1, 2]
  87. print("p is q ->", p is q)
  88. print("p is r ->", p is r)
  89. print("p == r ->", p == r)