Python菜鸟编程第一课之开始编程
1. 第一条编程语言
- 运行Python程序的三种方式
(1)Python解释器环境运行
(2)脚本运行
(3)IDE(比如 Pycharm、sublime等)
1.1print()函数
- print()是最简单的输出函数
print("hello world")
print("hello python")
print("To be or not to be,it`s a question")
print("To be or not to be,it`s up to you")
print("Make it")
print("以梦为马,不负韶华")
1.2 注释
- 单行注释
一个“#” - 多行注释
三个单引号或者三个双引号
"""
多行
注释
"""
'''
多行
注释
'''
1.3 input()输入函数
- input()输入函数
作用:从外部获取值
用法:括号中可以提供提示信息
input()函数返回值为字符串类型
input("提示用户的输入函数")
demo:
>>> a=input("请输入:")
请输入:hello
>>> a
'hello'
>>> type(a) #type()输入数据类型
<class 'str'>
1.4Python中常见的数据类型
- 数字(number)
- 整形(int)
- 浮点型(float)
- 布尔型(bool)
- 复数(complex)
- 字符串(string)
- 列表(list)
- 元祖(tuple)
- 字典(dict)
- 集合(set)
1.5变量和常量
- 变量
概念:程序可操作的存储区的名称。程序运行时存储区能够改变的数据。
每个变量都有自己的特定的数据类型
- 作用:将数据存储到内存
变量的命名规则:必须是字母、下划线、数字组合。不能以数字开头,不可以是Python中的关键字。
变量的命名的注意事项:
- 见名知意
- 区分大小写
- 在Python中,单下划线和双下划线开头的变量有特殊的用途,一般不推荐使用单下划线跟双下划线开头的变量名称
变量的定义:
val_name=初始值
关键词的查看:
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
内存地址查看:id()
l1=['a','b','c']
print(id(l1))
l1[0]=1
print(id(l1))
结果:
1501337510408
1501337510408
- 常量
顾名思义不变的量。例如π
>>> tp=1,2,3
>>> x, y,z=tp
>>> x
1
>>> y
2
>>> z
3
>>> type(tp)
<class 'tuple'>
变量互换操作
(1)直接互换
>>> a=1
>>> b=2
>>> a,b=b,a
>>> a
2
>>> b
1
(2)利用中间变量
>>> a=1
>>> b=2
>>> c=a
>>> a=b
>>> b=c
>>> a
2
>>> b
1
1.6数字
- 整形(int)
- 32bit,取值范围: ~~
- 64bit,取值范围: ~~
以前Python区分短整型与长整型,目前无区分
- 浮点型(float)
- 带有小数点的数字
- 布尔型(bool)
- True
- False
- 复数(complex)
- 实部(real)
- 虚部(imag)
- 共轭复数(conjugate)
>>> cpx=complex(1,2)
>>> cpx
(1+2j)
使用dir()查看目前定义的变量
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b', 'c', 'cpx']
>>> dir(cpx)
['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', 'conjugate', 'imag', 'real']
>>> cpx.real
1.0
>>> cpx.imag
2.0
>>> cpx.conjugate()
(1-2j)
1.7常见的数学函数
函数名 | 描述 |
abs(x) | 绝对值 |
pow(x,y) | |
round(x,[n]) | 返回四舍五入的值,如果给出n,表明四舍五入后的小数点的位数为n位 |
math.exp(x) | 返回e的x次幂 |
math.fabs(x) | 返回绝对值,返回值的类型为float |
math.ceil(x) | 返回数字的上入整数 math.ceil(4.1)返回5 |
math.floor(x) | 返回数字的下舍整数 math.floor(4.1)返回4 |
math.log(x,[y]) | 单参数默认e为底数,双参数以y为底数,返回对数函数 |
math.modf(x) | 返回浮点数的小数部分跟整数部分 |
math.sqrt(x) | 开平方 |
max | 返回最大值 |
min | 返回最小值 |
有些需要导入math 函数,import math。
使用dir(math)查看math 中剩余函数
1.8表达式与运算符
- 表达式
- 由变量、常量和运算符组成的式子,也称为表达式
- 运算符
- 算术运算符
- 比较运算符
- 逻辑运算符
- 赋值运算符
- 成员运算符
- 身份运算符
- 位运算符
1.81Python算术运算符
运算符 | 描述 | 实例 |
+ | 相加/拼接 | a+b |
- | 相减/求差集 | a-b |
* | 相乘/重复 | a*b |
/ | 相除 | a/b |
// | 幂运算 | a**b |
% | 取余数 | a%b |
// | 取整数 | a//b |
divmod(x,y)
返回x除以y得到的商和余数,以元祖形式输出
>>> divmod(23,4)
(5, 3)
1.82Python 比较运算符
1.83Python 赋值运算符
1.84Python 位运算符
按位运算符是把数字看做二进制来计算的。常见的位运算符如下:
运算符 | 描述 |
& | 按位“与”,同为1才为1,否则为0 |
| | |按位“或”,有1即为1,否则为0 |
^ | 按位“异或”,不同为1,相同为0 |
~ | 按位“取反”,~得到-x-1 |
<< | 左移运算符 |
> > | 右移运算符 |
#&运算、|运算、^运算、~运算
>>> a=15
>>> b=31
>>> bin(a)
'0b1111'
>>> bin(b)
'0b11111'
>>> a&b
15
>>> a|b
31
>>> a^b
16
>>> ~a
-16
>>> a>>2
3
>>> a<<2
60
1.85Python成员运算符
运算符 | 描述 |
in | 如果存在知道序列中,返回True,否则False |
not in | 如果不存在知道序列中,返回False,否则True |
>>> str1='abc'
>>> "a" in str1
True
>>> "a" not in str1
False
1.86Python身份运算符
用于比较两个对象的存储单元
id()
运算符 | 描述 |
is | 判断两个标识符是否引用自同一个对象,如果是返回True,否则False |
not is | 判断两个标识符是否引用自同一个对象,如果不是返回False,否则True |
>>> a='ab'
>>> b='ab'
>>> a is b
True
>>> id('ab')
2644797138512
>>> id(a)
2644797138512
>>> id(b)
2644797138512
1.87逻辑运算符
- not
- and
- or
判断顺序not and or
1.9数据类型的强制转换
强转类型 | 描述 |
int(x,[base]) | 将x强制转换成整形。如果x是字符串,主要知道base基数 |
float(x) | 将x转换成浮点型 |
str(x) | 强转为字符串 |
repr(x) | 将对象转换成表达式字符串 |
list(x) | |
tuple(x) | |
dict(x) | |
set(x) | |
chr(x) | 将整数转换为字符 |
ord(x) | 将字符转换为数字 |
bin(x) | 转换为二进制 |
oct(x) | 转换为八进制 |
hex(x) | 转换为十六进制 |
#int类型强制转换
>>> a=12.3
>>> int(a)
12
>>> str1='123'
>>> int(str1,8)#代表的就是八进制的‘123’,也就是‘83’,int强转后就输出整型的83
83
>>> 8**2+2*8+3
83
>>> int(str1,16)
291
>>> 16**2+2*16+3
291
#repr(x)
>>> str1="City College\nOf Zhejiang"
>>> str1
'City College\nOf Zhejiang'
>>> print(str1)
City College
Of Zhejiang
>>> repr(str1)
"'City College\\nOf Zhejiang'"
#chr(x)
>>> chr(65)
'A'
>>> for i in range (256):
... print(chr(i),end='')
...
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„
†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ>>>
1.10随机函数
import random
random模块的常见功能:
(1)random.random()
作用:用来生成一个0-1的随机浮点数,[0,1)包含0但是不包含1
>>> for i in range(10):
... a=random.random()
... print(a,end=" ")
...
0.38480389816074634 0.5024158351777877 0.8448623069410243 0.9872454452353505 0.9737683088354863 0.7031608193839518 0.9372691172322437 0.0746381651284681 0.14078341669108996 0.24930466973538712
(2)random.uniform(a,b)
作用:用来生成指定范围内的浮点数[a,b]
>>> for i in range(10):
... a=random.uniform(6,8)
... print(a,end=" ")
...
6.493909180581849 6.379256356188458 6.769833662421621 7.97654829905435 6.683271596295308 7.973973270387759 7.776093814925661 7.519853804176094 6.282906430137139 6.541240823823188
(3)random.randint(a,b)
作用:用来生成指定范围内的整数[a,b]
>>> import random
>>> for i in range(10):
... a=random.randint(6,10)
... print(a,end="")
...
779681010968
(4)random.randrange([start],[stop],[step])
作用:从指定范围内,按指定基数递增或者递减的集合里,随机获取一个整数
random.randrange([start],[stop],[step])
1,3,5,7,9,11,13,15
import random
for i in range(10):
a=random.randrange(1,16,2)
print(a,end=" ")
#运行结果
15 3 13 13 1 9 7 9 11 11
(5) random.choice(sequence)
作用:从序列中随机获取一个元素,sequence可以是列表、元祖或者字符串
import random
for i in range(10):
a=random.choice(range(1,16,2))
print(a,end=" ")
#运行结果:
1 11 11 7 11 3 15 9 7 13
import random
li=['a','b','c','d']
for i in range(10):
a=random.choice(li)
print(a,end=" ")
#运行结果:
a d a d b b c c c a
(6)random.shuffle(x[,random])
作用:用来将一个列表中的元素打乱。
import random
li=['a','b','c','d']
for i in range(10):
random.shuffle(li)
print(li)
#运行结果:
['c', 'b', 'd', 'a']
(7)random.sample(sequence,k)
作用:用来从指定序列中随机获取指定长度的片段并随机排列,但是不会修改原来序列
import random
li=['a','b','c','d']
for i in range(10):
print(random.sample(li,2))