Python新手入门【变量类型】

288 阅读2分钟

数据类型

  • 变量就是编程中最基本的存储单位
  • Python中的变量赋值不需要类型声明

  • 展示打印的结果

1.整数

a = 1
print(a)

输出结果为:

1

2.浮点数

b = 1.23
print(b)

输出结果为:

1.23

3.布尔量

c = True
print(c)

输出结果为:

True

4.科学计数法

d = 1e3
print(d)

输出结果为:

1000.0

5.字符串

#!/usr/bin/python
# -*- coding: UTF-8 -*-

str = 'Python创客'

print(str)           # 输出完整字符串
print(str[0])        # 输出字符串中的第一个字符
print(str[2:5])      # 输出字符串中第三个至第六个之间的字符串
print(str[2:])       # 输出从第三个字符开始的字符串
print(str * 2)       # 输出字符串两次
print(str + "TEST")  # 输出连接的字符串
print(str.upper())    # 全部大写
print(str.lower())    # 全部小写
print(str.find('y'))  # 搜索指定字符串,没有返回-1
print(str.count('y')) # 统计指定的字符串出现的次数

输出结果为:

Python创客
P
tho
thon创客
Python创客Python创客
Python创客TEST
PYTHON创客
python创客
1
1

6.列表

#!/usr/bin/python
# -*- coding: UTF-8 -*-

list = [ 'runoob', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print(list)               # 输出完整列表
print(list[0])            # 输出列表的第一个元素
print(list[1:3])          # 输出第二个至第三个元素 
print(list[2:])           # 输出从第三个开始至列表末尾的所有元素
print(tinylist * 2)       # 输出列表两次
print(list + tinylist)    # 打印组合的列表
print(list.append(44))  # 添加44元素

输出结果为:

('runoob', 786, 2.23, 'john', 70.2)
runoob
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('runoob', 786, 2.23, 'john', 70.2, 123, 'john')
('runoob', 786, 2.23, 'john', 70.2, 123, 'john',44)

7.字典

#!/usr/bin/python
# -*- coding: UTF-8 -*-

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"

tinydict = {'name': 'runoob','code':6734, 'dept': 'sales'}

print(dict['one'])          # 输出键为'one' 的值
print(dict[2])              # 输出键为 2 的值
print(tinydict)             # 输出完整的字典
print(tinydict.keys())      # 输出所有键
print(tinydict.values())    # 输出所有值

输出结果为:

This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'runoob'}
['dept', 'code', 'name']
['sales', 6734, 'runoob']

类型转换

函数描述
int(x)将x转换为一个整数
long(x)将x转换为一个长整数
float(x)将x转换为一个浮点数
str(x)将对象x转换为字符串
list(x)将序列s转换为一个列表
chr(x)将一个整数转换为一个字符
hex(x)将一个整数转换为一个十六进制字符串