安装pycharm后,就可以开始我们的项目了。
1:print打印
创建test.py文件,
print('hello world')
只用一句话,就可以了。
2:空格和缩进
python和我们之前的语言风格稍微不同,
代码上缩进空白的数量是可变的,但是所有的缩进必须相同,否则就会报错。(莫名其妙,哈哈)
如:
这样直接运行就会出错。
3:数字类型
python2.x的时候,数字类型有int ,long,float,以及复数complex;到了3.x后,取消了long类型,统一为int类型。
count1=1
count2=2
print(count1+count2)
count3=4.2
print(count3)
print(type(1000000000000000000000))
print(type(count3))
type()为内置函数,输出对应的类型。
其中可以看到我们打印的100000000000.。。最后输出的为int类型
4:字符串
字符串主要了解下常用的一些用法。
4.1:截取字符串
[start:end]中end的值即使超出字符串的长度,也没问题
test='hello world'
print(test[0:70])
4.2:截取并添加间隔
count4 = "123456789"
print(count4[0:9:2])
4.3:重复输出
print("hello"*5)
5:元组
元组的创建:
string = (1, 2, 3, 4, 5, 10) # 元组
string2 = (6, 7, 8) # 元组
注意,元组是不允许修改的:
string[2]=100
TypeError: 'tuple' object does not support item assignment
元组拼接:
print(string+string2)
输出结果:
(1, 2, 3, 4, 5, 10, 6, 7, 8)
删除元组后,还去调用就会出现下述的错误
del string # 删除元组
print(string)
NameError: name 'string' is not defined
元组相关内置函数
max(元组) #最大值
min(元组) #最小值
tuple(元组) #将列表转为元组
len(元组) #元组的长度
迭代
for x in string: print(x) # 迭代
6:列表
listTest = [1, 2, 3]
添加元素
listTest.append(4)
列表可以修改元素
listTest[2] = 1000
删除元素
del listTest[1]
清除
listTest.clear()
del listTest[1]
IndexError: list assignment index out of range
清除后再去删除就会报错了。
组合
listTest = [1, 2, 3]
listTest2 = [4, 5, 6]
print(listTest+listTest2)
输出:
[1, 2, 3, 4, 5, 6]
7:字典(map)
字典的格式是每个键值以冒号分割,每个键值对之间用逗号分割。
dict1 = {'a': 1, '2': 2}
查询字典的元素:
dict1['2']
dict1['3']
KeyError: '3'
如上,如果key不存在就会出错
添加:
dict1['3'] = 3
删除:
del dict1['a'] #删除某个值
dict1.clear() #清空字典
del dict1 #删除字典