【python】入门指南1

基础的数据结构:int, float, string

注意:python入门系列的文章的示例均使用python3来完成。

#!/bin/python

a = 1 
b = 1.0 
c = 'string'


print(a, type(a))
print(b, type(b))
print(c, type(c))

输出结果:

1 <class 'int'>
1.0 <class 'float'>
string <class 'str'>

type(a)这个表示获取a变量所属的类型,可以看到a,b,c分别属于int,float,str类型。

注意,type(a)返回的是对应的class名称,而不是简单的字符串类型。说明在python3中,所有的类型都归属于class。

测试type的返回值

#!/bin/python

a = 1

print(a, type(a))
print(type(a) == 'int')
print(type(a) == int)

输出结果:

1 <class 'int'>
False
True

引入bool类型:只有连个值,是常量的bool值,True和False,注意这里是区分大小写的。True不能写成TRUE,也不能写成true。

代码实例:

#!/bin/python

a = True
print(a, type(a))
print(type(a) == bool)

b = False
print(b, type(b))
print(type(b) == bool)

输出:

True <class 'bool'>
True
False <class 'bool'>
True

int,float,str互转

示例代码

#!/bin/python

a = 1
print(str(a), type(str(a)))
print(float(a), type(float(a)))

b = 1.0
print(str(b), type(str(b)))
print(int(b), type(int(b)))

c = "1.0"
print(float(c), type(float(c)))
print(int(float(c)), type(int(float(c))))

输出结果:

1 <class 'str'>
1.0 <class 'float'>
1.0 <class 'str'>
1 <class 'int'>
1.0 <class 'float'>
1 <class 'int'>

以上是:int,float,str三者的互转。

python中如何添加注释

#!/bin/python

#It is a comment

'''
This is a comment;
thie is another comment
'''

分两种注释:#表示注释当前行,'''表示注释多行

原文地址:https://www.cnblogs.com/helww/p/9816368.html