练习答案:
在字符串"Python非常有趣"中,分别截取:
Python
非常有趣
'''
练习答案:
在字符串"Python非常有趣"中,分别截取:
Python
非常有趣
'''
a="Python非常有趣"
print([:6])
print([6:])
Python
非常有趣
基础中的基础,与数学符号几乎一样(注意:有所不同)
算数运算符:
基础运算符:与数学相同
取余数(%):也称为取模,eg.7%3=1
具有运算功能和分类功能(余数0,1,2分类)
整除(//):eg.7//2=3
幂次(**):eg.2**3=8
a=3
b=2
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(7%2)
print(7//2)
#取整是取整数部分而不是四舍五入
print(2**3)
#为观察更清晰可写为以下代码
print("2**3=",2**3)
5
1
6
1.5
1
3
8
2**3= 8
赋值运算:
基础运算符
#简单赋值
a=4
b=a
print(b)
4
复合运算符
'''
a=4
b+=a #b=b+a,但b没有值
#发生异常:NameError
#name'b'is not defined
print(b)
'''
a=4
b=5
b+=a #b=b+a
print(b)
9
a=4
b=5
b*=a #b=b*a
print(b)
20
比较运算符:
大于(>),小于(<),等于(==)
大于等于(>=)
小于等于(<=)
不等于(!=)
a=5
b=6
print(a>b)
print(a<b)
print(a==b) #==表示两个数相等
print(a!=b) #!=表示两个数不相等
False
True
False
True
逻辑运算符
与(并且)
或(或者)
非(取反)
(后续介绍)
类型转换
字符→数值
int:转换成整形
float:转换成实形(float形)
a="6"
b="7"
print(a+b)
print(type(a))
print(type(b))
67
<class'str'>
<class'str'>
ai=int(a)
bi=int(b)
print(a+b)
print(type(ai))
print(type(bi))
13
<class'int'>
<class'int'>
ai=float(a)
bi=float(b)
print(a+b)
print(type(ai))
print(type(bi))
13.0
<class'float'>
<class'float'>
数值→字符
str
repr
#不同类型不能相连
a="圆周率是:"
b=3.14
#print(a+b)
#发生异常:TyprError
#can only concatenate str (not "float") to str
print(a+str(b))
print(a+repr(b))
圆周率是: 3.14
圆周率是: 3.14
x="Python课程"
print(x)
print(str(x))
print(repr(x))
#repr让字符串本身带了一个单引号
Python课程
Python课程
'Python课程'
#要想使结果带引号可使用repr,如
a="圆周率是:"
b=3.14
print(repr(a+repr(b)))
'圆周率是: 3.14'
练习:
计算“4+6”,通过类型转换函数,让其结果分别为:
46
10
(答案见下一节)