1 如何判断数据类型
假设有字符串对象x
(1) type()函数
print(type(x))
#得到:
<class 'str'>
(2)_ _class_ _属性
print(x.__class__)
#得到:
<class 'str'>
(3)isinstance()函数
isinstance()函数返回值为Bool类型
a = 'haha';
print(type(a))
if(isinstance(a,str)):
print(True)
else:
print(False)
注意:使用isinstance(obj,str)时,前面的代码不要出现以str为名称的变量,否则会出现错误:
"TypeError: isinstance() arg 2 must be a type or tuple of types"
补充:type()和isinstance()的区别:
对具有继承关系的类,type()不能判断出是否是父类。
举例说明:
class A:
pass
class B(A):
pass
#输出为True
if(type(A()) == A):
print(True)
else:
print(False)
#输出为True
if(isinstance(A(),A)):
print(True)
else:
print(False)
#输出为False
if(type(B()) == A):
print(True)
else:
print(False)
#输出为True
if(isinstance(B(),A)):
print(True)
else:
print(False)
执行结果如下:
true
true
False
True
其中,A是B的父类,用type() 判断B的对象是否是A类型时,出现错误,即说明type()不能判断父类型。
2 与C、C++不同的地方
(1)if条件语句
a = 1;
if a == 1:
print("First")
elif a == 2 :
print("Second")
else:
print("None")
不同点:else if 变为 elif
(2) While循环语句
count = 2
while count < 5 :
pass
else:
print("circle end")
while ... else ...在循环语句结束时执行else语句块。
(3)for循环语句
#法1:直接遍历
for sentence in list:
print(sentence)
else:
print("end")
#法2:通过索引遍历
list = ['one','two','three','four','five']
for index in range(len(list)):
print(list[index])
else:
print("end")