python基础

常见的数学函数

函数名描述
abs(x)返回数字的绝对值,如abs(-10) 返回 10
fabs(x)返回数字的绝对值,如math.fabs(-10) 返回10.0
ceil(x)返回数字的上入整数,如math.ceil(4.1) 返回 5
floor(x)返回数字的下舍整数,如math.floor(4.9)返回 4
round(x [,n])返回浮点数x的四舍五入值,如给出n值,则代表舍入到小数点后的位数。
exp(x)返回e的x次幂(ex),如math.exp(1) 返回2.718281828459045
log(x)如math.log(math.e)返回1.0,math.log(100,10)返回2.0
log10(x)返回以10为基数的x的对数,如math.log10(100)返回 2.0
max(x1, x2,…)返回给定参数的最大值,参数可以为序列。
min(x1, x2,…)返回给定参数的最小值,参数可以为序列。
modf(x)返回x的整数部分与小数部分,两部分的数值符号与x相同,整数部分以浮点型表示。
pow(x, y)x**y 运算后的值。
sqrt(x)返回数字x的平方根
cmp(x, y)Py2,如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1
NameError: name ... is not defined
名称错误:某某名称未被定义
  • cmp()函数

python2使用,python3已取消。

Python3中对应的使用:

>>>import operator

然后:

>>> operator.eq("a","a");

True

lt(a,b) 相当于 a<b     从第一个数字或字母(ASCII)比大小

less than

le(a,b)相当于a<=b

less and equal

eq(a,b)相当于a==b     字母完全一样,返回True,

equal

ne(a,b)相当于a!=b

not equal

gt(a,b)相当于a>b

greater than

ge(a,b)相当于 a>=b

greater and equal

函数的返回值是布尔

随机函数(random)

  • 模块导入
# 方法1
>>>import random
# 方法2
>>> from random import * #不推荐使用
  • 查看对应的方法和属性
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'System
Random', 'TWOPI', '_BuiltinMethodType', '_MethodType', '_Sequence', '_Set', '__a
ll__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__nam
e__', '__package__', '__spec__', '_acos', '_bisect', '_ceil', '_cos', '_e', '_ex
p', '_inst', '_itertools', '_log', '_pi', '_random', '_sha512', '_sin', '_sqrt',
 '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choi
ces', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognor
mvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', '
sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariat
e', 'weibullvariate']
>>>
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> import random
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'random']

>>> from random import *
>>> dir()
['Random', 'SystemRandom', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package
__', '__spec__', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', '
getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 's
eed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
>>>
  • random模块常用的功能
  • 1.random.random():用于司机生成一个0到1的浮点数n(0<=n<=1)
>>> import random
>>> num=random.random()
>>> print(num)
0.8885140760483085
>>> print(num)
0.8885140760483085
>>> num=random.random()
>>> print(num)
0.10160300734548322
>>>
  • 2.random.uniform(a,b):用于生成指定范围内的随机浮点数,两个参数,其中一个是上限,另一个是下限:
  • 如果a>b,生成的随机数n:a<=n<=b;
  • 如果a<b,生成的随机数n:b<=n<=a;
>>> import random
>>> random.uniform(1,10)
4.411380377649224
>>> random.uniform(10,1)
3.1936772709273615
>>>
  • 3.random.randint(a,b):随机数生成a到b范围内的整数n(a<=n<=b)
>>> random.randint(1,10)
  • 4.random.randrange([start],[stop],[step]):从指定范围内,按指定技术递增的集合中获取一个随机数。集合为{start,start+step,start+2*step,…,start+n*step}
>>> random.randrange(10,30,2)
26
>>> random.randrange(100,30,-2)
88
>>>
  • 5.random.choice(sequence):从序列中随机获取一个元素
>>> import random
>>> lst=['python','C','C++','javascript']
>>> str1=('I love python')
>>> random.choice(lst)
'javascript'
>>> random.choice(lst)
'C++'
>>> random.choice(str1)
'y'
>>> random.choice(str1)
'o'
>>>
  • 6.random.shuffle(x[,random]):用于将一个列表中的元素打乱,即将列表内的元素随机排列。
>>> import random
>>> p=['A','B','C','D','E']
>>> random.shuffle(p)
>>> p
['D','C','E','A','B']
>>> random.shuffle(p)
>>> p
['D','B','E','A','C']
  • 7.random.sample(sequence,k):从指定序列中随机获取指定长度的片段并随即排列。注意:sample函数不会修改原有序列。
>>> import random
>>> li=[1,2,3,4,5,6,7]
>>> random.sample(li,4)
[1, 2, 6, 3]
>>> random.sample(li,3)
[3, 2, 7]
>>> random.sample(li,5)
[1, 2, 7, 3, 4]
>>> li
[1, 2, 3, 4, 5, 6, 7]
>>>

Python流程控制

IF条件分支语句

Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块。

  • if单分支语句

    if 逻辑语句:
    语句(块)

demo:

print(111)
if True:
    print(222)
print(333)

运行:

111
222
333

如果改成如下:

print(111)
if False:
    print(222)
print(333)

运行:

111
333
  • 将True或者False换成逻辑语句。
learning = "Python"
if learning = ="Python":
    print("啊哈,真巧,我也在学习python")
    
print("很高兴认识你")
  • if双分支语句
if 逻辑语句1:
    语句(块)1
else:
    语句(块)2

命令行运行程序需要找到脚本文件才可以运行。

  • 一、进入脚本文件所在文件夹运行程序
  • 方法一:
Microsoft Windows [版本 6.1.7601]
版权所有 (c) 2009 Microsoft Corporation。保留所有权利。

C:\Users\Administrator>cd E:\湖南营销学院\day06

C:\Users\Administrator>e:

E:\湖南营销学院\day06>python day6.py
请输入你猜的数字(1or2):2
Sorry, 你猜错了
1

E:\湖南营销学院\day06>
  • 方法二:
Shift+鼠标右键,打开命令窗口
  • 按照对应路径运行脚本
  • 方法三
C:\Users\Administrator>python E:\湖南营销学院\day06\day6.py
请输入你猜的数字(1or2):2
Sorry, 你猜错了
1

C:\Users\Administrator>

if多分支语句

Python 中用 elif 代替了 else if,所以if语句的关键字为:if – elif – else。

注意:

  • 1.每个条件后面要使用冒号 :,表示接下来是满足条件后要执行的语句块。
  • 2.使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
  • 3.在Python中没有switch – case语句。
if逻辑语句1:
    语句(块)1
elif 逻辑语句2:
    语句(块)2
elif 逻辑语句3:
    语句(块)3
    ......
elif 逻辑语句n-1:
    语句(块)n-1
else:
    语句(块)n

demo:

要求用户输入0-100的数字后,你能正确打印他的对应成绩

score  = int(input("输入分数"))

if score > 100:
	print("我擦,最高分才100,附加题也有分,666...")
elif score >= 90:
	print("A")
elif score >= 80:
	print("B")
elif score >= 60:
	print("C")
elif score >= 40:
	print("D")
else:
	print("太笨了...E")

while

  • 概念:循环用来执行部分代码------即在一定的条件下执行重复的代码。
  • 格式:
while 逻辑语句:
   语句(块)

demo:

1.打印1-100:

count = 0
while count < 100:
	# count = count + 1
	count += 1  #自增 不是++i i++
    
	print(count)

2.将字符串里的所有字符输出:

str_data = "dong is a handsoe man"

count = 0
while count < len(str_data):
	print("str_data[%d] = %s" %(count,str_data[count]))
	count += 1
	print("循环结束")

3.求1-100的和:

count = 1
sum = 0

while count <= 100:
	sum = sum + count
	sum += count
	count += 1
print("1-100的和=%d"%(sum))

for循环

python for循环可以遍历任何序列的项目,如应该 列表或者一个字符串。

for循环格式:

for i in 序列:
    语句(块)

demo:

1.遍历字符串

a = "Life is short,I use python.")
for i in a:
	print(i,end = " ")

2.range()

range(end)
# [0,reg]
range(start,end)
# [start,end]
range(start,end,step)
# {start,start+step,......,start+n*step}(start+n*step)为[start,end]范围内的

demo:

for i in range(10):
    print(i,end=",")
# 0,1,2,3,4,5,6,7,8,9,
print()  #换行
for i in range(3, 10):
    print(i,end=",")
# 3,4,5,6,7,8,9,
print()
for i in range(5, 10,3):
    print(i,end=",")
# 5,8,

什么是字符串

字符串是python中最常用的数据类型,我们可以使用引号(“或”)来创建字符串,事实上,在Python中,家里引导的字符都被认为是字符串!

name = "Changsha" #双引号
age = "5000" #只要加双引号就是字符串
age_1 = 5000 #不加,整型
msg = """I`m in Changesha""" #三双引号
msg_1 = '''I`m in Hengyang''' #三单引号
hometowm = 'Changesha' #单引号
print(type(name),type(age),type(age_1),type(msg),type(msg_1),type(hometowm),sep = "|")

<class 'str'>|<class 'str'>|<class 'int'>|<class 'str'>|<class 'str'>|<class 'st
r'>

多引号什么作用呢?作用就是多行字符必须用多引号。

msg = """
轻轻的我走了,
正如你悄悄地来;
我轻轻的招手,
作别西天的云彩。
"""
print(msg)

字符串运算及操作

数字可以进行加减乘除等运算,字符串呢?让我大声告诉你,也能?是的,但只能进行”相加“和”相乘“运算。

(1)拼接+

>>> a="Hello"
>>> b="Python"
>>> a+b
'HelloPython'
>>>

注意:字符长度拼接只鞥是双方都是字符串,不能跟数字或其他类型拼接。

>>> age_1=5000
>>> name+age_1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int
>>>

(2)重复*

>>> a="Hello"
>>> a*3
'HelloHelloHello'
>>>

(3)字符串索引([]以及切片([:]))

#########012345678901234567890123456789
>>> a="Life is short, I use python"
>>> len(a)
27
>>> #索引
...
>>> a[0]
'L'
>>> a[15]
'I'
>>> a[-1]
'n'
>>> a[-6]
'p'
>>> #切片
...
>>> a[:13]#从第一个元素开始,一直到索引为12的元素
'Life is short'
>>> a[15:]#从索引值为15元素开始,一直到最后
'I use python'
>>> a[15:2]#从索引值为15的元素开始,步长为2,即每次元素跳过一个元素,一直到最后
'Iuepto'
>>> a[::-1]#逆序输出
'nohtyp esu I ,trohs si efiL'
>>>

(4)大小写转换

  • str.lower():转小写
  • str.upper():转大写
  • str.swapcase():大小写对换
  • str.capitalize():字符串首为大写,其余小写
  • str.title():以分隔符为标记,首字符为大写,其余为小写
>>> a="Life is short, I use python"
>>> a.lower()#将所有大写字符转换为小写字符
'life is short, i use python'
>>> a.upper()#将所有小写字符转换为大写字符
'LIFE IS SHORT, I USE PYTHON'
>>> a.swapcase()#将所有小写字符变成大写,将大写字符变成小写
'lIFE IS SHORT, i USE PYTHON'
>>> a.capitalize()#将字符串的第一个字符大写
'Life is short, i use python'
>>> a.title()#返回标题化的字符串
'Life Is Short, I Use Python'
>>>

应用:

#不区分大小写
input_str="AbDc"
get_str=input("请输入验证码(不区分大小写)")
if input_str.lower() == get_str.lower():
    print("输入成功")
else:
    print("请重新输入")     

(5)字符串格式输出对齐

  • str.center()
  • str.ljust()
  • str.rjust()
  • str.zfill()
>>> a="Life is short, I use python"
>>> a.center(35,'*')#返回一个原字符串居中,并使用空格填充至长度width的新字符串
'****Life is short, I use python****'
>>> a.ljust(35,'*')#返回一个原字符串左对齐,并使用空格填充至长度width的心字符串
'Life is short, I use python********'
>>> a.rjust(35,'*')#返回一个原字符串右对齐,并使用空格填充至长度width的新字符串
'********Life is short, I use python'
>>> a.zfill(35)#返回长度为width的字符串,原字符串string右对齐,前面填充0,只有一个参数
'00000000Life is short, I use python'
>>>

(6)删除指定字符

  • str.lstrip()
  • str.rstrip()
  • str.strip()
>>> a="****Life is short, I use python****"
>>> a.lstrip("*")
'Life is short, I use python****'
>>> a.rstrip("*")
'****Life is short, I use python'
>>> a.strip("*")
'Life is short, I use python'
>>>

(7)计数

=COUNTIF(B2:B31, “>=30”)/COUNT(B2:B31)

>>> a="Life is short, I use python"
>>> a.count("i")#返回str在String里面出现的次数
2
>>> a.count("i",4,8)#在索引值为[4,8]的范围内str出现的次数
1
>>>

(8)字符串搜索定位与替换

  • str.find()
>>> a="Life is short, I use python"
>>> a.find('e')#查找元素并返回第一次出现的元素的索引值
3
>>> a.find('e',18,24)#查找元素在制定索引范围内的索引
19
>>> a.find('w')#找不到值返回-1
-1
>>>
  • str.index()
  • 和find()方法一样,只不过如果str不在string中会报一个异常。
>>> a="Life is short, I use python"
>>> a.index('e')
3
>>> a.index('e',18)
19
>>> a.index('w')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>>
  • str.replace()替换
>>> a="Life is short, I use python"
>>> a.replace('I use','You need')
'Life is short, You need python'
>>> a.replace('t','T')
'Life is shorT, I use pyThon'
>>> a.replace('t','T',1)
'Life is shorT, I use python'
>>>

(9)字符串条件判断

  • isalnum(),字符串由字母或数字组成,
  • isalpha(),字符串只由字母组成,
  • isdigit(),字符串只由数字组成
In [1]: a = "abc123"

In [2]: b = "ABC"

In [3]: c = 123

In [4]: a.isalnum()
Out[4]: True

In [5]: a.isalpha()
Out[5]: False

In [6]: a.isdigit()
Out[6]: False

In [7]: b.isalnum()
Out[7]: True

In [8]: b.isalpha()
Out[8]: True

In [9]: b.isdigit()
Out[9]: False>>> str = '01234'
 
>>> str.isalnum()#是否全是字母和数字,并至少有一个字符
True
>>> str.isdigit()#是否全是数字,并至少有一个字符
True      
 
 
>>> str = 'string'
 
>>> str.isalnum()#是否全是字母和数字,并至少有一个字符
True
>>> str.isalpha()#是否全是字母,并至少有一个字符 
True
>>> str.islower()#是否全是小写,当全是小写和数字一起时候,也判断为True
True
 
>>> str = "01234abcd"
 
>>> str.islower()#是否全是小写,当全是小写和数字一起时候,也判断为True
True
 
>>> str.isalnum()#是否全是字母和数字,并至少有一个字符
True
 
>>> str = ' '
>>> str.isspace()#是否全是空白字符,并至少有一个字符
True
 
>>> str = 'ABC'
 
>>> str.isupper()#是否全是大写,当全是大写和数字一起时候,也判断为True
True
 
>>> str = 'Aaa Bbb'
 
>>> str.istitle()#所有单词字首都是大写,标题 
True
 
 
>>> str = 'string learn'
 
>>> str.startswith('str')#判断字符串以'str'开头
True
 
>>> str.endswith('arn')#判读字符串以'arn'结尾
True

(10)制表符转换

str.expandtabs()

>>> a="L\tife is short, I use python"
>>> a.expandtabs()#默认将制表符转化为8个空格
'L       ife is short, I use python'
>>> a.expandtabs(4)#加上参数,将制表符转化为对应个数的空格
'L   ife is short, I use python'
>>>

(11)ASCII码和字符的转化

  • chr():用一个范围在range(256)内的(就是0~255)整数作参数,返回一个对应的字符。
  • ord():将一个ASCII字符转换为对应的数字
>>> chr(65)
'A'
>>> ord('a')
97
>>>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值