1、变量
变量类型:不用声明,赋值是什么类型该变量就是什么类型;
命名规则:全小写,使用下划线连接单词;
str_test = "China"
int_test = 123
float_test = 123.5
print(str_test)
print(type(str_test))
print(int_test)
print(type(int_test))
print(float_test)
print(type(float_test))
China<class 'str'>123 <class 'int'> 123.5 <class 'float'>
2、类型转换
str_eight = str(8)
int_eight = int(str_eight)
print(type(str_eight))
print(type(int_eight))
<class 'str'>
<class 'int'>
3、运算符
加 + 减 - 乘* 除/ 幂**,加减乘除大家都一样,就不多说了,幂:
int_days = 10
print(int_days ** 2)
100
4、List集合
声明、赋值和取值,下标index从0开始
months = []
months.append("January")
months.append("February")
print(months)
print(months[0])
['January', 'February'] January
int_months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
#从后面开始取
print(int_months[-1])
#切片 取index为2和3的 不包含4
print(int_months[2:4])
#取index从5开始的到最后
print(int_months[5:])
#取index从0到2的
print(int_months[:3])
12 [3, 4] [6, 7, 8, 9, 10, 11, 12] [1, 2, 3]
5、循环结构
通过冒号和缩进来控制代码块,类似Java的{}
citys = ["Beijing", "Shanghai", "Guangzhou"]
for city in citys:
print(city)
Beijing Shanghai Guangzhou
i = 0
while i < 3:
i += 1
print(i)
1 2 3
for i in range(10):
print(i)
0 1 2 3 4 5 6 7 8 9
6、判断结构
与其它语言没什么不同,没什么好讲的了。当直接使用数字时1=True,0=False
sample = 100
if sample > 1:
print(sample)
else:
print("not found")
100
animals = ["cat", "dog", "rabbit"]
if "cat" in animals:
print("cat found")
cat found
7、字典结构
即是key value 键值对
scores = {}
scores["Jim"] = 80
scores["Sue"] = 85
scores["Ann"] = 75
print(type(scores))
print(scores)
print(scores["Sue"])
<class 'dict'> {'Jim': 80, 'Sue': 85, 'Ann': 75} 85
students = {
"Tom": 60,
"Jim": 70
}
print("Tom" in students)
True
8、文件操作
open(文件名,操作模式) r为读,w为写,完成后记得close
f = open("d:\\test.txt", "w")
f.write("123456")
f.write("\n")
f.write("234567")
f.close()
f = open("d:\\test.txt", "r")
g = f.read()
print(g)
f.close()
123456 234567
读取一个csv文件放到List中,csv内容如下
weather_data = []
f = open("d:\\weather.csv", "r")
data = f.read()
rows = data.split('\n')
for row in rows:
split_row = row.split('\t')
weather_data.append(split_row)
print(weather_data)
f.close()
[['1', 'Sunny'], ['2', 'Sunny'], ['3', 'Fog'], ['4', 'Rain'], ['5', 'Rain'], ['6', 'Sunny'], ['7', 'Fog']]
9、函数定义
def printHello():
print ('hello python')
def add(a, b):
return a + b
printHello()
print(add(1, 2))
hello python 3