python
是一种解释行,面向对象的动态数据类型的高级程序设计语言,在1989
年发明;- 解释型:开发过程中没有编译这个环节,类似于
shell
; - 交互型:支持
python
提示符,互动执行程序; - 面向对象:支持面向对象的风格或者代码封装在对象的编程技术;
- 解释型:开发过程中没有编译这个环节,类似于
python
的特点:- 易于学习:关键字相对较少,结构简单;
- 易于阅读:
Python
代码阅读清晰; - 拥有广泛的标准库;
- 可移植性好;
- 可扩展性好:可以使用其他的代码来扩充这部分代码;
- 支持多种
GUI
变成以及系统调用; - 支持将
Python
代码嵌入到C/C++
程序中;
- 缺点:
- 运行速度慢:和
C
程序相比非常慢,Python
属于解释性语言,代码在执行时会一行一行翻译成CPU
机器代码,翻译过程十分耗时; - 代码不能够加密:解释型语言只能够发布源码,不像
C
语言发布成二进制的可执行文件;
- 运行速度慢:和
- 注释
- 代码的注释使用
#
进行注释; - 多行注释使用
'''注释多行 '''
,写代码时,不应该存在中文字符; - 同样的
"""注释多行"""
; - 输出
print
:打印双引号之间的内容;
print("hello world")
- 如果需要打印多条信息,可以使用
,
进行分割
print("hi python","hello python")
- 输出的结果是
- 输出数字以及运算
print(19)
print(10 + 8)
print("10 + 8 ", 18)
- 输出的结果是
- 输入
input
:用于从标准输入获取变量的值
age=input("please input your age ")
print("age = ", age)
-
输出的结果为
-
Python的数据类型
-
number
: -
整数:
Python
可以处理任意大小的整数,同时也包括负整数,在程序中的写法和数学表达是一致的; -
连续定义多个变量
num1 = 10
num3 = num2 = num1 //这样变量的地址是一样的
num6,num7 = 6,6这两个变量的地址也是一样的;
print(id(num2),id(num3));
93941385645920 93941385645920
- 浮点数:浮点数由整数部分和小数部分组成,浮点数运算可能会丢失精度;
float1 = 1.1
float2 = 2.30000
print(type(float1))
print(float1+float2)
-
结果为
-
复数:表示的实数部分和虚数部分组成;
-
数值类型转换:
print(int(1.9))
print(int('123'))
print(int("+123"))
print(int("-112"))
- 常见的数学函数
abs()
:用于返回某个数的绝对值;print((num2>num3)-(num2<num3))
:用于表示比较这两个数的大小,返回值为1 0 -1
;max(arg1,arg2,arg3..)
:用于返回给定参数的最大值;min(arg1,arg2,arg3..)
:用于返回给定参数的最小值;pow(x,y)
:用于计算x^y
的结果;round(x,y)
:表示保留y
位,x
的值,省略表示的就是只保留整数位;math
库:数学运算相关的库;math.ceil(18.1)
:表示向上取整;math.flooe()
:表示向下取整;math.modf(22.3)
:用于将一个数拆分为整数[浮点型]部分和小数部分;math.sqrt()
:表示用于开平方;
print(max(num2,num3))
print(min(num2,num3))
print(pow(num2,num3))
print(round(3.456,1))
- 随机数:
print(random.choice([1,3,5,7,9,"aa"])) //在这些数里面选出随机数
print(random.choice(range(5)))
print(random.choice("sunck"))
print(random.choice(range(100))+1)
print(random.randrange(1,100,2)) //1-->100生成随机数[包含1,但是不包含100],步长为2;
print(random.randrange(100)) //start默认是0,步长默认为1
print(random.random()) //随机生成[0,1)之间的浮点数;
- 将列表中的元素进行随机排序
list = [1,2,3,4,5]
random.shuffle(list)
print(list)
- 显示的结果为
- 随机生成实数
random.uniform(3,9) //范围是[3,9]
- 随机数小程序
import random
num = int(input("please input your number "))
res = random.choice(range(100)) + 1
if num == res:
print("you are lucky")
else:
print("not you")
string
: 表示字符串,python
里面没有字符的概念;- 字符串是以单引号或者双引号引用的任意文本,引号本身不是数据;
str1 = "hello today"
str2 = "hello tomorrow"
- 字符串运算:
+
:用于连接字符串
str1 = "hello today "
str2 = "hello tomorrow"
print(str1)
str3 = str1 + str2
*
:表示字符串的多次输出,也就是拼接
str3 = "oo "
print(str3*3)
[]
用于获取某个单个字符
str1 = "hello today "
str2 = "hello tomorrow"
print(str1[1])
str1[1]='a' //字符串不可变原则,所以一定会出错;
- 截取字符串
str2 = "hello tomorrow,it's a new day"
print(str2[2:14])
print(str2[:13])
print(str2[10:])
- 显示的的结果
- 关于
in
的使用
str2 = "hello tomorrow,it's a new day"
print("hello" in str2)
print("hi" in str2)
- 输出的结果
- 转义字符
\n
:用于表示换行;
print("num = %d \nstr = %s\nfnum =%f " %(num,str1,fnum2))
print("today is \\n a new day")
print('today is a \'new\' day')
print("today is a 'new' day")
- 如果需要打印多行,使用
print('''
today
is
a
good
day
''')
\t
:表示制表符,默认是4
个空格
print("today is a \t good day")
r
:如果字符串中,存在很多字符进行转义,为了简化,允许使用r
表示内部的字符串默认不转义
print(r"\\\\t\\\\")
eval()
:用于将字符串当成有效的表达式来求值,并且返回计算结果,用于将字符串转换成整数不能够用于处理字母;
num = eval("1234")
print(num)
print(type(num))
num = eval("12+34")
print(num)
print(type(num)) //输出结果为46
len()
:用于返回字符个数,并不计算字节个数
print(len("today is a new day"))
lower(str)
:转换字符串中的大写字母为小写字母
str2 = "Hello tomoRRow,it's a new day"
print(str2.lower()) //并不改变原有字符串的;
upper()
:将小写字母转换为大写字母
print(str2.upper())
swapcase()
:用于将大写转换为小写,用于将小写转换为大写
print(str2.swapcase())
capitalize()
:只有将首字母大写,其他字母都是小写
print(str2.capitalize())
Hello tomorrow,it's a new day
title()
:每个单词的首字母大写
print(str2.title())
Hello Tomorrow,It'S A New Day
center(width,filechar)
:表示宽度和填充字符
print(str1.center(40,'*'))
**************hello today**************
ljust()
:表示进行左对齐,默认是空格填充
print(str1.ljust(20,"%"))
hello today%%%%%%%%%
rjust()
:表示返回一个指定长度的字符串,是右对齐,默认使用空格填充
print(str1.rjust(20,'*'))
*********hello today
zfill()
:返回指定字符串的长度,字符串右对齐,默认使用0
进行填充
print(str1.zfill(20))
000000000hello today
count(str[,start][,end])
:可以用于在指定字符串的位置中查找指定字符串出现的位置
str2 = "Hello tomotoRRow,it's a new day"
print(str2.count("to",5,len(str2)))
2
find(str[,start][,end[)
:用于查找指定字符串重做开始第一次出现的位置,如果不存在就返回-1
str2 = "Hello tomotoRRow,it's a new day"
print(str2.find("to",7,len(str2)))
10
rfind()
:用法和上面一样,表示从由向左进行查找
print(str2.rfind("to"))
10
index(str,start=0,end-len=(str))
:用法和上面一样,如果指定字符串不存在,就会报错;
str2 = "Hello tomotoRRow,it's a new day"
print(str2.index("too"))
Traceback (most recent call last):
File "/root/PycharmProjects/test/first.py", line 5, in <module>
print(str2.index("too"))
ValueError: substring not found
-
rindex()
:表示从右向左进行查找,如果找不到,就会出错 -
lstrip()
:用于去掉字符串左侧指定的字符,默认为空格
str2 = "*******Hello tomotoRRow,it's a new day"
print(str2.lstrip('*'))
Hello tomotoRRow,it's a new day
split(" ",num)
:表示按照某个关键字将字符串进行切割,如果指定num
表示截取指定的num
个字符串;
string1 = "today is a new day, but where are you"
string2 = string1.split(" ")
wordnum = 0
for i in string2:
if len(i) > 0:
wordnum +=1
print(wordnum)
9
splitlines(true | false)
:表示按照\r, \r\n, \
分隔,true
表示返回换行符,false
表示不返回换行符;
string1 = '''today is an new day, but where are you
the next day is an new day
hello tomorrow
'''
print(string1.splitlines())
print(string1.splitlines(True))
['today is an new day, but where are you', 'the next day is an new day ', 'hello tomorrow']
['today is an new day, but where are you\n', 'the next day is an new day \n', 'hello tomorrow\n']
join
:用于将列表组合成为字符串
list1 = ['today is an new day, but where are you', 'the next day is an new day ', 'hello tomorrow']
string1 = "\n".join(list1)
print(string1)
today is an new day, but where are you
the next day is an new day
hello tomorrow
max()
:表示用于返回字符串里面的最大值;min()
:表示用于返回字符串里面的最小值,按照ASCII
进行比较;replace(old,new,count)
:表示要替换的值,替换的值,替换的次数,默认进行全部替换,如果指定了count
,那么只进行前count
的替换;
string1 = "today is an new day"
string2 = string1.replace("an","a",1)
print(string2)
maketrans("映射前","映射后")
:表示创建字符串映射表,是一张表,每个字符对应进行替换,是按照字符为单位的,替换前后的字符数必须相等;translate()
:表示执行上面的映射
string1 = str.maketrans("an", "6o")
string2 = "today is an an an an new day"
string3 = string2.translate(string1)
print(string3)
tod6y is 6o 6o 6o 6o oew d6y
-
这种替换较少使用;
-
startwith("str", num1, num2)
:表示从num1
到num2
进行查找,是否是以str
开头的字符串,如果没有指定范围,默认是整个字符串;
string2 = "today is an an an an new day"
print(string2.startswith("an", 3, 10))
False
endwith("str",
num1,
num2)
:使用同上,用于判断是否是str
结尾的- 编码:
encode("utf-8,"ignore")
string2 = "today is an an an an new day"
data = string2.encode("utf-8")
print(data)
print(type(data))
解码
string3 = data.decode("utf-8")
print(string3)
b'today is an an an an new day'
today is an an an an new day
-
解码和编码必须使用同样的格式,否则会出错;
-
isalpha()
:表示如果字符串中至少有一个字符,并且所有的字符都是字母,但会True
,否则返回False
; -
isalnum
:表示字符串中至少有一个字符,并且所有的字符都是字母或者数字返回True
,否则返回False
; -
isupper()
:表示字符串中至少有一个英文字符,且所有的英文字符必须都是大写的英文字母,返回True
,否则返回False
,如果包含数字也会返回True
-
islower()
:表示字符串中至少一个英文字符,并且所有的英文字符必须都是小写的英文字符; -
istitle()
:表示如果字符串是标题化的就返回True
,否则就是返回False
,标题化表示单词的第一个字母必须是大写; -
isdigit()
:如果字符串只包含数字,返回True
,否则返回False
; -
isnumeric()
:字符串中只包含数字字符,返回为True
; -
isdecimal()
:字符串中只包含十进制字符; -
isspace()
:如果字符串中只包含空格,返回True
,否则返回False
; -
rstrip()
:作用和上面的一样 -
ord()
:用于将字母转换成为ACSII
-
chr()
:用于将某些ASCII
转换成为值; -
字符串进行比较的规则:
- 某个字符串的
ASCII
的大,那么就是比第二个; - 如果相等,就会比较下一个字符的
ASCII
;
- 某个字符串的
-
boolean
:用于表示true
以及false
,有且只有这两种值, -
None
:是一个特殊值,但是不能够使用0
来进行表示; -
list
-
列表用于存储更多的数据 ,列表表示一组有序的集合,并且允许时不同的类型
age = []
print(age)
[]
age = [12, 23, 34, 45]
print(age)
[12, 23, 34, 45]
list1 = [1, 2, "sunck", True]
print(list1)
[1, 2, 'sunck', True]
- 取值和替换:对于元素的访问从
0
开始,并且访问不能够越界;
list1 = [1, 2, "sunck", True]
print(list1[1])
list1[1] = 12
print(list1)
- 层级嵌套 不能够超过
3
层 - 列表操作
list2 = age + list1
print(list2)
- 列表重复
print(age * 3)
[12, 23, 34, 45, 12, 23, 34, 45, 12, 23, 34, 45]
- 判断元素是否在列表中
print(12 in age)
- 列表截取
list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list2[2:6])
print(list2[2:])
print(list2[:6])
[3, 4, 5, 6]
[3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6]
- 二维列表
list33 = [[1,2,3],[4,5,6],[7,8,9]]
print(list33[1][1])
- 列表方法
append
:表示在末尾一次性追加另一个列表中的多个值;
list1 = [1, 2, 3, 4, 5]
list1.append(6)
print(list1)
list1.append([7, 8, 9])
print(list1)
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, [7, 8, 9]]
- 追加的是一个列表中的元素
list1 = [1, 2, 3, 4, 5]
list1.extend([6, 7, 8])
print(list1)
[1, 2, 3, 4, 5, 6, 7, 8]
insert
: 在下标处,添加一个元素,将列表当做一个元素来处理
list1 = [1, 2, 3, 4, 5]
list1.insert(3, 100)
print(list1)
[1, 2, 3, 100, 4, 5]
- 插入的是一个列表
list1 = [1, 2, 3, 4, 5]
list1.insert(3, [100, 200])
print(list1)
[1, 2, 3, [100, 200], 4, 5]
pop(x=list[-1])
:默认表示列表最后一个元素被弹走,可以指定下标移除指定元素,并且返回删除的数据
list1 = [1, 2, 3, 4, 5]
print(list1[-1])
5
list1.pop()
print(list1)
[1, 2, 3, 4]
list1.pop(2)
print(list1)
[1, 2, 4]
remove()
:表示用于删除指定元素第一个匹配的结果,首先会查找指定元素的值
list1 = [1, 2, 3, 4, 4, 4, 5]
list1.remove(4)
print(list1)
[1, 2, 3, 4, 4, 5]
clear()
:用于删除列表中的所有元素
list1 = [1, 2, 3, 4, 4, 4, 5]
list1.clear()
print(list1)
[]
index()
:表示从列表中找出第一个匹配的索引
list1 = [1, 2, 3, 4, 4, 4, 5]
print(list1.index(3))
print(list1.index(4, 2, 7))
2
3
len()
:用于获取列表里面的元素个数
list1 = [1, 2, 3, 4, 4, 4, 5]
print(len(list1))
max()
:用于获取列表中的最大值;min()
:用于获取列表中的最小值;count()
:用于查询某个元素出现的次数;reverse()
:用于进行列表的倒序;sort()
:默认进行升序排序;- 关于浅拷贝与深拷贝
list1 = [1, 2, 3, 4, 4, 4, 5]
list2 = list1
list2[3] = 300
print(list2)
print(list1)
print(id(list1))
print(id(list2))
[1, 2, 3, 300, 4, 4, 5]
[1, 2, 3, 300, 4, 4, 5]
140657342356296
140657342356296
- 栈区:程序结束,自动释放程序空间;
- 堆区:手动申请,手动释放,普通变量保存在栈区;
- 浅拷贝的地址结构
- 由于执行的是浅拷贝,栈区
list27
和list28
里面保存的是堆区里面的同一段地址空间的首地址0x100
,其实访问的是同一片地址空间; - 深拷贝
list1 = [1, 2, 3, 4, 4, 4, 5]
list2 = list1.copy()
list2[3] = 300
print(list2)
print(list1)
print(id(list1))
print(id(list2))
[1, 2, 3, 300, 4, 4, 5]
[1, 2, 3, 4, 4, 4, 5]
140278067989320
140278067987720
-
深拷贝表示的是内存拷贝,
-
元组转换为列表
list2 = list((1, 2, 3, 4, 5))
print(list2)
[1, 2, 3, 4, 5]
- 分解质因数的小程序
num = int(input())
i = 2
list1 = []
if num == 1:
print(1)
while num != 1:
if num % i == 0:
list1.append(i)
num //= i
else:
i += 1
print(list1)
- ** tuple**
- 表示元组,元组和列表的不同之处在于,元组里面的元素不能够进行修改,但是可以进行元组的组合;
- 创建元组
tuple2 = (1, 2, 3, 4, "hello", True)
- 对于只有一个元素的元组
tuple1 = (1, )
- 元组的访问,下标从
0
开始,并且不允许越界;
print(tuple2[3]) //下标为 0
print(tuple2[-1]) //用于获取最后一个元素 [-2]表示倒数第二个元素
- 对于这样一种情况是可以进行修改的.也就是对于元组里面存在可修改的列表时,是可以进行修改的;
tuple2 = (1, 2, 3, 4, 5, [7, 8, 9])
tuple2[-1][0] = 50
print(tuple2)
(1, 2, 3, 4, 5, [50, 8, 9])
- 元组表示的是元组里面的数据不可变,但是列表中的数据是可以进行改变的;
- 删掉元组
del tuple2
- 元组的操作
+
:表示相加
print(tuple2 + tuple1)
(1, 2, 3, 4, 5, [50, 8, 9], 1, 2, 3, 4)
*
:表示乘法
tuple3 = (1, 2, 3)
print(tuple3 * 3)
(1, 2, 3, 1, 2, 3, 1, 2, 3)
in
: 判断元素是否在元组里面
tuple3 = (1, 2, 3)
print( 1 in tuple3)
- 元组的截取:从开始下标开始截取,结束到结束下标之前;
tuple1 = (1, 2, 3, 4, 5, 6, 7, 8, 9)
print(tuple1[3:])
print(tuple1[3:5])
print(tuple1[:5])
(4, 5, 6, 7, 8, 9)
(4, 5)
(1, 2, 3, 4, 5)
- 二维元组
tuple2 = ((1, 2, 3, 4),(1, 2, 3, ),(1, 2, 3, ),(4, 5, 6, ))
print(tuple2[1][1])
- 元组的方法
len()
:用于返回元组里面元素的个数
tuple1 = (1, 2, 3, 4, 5, 6, 7, 8, 9)
max()
:用于返回元组里面的最大值
print(max(tuple1))
- 将列表转换成元组
list1 = [1, 2, 3, 4, 5]
tuple2 = tuple(list1)
print(tuple2)
(1, 2, 3, 4, 5)
- 元组的打印
for i in tuple2:
print(i)
- dictionary
- 表示字典,使用键值的存储形式,具有快速的查找速度,
key-value
,对于key
的要求:- 首先
key
必须是唯一的; key
:必须是不可变的对象;- 字符串,整数都必须是不可变的,可以作为
key
; list
是可变的,不能够作为key
- 首先
- 字典的创建
dict1 = {"tom":60, "xiaoxiao":90, "houhou":100}
- 通过
key
来访问value
,通过这种方式取值,如果值不存在,就会报错;
print(dict1["jerry"])
- 大多数情况下是通过下面这种方式来取值的,因为如果取的值不存在,不会进行报错,方便进行返回值的判断;
print(dict1.get("houhouo"))
- 添加
dict1["cat"] = 99 //如果字典里面内部存在就是添加
dict1["jerry"] = 90 //字典里面存在就是修改
- 删除
dict1.pop("houhou") //删除的前提是必须存在
- 遍历
dict1 = {"tom":60, "jerry":90, "houhou":100}
print(dict1.get("houhouo"))
dict1["cat"] = 99
dict1["jerry"] = 90
for key in dict1:
print(key, dict1[key])
for value in dict1.values():
print(value)
for key, value in dict1.items():
print(key, value)
for key, values in enumerate(dict1):
print(key, values)
0 tom
1 jerry
2 houhou
3 cat
dictionary
:- 字典的存储一般是无序的;
- 和
list
相比,查找和插入的速度是极快的,不会随着key-value
的增加而变慢; dict
在存储数据时,还需要存储序号,会导致内存浪费;
list
:- 查找和插入的速度会随着数量的增多而减慢;
- 占用内存小,内存浪费小;
- 一个用于查询字符串中的关键字
w = "the"
str = "this is a good day, hello the new day, the the a and what the weather;"
d = {}
list = str.split(" ")
print(list)
for value in list:
need = d.get(value)
if need == None:
d[value] = 1
else:
d[value] += 1
print(d[w])
print(d)
w = "the"
str = "this is a good day, hello the new day, the the a and what the weather;"
d = {}
list = str.split(" ")
print(list)
for value in list:
need = d.get(value)
if need == None:
d[value] = 1
else:
d[value] += 1
print(d[w])
print(d)
['this', 'is', 'a', 'good', 'day,', 'hello', 'the', 'new', 'day,', 'the', 'the', 'a', 'and', 'what', 'the', 'weather;']
4
{'what': 1, 'good': 1, 'and': 1, 'day,': 2, 'this': 1, 'is': 1, 'the': 4, 'new': 1, 'hello': 1, 'a': 2, 'weather;': 1}
-
set
:表示集合; -
标识符
-
标识符是字符串,但是字符串未必是标识符;
-
标识符遵守的规则:
- 只能够通过字母,数字,下划线组成;
- 开头不能够使数字;
- 不能够使
Python
的关键字和保留字; - 标识符对于大小写敏感;
- 见名知意
- 在
Python3
中,允许使用非ASCII
来定义标识符;
-
表示符是用来给变量和函数进行命名的;
-
查看关键字
import keyword
print(keyword.kwlist)
- 显示的结果
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
- 变量和常量
- 变量表示可以操作的存储空间名称,还表示程序运行期间能够改变的数据,对于每个变量来说都存在特定的类型;变量是用来将不同类型的数据保存在内存里面;
- 定义变量:
name = 初始值
,初始值是为了确定变量的类型,变量的类型根据初始值确定的; - 数据的存储是
变量名 = 数据值
,这个是用来存储数据值的; - 变量在使用之前必须进行定义,否则会出错;
- 定义变量:
- 一个简单的求和程序
number1 = int(input("please input a number"))
number2 = int(input("please input a number "))
print("the sum is ",number1+number2)
-
显示结果为
-
删除变量
-
del name
,删除之后,变量无法引用,用于释放内存空间;
del number1
del number2
- 查看变量的类型
print(type(number1))
<class 'int'>
- 查看变量的地址
print(id(age))
140043296231312 //变量的首地址
-
常量:程序运行期间不能够改变的数据,成为常量
-
运算符和表达式
-
表达式:由变量,常量和运算符组成的式子;
-
算术运算表达式不会改变变量的值,
-
运算符:
-
算术运算符:
+ - * /
,%
取模,**
求幂,//
取整;
赋值运算符:=
,格式是变量 = 表达式
,计算了等号右侧的表达式的值并且赋值给等号左侧的变量; -
复合运算符:
+= -= /= %= **= //=
-
位运算符:将数值当做二进制数来进行运算;
&
:表示按位与运算符,如果按位进行运算,两个值都为1
,结果为1
,否则为0
;|
:表示二进制位有一个为1
时,结果为1
;^
:表示按位异或运算符,两个二进制位不同时,结果为1
;~
:表示按位取反运算符;<<
:表示二进制位向左移动几位,高位丢弃,低位补0
;
0000 0000 0000 0010
0000 0000 0000 1000
* `>>`:表示各个二进制向右移动几位,低位丢弃;
-
关系运算符和关系运算表达式的结果是
true
和false
-
==
!=
>
<
>=
<=
-
逻辑运算符:
-
表达式1 and 表达式2
:双真为真; -
表达式1 or 表达式2
:一个为真,就是真; -
not 表达式
:真为假,假为真; -
成员运算符
-
in
:如果在指定的序列中,找到的指定的值,返回值为true
,否则为false
; -
not in
:如果在指定的序列中,没有找到的指定的值,返回值为true
,否则为false
; -
身份运算符
-
is
:判断两个标识符是不是引用同一个对象; -
is not
:判断两个标识符是不是引用不同的对象; -
运算符优先级
-
** --> ~ + - --> * / % // --> + - --> << >> --> & --> ^ | --> < > <= >= --> == != --> = --> is --> in --> not or and
-
判断语句
if 表达式:
语句
else:
语句
-
当程序执行到
if 语句
时,首先计算表达式的值,并且得到表达式的真假,表达式为真,执行if
语句 ,如果表达式为假,则跳过if
语句,向后执行; -
假:
0
以及0.0
或者''
再或者False
; -
其余都为真;
-
判断三位的水仙花数
num1 = int(input("please input a number "))
a = num1 % 10
b = num1 //10 % 10
c = num1 //100
if num1 == a**3 + b**3 + c**3:
print("yes")
else:
print("no")
- 三个数取最大值
max = num1
if num2 > max:
max = num2
if num3 > max:
max = num3
- 循环
while
循环
while 表达式:
语句
- 表达式的结果为真,执行语句,执行完成语句之后,再次计算表达式的值,继续进行判断,知道为假;
while i < 100:
sum += i
i += 1
print("down")
print(sum)
while index < len(string1) - 1:
print(string1[index])
index += 1
if-elif-else
语句
if 表达式1:
语句
elif 表达式2:
语句2
.
.
.
else:
语句n
- 每个
elif
都是对上面条件的否定; - 循环语句
- 死循环:表示表达式永远为真的循环;
while 表达式:
语句1
else:
语句2
- 执行的逻辑是:在表达式语句为
false
,会执行else:
中的语句2
; for
循环语句:
for 变量名 in 集合:
语句
- 按照顺序取集合中的每个元素复制给变量,然后执行语句,知道取完集合中的元素;
range()
:列表生成器,用于生成数列,表示范围[0,n)
;
for i in range(2,20,2): 开始位置默认为0,结束位置,步长默认为1
print(i)
- 获取下标
for index, i in enumerate([1, 2, 3, 4, 5]):
print(index, i)
break
:用于跳出for
和while
的循环,只能跳出距离最近的那一层循环;continue
:用于跳过当前循环的剩余语句,然后继续下一次循环,同样只能够跳过最近的一次循环;turtle
:是一个简单的绘图工具done()
:用于保持程序不结束;forward()
:表示向前移动,原点默认是从中间开始的;backward()
:表示向后移动;right()
:left()
goto(x,y)
:移动到坐标为x
,y
的位置speed()
:表示移动的速度;up
:表示在移动过程中,不画图down()
:表示开始划线setheading()
:改变朝向pencolor()
:用于表示颜色pensize()
:用于表示粗细reset()
:用于清空窗口,重置turtle
状态clear()
:表示清空窗口,但是不会重置turtle
circle()
:表示用于绘制圆形,或者是五边形- 关于填充
turtle.begin_fill()
turtle.fillcolor("blue")
:表示填充什么颜色turtle.end_fill()
:表示结束填充undo()
:表示撤销生一次动作;hideturtle()
:表示隐藏海龟showtutle()
:表示用于显示海龟screensize()
:表示更改显示的屏幕大小