Python(基于python3)
-
hello world
print("hello world")
- 变量
text = "hello world!"
print(text)
这里添加了一个变量text,变量text中存储了一个值-----即与变量相关联的信息。上述的代码中,变量text存储的是文本hello world!
2.1 变量的命名和使用
命名规则:
- 变量名只能包含字母、数字和下划线。变量名可以以字母或者下划线开头,但不能以数字开头。
- 变量名不能包含空格,但可以使用下划线来分隔其中的单词。
- 不能使用python关键字和函数名作为变量名。
- 变量名应既短又具有描述性。
- 尽量不用使用小写字母i和大写字母O,因为他们可能被人错看成数字1和0.
- 字符串
字符串就是一系列的字符。在python中,用引号括起来的都是字符串,其中的引号可以使单引号,也可以是双引号。
3.1 使用方法修改字符串的大小写
text = "hello world!"
print(text)
print(text.title())
输出结果:
hello world!
Hello World!
3.2 合并(拼接)字符串
使用 + 进行拼接
first_word = "zhangsan"
last_word = "lisi"
full_word = first_word + "" + last_word
print(full_word)
输出结果:
zhangsanlisi
3.3 使用制表符或换行符来添加空白
这里的空白泛指任何非打印字符,如空格、制表符和换行符。
\t 4个空格
print("space")
print("\tspace")
输出结果:
space
space
\n 换行
print("space")
print("\nspace")
输出结果:
space
space
3.4 删除空白
rstrip() 删除字符串末尾多余的空白
space_nothing = "space1"
space_with_space = "space "
print(space_nothing)
print(space_with_space+"1")
print(space_with_space.rstrip()+"1")
print(space_with_space+"1")
输出结果:
space
space1
space 1
space1
space 1
从上面的代码可以看出,retrip()方法只是暂时将字符串引用末尾的空白删除了,但是没有修改原来字符串的引用。
lstrip() 删除字符串开头多余的空白
strip() 删除字符串开头和末尾的空表
- 数字
4.1 整数
基础运算:
print(2+3)
print(2-3)
print(2*3)
print(2/3)
# 平方
print(2**3)
输出结果:
5
-1
6
0.6666666666666666
8
4.2 浮点数
python将带小数点的数字都称为浮点数。
浮点数的基本运算:
# 浮点数
print("浮点数")
print(2.54 + 3.63)
print(2.54 - 3.63)
print(2.54 * 3.63)
print(2.54 / 3.63)
输出结果:
浮点数
6.17
-1.0899999999999999
9.2202
0.6997245179063362
需要注意的是,结果包含的小数位数可能是不确定的。
4.3 使用函数str()避免类型错误
在python中,需要显式的指出希望某个整数用作字符串,可以使用函数str(),它让python将非字符串表示为字符串。
# str()
age = 24
birthday_word = "happy " + str(age) + "rd birthday"
print(birthday_word.title())
输出结果:
Happy 24Rd Birthday
- python中的注释
在python中,注释用井号#标识。井号后面的内容都会被Python解释器忽略。
# 这里是注释
print("你看没有打印注释的内容吧")
- python之禅
python之禅指的是编写优秀python代码的知道原则,只需要在解释器中执行命令import this,就可以获取到这些原则。
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!
扫码_搜索联合传播样式-标准色版-压缩版.jpg