第 2 章 变量和简单数据类型

第 2 章 变量和简单数据类型

2.2 变量

message = "Hello World!"

message 就是变量,这个变量存储了一个值。

2.2.1 变量的命名和使用

  • 变量名:字母,数字,下划线。message_1
  • 用下划线分割单词
  • 变量名具有描述性:name_lengthlength_of_persons_name
  • 慎用小写字母i和大写字母O,容易当成数字1和0

2.2.2 使用变量时避免命名错误

2.3 字符串

2.3.1 使用方法修改字符串的大小写

方法跟在字符串后面调用。

name = 'bramble xu'
print(name.title())

输出的结果是Bramble Xu.

  • name.title() : 能把每个单词的首字母变为大写
  • name.upper() : 全是大写
  • name.lower() : 全是小写

2.3.2 合并(拼接)字符串

+号来拼接字符。

first_name = 'bramble'
last_name = 'xu'
full_name = first_name + ' ' + last_name

print('Hello, ' + full_name.title() + '!')

输出结果Hello, Bramble Xu!

2.3.3 使用制表符或换行符来添加空白

  • \t : 制表符
  • \n : 换行符
>>> print("\tPython")
    Python

>>> print("Languages:\n\tPython\n\tC\n\tJavaScript")
Languages:
    Python
    C
    JavaScript

2.3.4 删除空白

在用户登录网站的时候检查用户名是否有空白,删去空白。

  • 'python '.rstrip(): 删除右边空白
  • ' python'.lstrip(): 删除左边空白
  • ' python '.strip(): 删除两边空白

要注意,这里调用strip()方法后,并没有对原本的字符串进行更改。想要永久删除空白,必须把删除操作的结果保存到变量里。

>>> favorite_language = 'python '
❶ >>> favorite_language = favorite_language.rstrip()
  >>> favorite_language
  'python'

2.3.5 使用字符串时避免语法错误

message = 'One of Python's strengths is its diverse community.' 比如这种一句话里有三个单引号,就造成了语法错误。

可以把外围的双引号用单引号代替
message = "One of Python's strengths is its diverse community.“

2.4 数字

2.4.1 整数

需要注意一下除法

在Python 3.0中,’/’总是执行真除法,不管操作数的类型,都会返回包含任何余数的浮点结果;’//’执行Floor除法,截除掉余数并且针对整数操作数返回一个整数,如果有任何一个操作数是浮点数,则返回一个浮点数。

Floor除法:效果等同于math模块中的floor函数:

  • math.floor(x) :返回不大于x的整数
  • 所以当运算数是负数时:结果会向下取整。
>>> 5//3   #1.6666666666666667
1
>>> -5//3
-2

与floor()函数类似的还有很多,比如trunc()函数:

>>> import math
>>> math.trunc(-1.6)
-1
>>> math.trunc(1.6)
1

2.6 Python之禅

>>> import this
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!

相关推荐