2022年 11月 5日

Python中的语法规则

1、注释

Python中有逐行注释和部分注释两种

  1. ##逐行注释
  2. # this is a command
  3. print ('hello world')
  4. ##成段注释
  5. """
  6. this
  7. is
  8. command
  9. """
  10. print ('hello world')
  11. ##运行结果
  12. [root@contral day01]# python3 command
  13. hello world
  14. hello world

2、变量的命名

2.1 命名方式:

和其它语言相似,变量只能含有数字、下换线、字母,且不能以数字开头,不能和关键字重名;

命名的的方式往往有两种,大头命名法和峰值命名:

  1. ##大头命名
  2. FirstName
  3. ##峰值命名
  4. firsTName

2.2 基本类型:

命名过程中不进行类型说明,直接命名,命名时的类型可用type类型进行查看。

  1. ##字符型 str
  2. name = 'linux'
  3. ##整型 int
  4. age = 18
  5. ##长整型 long (该变量只在python2里面有所定义)
  6. date = 1234648965165812352
  7. ##浮点型 float
  8. height = 176.5
  9. weight = 64.5
  10. ##布尔型
  11. gender = true / false
  12. bool(gender) ##有值则为真,无值则为假
  13. ##变量定义也可以通过变量复制进行定义
  14. result = weight * 2

2.3 变量的方式:dir(varname)

  1. ##可以用dir查看变量的方式
  2. In [5]: string = 'welcome to this world'
  3. In [6]: string
  4. Out[6]: 'welcome to this world'
  5. In [7]: dir(string) ##查看变量的方式
  6. Out[7]:
  7. ['__add__',
  8. '__class__',
  9. '__contains__',
  10. '__delattr__',
  11. ....
  12. ##方式的使用
  13. In [9]: string.center(40)
  14. Out[9]: ' welcome to this world '
  15. In [10]: string.center(40,'-') ##.调用方式,括号内放置方式的参数
  16. Out[10]: '---------welcome to this world----------'

【注】此处的所有类型都可作为内置函数,进行转化

  1. ##类型作为内置函数
  2. ##定义类型
  3. In [12]: a = 1
  4. In [13]: b = 2.3
  5. ##直接类型转化
  6. In [16]: int (a)
  7. Out[16]: 1
  8. In [17]: int (b)
  9. Out[17]: 2
  10. In [18]: float (a)
  11. Out[18]: 1.0
  12. In [20]: str (b) ##数字和字符之间的转化,但字符转化不到数字
  13. Out[20]: '2.3'

3、逻辑运算符

  1. ##逻辑运算符
  2. #与 and:表示and前后均成立条件为真(一假为假)
  3. condition1(true) and condition2(true) = ture
  4. condition1(true) and condition2(false) = false
  5. #或 or:表示or条件前后有一个为真即为真(一真为真)
  6. condition1(false) or condition2(true) = ture
  7. condition1(false) or condition2(false) = false
  8. #非 not:表示对当前条件取反
  9. not condition(false) = true
  10. not condition(true) = false