python | 变量和简单的数据类型

第二章

如何使用变量
如何创建描述性变量名
如何消除名称错误和语法错误
什么是字符串
如何使用小写、大写、首字母大写的方式显示字符串
如何使用空白来显示整洁的输出
如何剔除字符串中多余的空白
如何使用整数和浮点数
使用数值数据时需要注意的意外行为
如何编写说明注释

变量和简单数据类型

变量
  1. 变量的命名和使用
    1. 变量命名规则
      1. 变量名只包含字母、数字、下划线,变量名可以用字母或者下划线开头,但不能以数字开头
      2. 变量名不能包括空格,可以使用下划线间隔单词
      3. 不能用 Python 关键字和函数名作为变量名
      4. 变量名应该简短又具有描述性
      5. 慎用字母 o (因为容易和数字 0 混淆
字符串
字符串是一系列字符,在 python 中,用引号括起来的都是字符串,其中引号可以是单引号也可以是双引号
  1. 使用方法修改字符串的大小写

    1. 将每个单词的首字母改为大写 title()

      name = "li zn cu"
      print(name.title())
      
      Li Zn Cu
      
    2. 将字符串全部变为小写 lower()

    3. 将字符串全部变成大写 upper()

      name = "Li Zn Cu"
      print(name.lower())
      print(name.upper())
      
      li zn cu
      LI ZN CU
      
  2. 合并(拼接)字符串

    • 使用 + 合并字符串
      first_name = "Li"
      last_name = "zncu"
      fulll_name = first_name + " " + last_name
      print(full_name)
      
      Li zncu
      
  3. 使用制表符或者换行符添加空白

    1. 制表符: \t
    2. 换行符: \n
  4. 删除空白

    • python能够找出字符串开头和末尾多余的空白
    • 要确保字符串末尾没有空白可以使用方法 rstrip()
    • 要确保字符串开头没有空白可以使用方法 lstrip()
    • 要确保字符串两端没有空白可以使用方法 strip()
数字
  1. 整数

    1. python 中可以对python进行加(+)、减(-)、乘(*)、除(/)运算
    2. python 中可以使用 ** 表示幂运算
    >>> 3 ** 2
    9
    
    >>>3 ** 3
    27
    
  2. 浮点数

    1. python 将待小数点的数字都称为浮点数
    2. 浮点数进行运算后,结果包含的小数位数可能是不确定的,所有语言都存在这种问题, python 会尽可能地精准表示结果
  3. 使用 str() 避免类型错误

    • 使用 str() 可以告知 python 你希望将变量的类型转为字符串进行接下来的操作
注释
注释是让你能够使用自然语言在程序中添加说明的东西
  1. 编写注释的方法
    • 使用 #
      #一个注释
      
  2. 该编写什么样的注释
    • 编写注释的主要目的是阐述代码要做什么,以及是如何做的
python 之禅

在解释器中输入 import this 就可以获得编写优秀 python 代码的指导原则

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值