内容简介:
Python会自动确定变量数据类型。变量在其他地方使用之前仅需要赋值。
数值
>>> num1 = 7
>>> num2 = 42
>>> total = num1 + num2
>>> print(total)
49
>>> total
49
# 对整数精度没有限制,仅受限于可分配的内存
>>> 34 ** 32
10170102859315411774579628461341138023025901305856
# 使用单个 / (除法)会返回浮点结果
>>> 9 / 5
1.8
# 使用两个 / (整除)仅返回整数部分(没有取舍)
>>> 9 // 5
1
>>> 9 % 5
4>>> appx_pi = 22 / 7
>>> appx_pi
3.142857142857143
>>> area = 42.16
>>> appx_pi + area
45.30285714285714
>>> num1
7
>>> num1 + area
49.16>>> sci_num1 = 3.982e5
>>> sci_num2 = 9.32e-1
>>> sci_num1 + sci_num2
398200.932
>>> 2.13e21 + 5.23e22
5.443e+220b或0B前缀表示0o或0O前缀表示0x或0X前缀表示>>> bin_num = 0b101
>>> oct_num = 0o12
>>> hex_num = 0xF
>>> bin_num
5
>>> oct_num
10
>>> hex_num
15
>>> oct_num + hex_num
25_分隔让数字更具有可读性>>> 1_000_000
1000000
>>> 1_00.3_352
100.3352
>>> 0xff_ab1
1047217
# f-strings格式在后面章节解释
>>> num = 34 ** 32
>>> print(f'{num:_}')
10_170_102_859_315_411_774_579_628_461_341_138_023_025_901_305_856进一步阅读
\进行反义操作:跳过属于字符串本身的引号>>> str1 = 'This is a string'
>>> str1
'This is a string'
>>> greeting = "Hello World!"
>>> greeting
'Hello World!'
>>> weather = "It's a nice and warm day"
>>> weather
"It's a nice and warm day"
>>> print(weather)
It's a nice and warm day
>>> weather = 'It\'s a nice and warm day'
>>> print(weather)
It's a nice and warm day\n可以在字符串中使用>>> colors = 'Blue\nRed\nGreen'
>>> colors
'Blue\nRed\nGreen'
>>> print(colors)
Blue
Red
Greenr(代表raw)如果你想要字符串被原样输出>>> raw_str = r'Blue\nRed\nGreen'
>>> print(raw_str)
Blue\nRed\nGreen
# 查看字符串内部是如何存储的
>>> raw_str
'Blue\\nRed\\nGreen'>>> str1 = 'Hello'
>>> str2 = ' World'
>>> print(str1 + str2)
Hello World
>>> style_char = '-'
>>> style_char * 10
'----------'
>>> word = 'buffalo '
>>> print(word * 8)
buffalo buffalo buffalo buffalo buffalo buffalo buffalo buffalo
# Python v3.6 允许变量使用f-strings进行插入
>>> msg = f'{str1} there'
>>> msg
'Hello there'"""或'''可以用于多行注释、字符串以及使用\反义#!/usr/bin/python3
"""
这一行是多行注释的一部分
This program shows examples of triple quoted strings
"""
# 把多行字符串赋值给变量
poem = """\
The woods are lovely, dark and deep,
But I have promises to keep,
And miles to go before I sleep,
And miles to go before I sleep.
"""
print(poem, end='')$ ./triple_quoted_string.py
The woods are lovely, dark and deep,
But I have promises to keep,
And miles to go before I sleep,
And miles to go before I sleep.
$进一步阅读
来自Python文档 - 常量的释义
None是NoneType类型的唯一值None 常用于数值的缺失False是bool类型的“错误”值True 是bool类型的“正确”值>>> bool(2)
True
>>> bool(0)
False
>>> bool('')
False
>>> bool('a')
True+ 加- 减* 乘/ 除(浮点输出)// 整除(整数输出,结果没有取舍)** 幂% 取模+ 字符串粘连* 字符串重复== 等于> 大于< 小于!= 不等于>= 大于或等于<= 小于或等于and 逻辑与or 逻辑或not 逻辑非& 与| 或^ 异或~ 位反转>> 右移<< 左移进一步阅读