1.print函数,打印信息到运行界面
print("hello world")
2.转义字符,当我们希望字符不被Python解析,只表达字面意思,可以在符号前加\
当\加一些特殊的字母字符时,也有另外的功能。
- print("he said \"Let\'s go\"")
- print("please print \nnextline")# \n表示换行
3.三引号跨行字符"""
因为Python是一行一行执行的,如果想要一次性打印出多行数据,除了用大量的print+\n的方法外,可以使用"""
- print("""
- 行行无别语
- 只道早还乡
- """)
- #python 会将被三引号字符包裹的文字视为一个整体
4.引入外部库
- import math
- # 利用math求一元二次方程组,math库内的常用函数见官方文档
- print(math.sin(1))
- print(max(4, 5))
- a = 1
- b = 4
- c = 4
- print(((-b) + math.sqrt(b * b - 4 * a * c)) / 2)
5.input()函数,获取输入数据
用input函数获取的所有数据均为String类型,在后续使用时需要强制类型转换。
input函数的返回值需要用变量命名,不然后续无法继续使用。
- #根据用户身高体重计算BMI
- user_weight = input("please write down your weight")
- user_height = input("please write down your height")
- print("your BMI is "+str(int(user_weight)/(float(user_height)*float(user_height))))
6.type()函数查看对象类型
- print(type(None))
- # 返回结果
7.字符串按索引下标取值
- # 可以将字符串按索引取值
- print("hello"[0])
8.if_else语句
- if 结果为布尔类型的变量或表达式:
- 执行语句1
- 执行语句2
- else:
- 执行语句3
- 执行语句4
- # 记得要写:
9.if_elif
等同于Java内的if_elseif
- user_weight = float(input("please write down your weight"))
- user_height = float(input("please write down your height"))
- user_bmi=user_weight/ user_height**2
- print("your BMI is " + str(user_bmi))
- if user_bmi<=18.5:
- print("体重偏瘦")
- elif (user_bmi > 18.5) & (user_bmi <= 25):
- print("体重正常")
10.逻辑符号
只有三个 and or not(与或非)优先级次序为not>and>or
11.列表list
向列表添加元素append
删除列表内元素remove
与其它语言不同,列表内元素类型可以不同。
列表内元素类型可以不相同,可以为布尔(注意python内的True和False都需要首字母大写,与Java不同)、浮点数、整数、嵌套list
- shopping_list = ["电源", 33]
- shopping_list.append(1.68)
- x=True
- shopping_list.append(x)
- print(shopping_list)
- shopping_list.remove("电源")
- #结果为 [ 33, 1.68, True]
列表常用函数
- score = [33, 1.68, 6., 55, 185]
- print(max(score))#求最大值
- print(min(score))#求最小值
- print(sorted(score))#从小到大排序
- #需注意在使用比较函数时,列表内元素类型要一样
- # 输出为185
- #1.68
- #[1.68, 6.0, 33, 55, 185]
12.字典
用{}包裹,内里元素组成为key-value,其中key为不可变类型(比如list就不可以)
- telephone = {"mumu": 1111111, "guagua": 222222, "xiaoming": 333333}
- print(telephone)
- # 根据key来获取value
- print(telephone["mumu"])
- # 向字典内添加值,如果key已存在则不变
- telephone["chrome"] = 4444444
- print(telephone)
- # pop与del均为删除,pop() 函数有返回值,返回值为对应的值,del语句没有返回值
- print(telephone.pop("xiaoming"))