Python学习篇 之 基础知识点

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")

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张之海

若有帮助,客官打赏一分吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值