1.1运算符
操作运算符主要有如下几类:
-
算数运算符
-
增强型赋值运算符
-
比较运算符
-
逻辑运算符
-
移位运算符
算数运算符
+
:加法;序列拼接
>>> 10 + 3 13 >>> "abc" + "123" 'abc123' >>> [1,2,3] + [4,5,6] [1, 2, 3, 4, 5, 6] >>> 10 + [1,2,3] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'list'
-
:减法
>>> 12 - 8 4 >>> 3.14 - 9 -5.859999999999999
*
:乘法;序列重复
>>> 12 * 2 24 >>> 3.14 * 2 6.28 >>> "abc" * 3 'abcabcabc' >>> [1,2,3]*3 [1, 2, 3, 1, 2, 3, 1, 2, 3] >>> 3.14*[1,2,3] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can't multiply sequence by non-int of type 'float' >>> [1,2,3] * [1,2,3] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can't multiply sequence by non-int of type 'list'
/
:除法(结果是浮点数)
>>> 10 / 3 3.3333333333333335 >>> 10 / 2 5.0
//
:整除(如果能整除则为整数,如果计算中包含浮点数则结果为浮点数)
>>> 10 // 3 3 >>> 10 // 2 5 >>> 10.0 // 3 3.0 >>> 10.0 // 2 5.0 >>> 12.3456 // 2 6.0
**
:幂运算
>>> 2 ** 8 256 >>> 16 ** 0.5 4.0 >>> 2 ** -3 0.125
%
:取余运算
>>> 10 % 3 1 >>> 9 % 3 0
PS:Python当中是没有i++ ++i
类似的自增运算符的哦~
增强型赋值运算符
+=
:加法增强型型赋值运算符
>>> num = 10 >>> num += 10 >>> num 20 >>> num = num + 10 >>> num 30 >>> num += 10 >>> num 40
其余的:-=
,*=
,/=
,//=
,%=
,**=
等等类似
比较运算符
只参与布尔类型运算,结果只能是True或者False
大于>
小于<
等于==
大于等于>=
小于等于<=
不等于!= 或 <>
>>> 3 > 2 True >>> -10 > 3 False
逻辑运算符
只参与布尔类型运算,结果只能是True或者False
三大逻辑:与 and
或 or
非 not
>>> 3 > 2 and 4 > 3 True >>> 3 > 2 or 4 < 5 True >>> 3 > 2 and 4 < 3 False >>> 3 < 2 or 4 > 5 False >>> 3 < 2 or 4 < 5 True >>> not 3 > 2 False
移位运算符
二进制计算:&
与运算 |
或运算 <<
左移运算 >>
右移运算
>>> 12 & 7 4 “”“ 1100 &0111 0100 => 4 “”“ >>> 12 | 7 15 “”“ 1100 |0111 1111 => 15 “”“ >>> 7 << 5 224 """ 0111 => 0111 00000 7 * 2**5 """ >>> 225 >> 3 28 """ 111 00001 => 111 00 225 / 2**3 """
1.2 输入与输出
输入其实就是由外界向程序输入数据
输出其实就是由程序向外界输出数据
我们目前的输入来源:从控制台获取键盘键入信息
我们目前的输出来源:输出到控制台
print函数
print函数用于将内容格式化显示在标准输出上,主要指的就是屏幕显示器
>>> a = 3 >>> b = 4 >>> c = 5 >>> print(a) 3 >>> print(a + b + c) 12 >>> print(a,b,c) 3 4 5 >>> text1 = "HelloWorld" >>> text2 = "你好世界" >>> print(text1 + text2) HelloWorld你好世界 >>> print(text1 + a) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str
print函数的原型:print(self,*args,sep=' ',end='\n',file=None)
-
self 暂时不用管 它只是面向对象中的一个当前对象引用的标识
-
*args 可变长参数列表(数组)
>>> print(1) 1 >>> print(1,2,3) 1 2 3 >>> print(1,2,3,4,5,6,7,8,9) 1 2 3 4 5 6 7 8 9
-
sep 打印元素之间的间隔分隔 默认空格
>>> print(1,2,3,4,5,6,7,8,9) 1 2 3 4 5 6 7 8 9 >>> print(1,2,3,sep='#') 1#2#3
-
end 打印信息的结尾 默认换行
>>> print(1,2,3) 1 2 3 >>> print(1,2,3,end="haha") 1 2 3haha>>>
-
file 将打印的内容输出到一个文本文件中
关于格式化输出的一个问题
如果想将多种数据拼接在一起进行输出打印的话怎么办?
>>> name = "张三" >>> age = 20 >>> height = 1.83 >>> print("大家好我叫",name,",今年",age,"岁,身高为",height,"米") 大家好我叫 张三 ,今年 20 岁,身高为 1.83 米 >>> print("大家好我叫"+ name + ",今年" + age + "岁,身高为" + height + "米") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str >>> print("大家好我叫%s,今年%d岁,身高%f米"%(name,age,height)) 大家好我叫张三,今年20岁,身高1.830000米 >>> print("大家好我叫%s,今年%d岁,身高%.2f米"%(name,age,height)) 大家好我叫张三,今年20岁,身高1.830000米
input输入
input函数用于从控制台输入数据,但是一定要注意,输入的数据为字符串类型!
>>> input() 123 '123' >>> age = input() 123 >>> age '123' >>> age = input("请输入年龄:") # 输入带提示 并将输入的内容保存在age变量里 请输入年龄:12 >>> age '12' >>> int(age) 12 >>> age '12' >>> age = int(age) # 将字符串通过int()函数转化为整数 并重新赋值给age变量 >>> age 12 >>> age = int(input("请输入年龄:")) # 综上所述的结论 请输入年龄:12 >>> age + 1 13 >>> age = int(input("请输入年龄:")) 请输入年龄:123abc Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '123abc' >>> age = int(input("请输入年龄:")) 请输入年龄:haha Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'haha' # 输入的数据'haha'不能直接转为数字 除非是纯数字的字符串 >>> height = float(input("请输入身高:")) # int()将数字字符串转整数 float将数字字符串转浮点数 请输入身高:3.14 >>> height + 1 4.140000000000001 # 下面的代码暴露出一个问题 input一次只能负责一个数据的输入! 因为多个数据的输入都会组成一个字符串! >>> input("请输入年龄和身高:") 请输入年龄和身高:12,1.82 '12,1.82' >>> input("请输入年龄和身高:") 请输入年龄和身高:12 1.82 '12 1.82' # 使用eval函数包装input来进行多值输入 同时eval函数也会自动进行数字字符串的转换工具 >>> age = eval(input("请输入年龄:")) 请输入年龄:12 >>> age + 1 13 >>> height = eval(input("请输入身高:")) 请输入身高:3.14 >>> height + 1 4.140000000000001 # 下面是eval的多值输入用法 多个数值输入时 注意用英文逗号(,)分隔 >>> age,height = eval(input("请输入年龄和身高:")) 请输入年龄和身高:12,1.83 >>> age 12 >>> height 1.83
1.3 其他常用内置函数
int()函数
将其他类型的数据(字符串)转化为整数
>>> num = int("123") >>> num 123 >>> type(num) <class 'int'> >>> num = int("3.14") # int中传入的字符串必须是十进制整数形式的字符串 Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '3.14' >>> num = int(3.14) # 直接将浮点数转整数 去掉小数部分 只保留整数部分 >>> num 3 >>> num = int(5.99) >>> num 5
也可以将字符串指定为特定的进制形式来进行转换(进制位在2~36之间)
打印出来的结果永远是十进制
>>> int("1001",2) 9 >>> int("9C1A",16) 39962 >>> int("066",7) 48 >>> int("066",50) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: int() base must be >= 2 and <= 36, or 0 >>> int("abcdefgwxyz123",36) 1759567932504727647771
float()函数
将浮点型字符串转成浮点数字
>>> float(3) 3.0 >>> float("3.14") 3.14
str()函数
将其他类型的数据转为字符串形式
>>> num = 10 >>> num = str(num) >>> num '10' >>> type(num) <class 'str'> >>> num = str(3.14) >>> num '3.14' >>> str(True) 'True' >>> str([1,2,3,4,5,6]) '[1, 2, 3, 4, 5, 6]'
有一个好处就是可以将多个数据进行统一的拼接
>>> print("大家好我叫"+name+",今年"+str(age)+"岁,身高"+str(height)+"米") 大家好我叫张三,今年20岁,身高1.83米
len()函数
查看序列结构数据的长度
>>> s = "123456" >>> len(s) 6 >>> arr = [1,2,3,4] >>> len(arr) 4 >>> len(123) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: object of type 'int' has no len()
type()函数
查看当前数据对象的类型
id()函数
查看当前数据对象的地址
max()/min()函数
最大最小值函数
>>> max(1,2,3,4,5,6,7) 7 >>> min(1,2,3,4,5,6,7) 1
abs()函数
绝对值函数,如果是算整数的绝对值 返回结果就是整数,浮点数的结果是浮点数
>>> abs(-10) 10 >>> abs(-10.12) 10.12
bin()/oct()/hex()函数
这三个函数分别将至今只转化为二、八、十六进制的 返回的结果是字符串
>>> bin(120) '0b1111000' >>> oct(120) '0o170' >>> hex(120) '0x78'
ord()/chr()函数
ord:返回某个ASCII字符对应的编码
chr:返回编码对应的某个ASCII字符
>>> ord('a') 97 >>> ord('z') 122 >>> ord('A') 65 >>> ord('Z') 90 >>> ord('0') 48 >>> ord('9') 57 >>> chr(97) 'a'
random模块
主要产生随机数,和随机相关的东西
-
random.randint(a,b):返回
[a,b]
之间的一个随机整数 -
random.random():返回
[0.0,1.0)
之间的一个随机浮点数 -
random.randrange(start,stop,step):从范围内随机产生一个整数
>>> import random >>> random.randint(1,5) 5 >>> random.random() 0.12105828440314592
round()函数
四舍五入,基本不看符号 直接看小数部分是否需要取舍!
>>> round(4.1) 4 >>> round(4.6) 5 >>> round(-4.1) -4 >>> round(-4.6) -5
区别与Math模块中的 ceil()向上取整
floor向下取整
>>> math.ceil(4.1) 5 >>> math.ceil(4.6) 5 >>> math.ceil(-4.1) -4 >>> math.ceil(-4.6) -4 >>> math.floor(4.1) 4 >>> math.floor(4.6) 4 >>> math.floor(-4.1) -5 >>> math.floor(-4.6) -5
math模块
-
math.pi:圆周率
-
math.e:自然常数e
-
math.pow(a,b):求a的b次幂
-
math.fabs(x):绝对值
-
math.ceil(x):向上取整
-
math.floor(x):向下取整
-
math.sqrt(x):开方
-
math.sin(x):正弦 弧度单位
-
math.cos(x):余弦
-
math.tan(x):正切
-
math.degrees(x):将弧度转角度
-
math.radians(x):将角度转弧度
2 流程控制
2.1 流程控制概述
流程控制指的就是代码运行的逻辑、分支走向、循环控制,是真正体现我们程序执行顺序的操作
流程控制一般分为顺序执行、条件判断和循环控制
这里面体现了一种传统的编程中的“因果关系”,就是什么样的原因就会产生什么样的结果,有什么输入就会产生相应的输出,用一个输入不论执行多少次,必然得到同样的输出结果,所有的都是确定的,可控的。
2.2 条件判断/选择语句
回顾一下,我们之前写的代码 都是按照从上到下的流程依次逐句执行——顺序执行
任何代码 从宏观的角度来看 都是顺序执行的 只不过在宏观的顺序执行中 会发生一些分支和循环的情况
2.3 if结构
A部分的代码
if 条件(布尔表达式):
B部分的代码
C部分的代码
条件为True: A - B - C
条件为False: A - C
2.4 if-else结构
A部分的代码
if 条件:
B部分的代码
else:
C部分的代码
D部分的代码
条件为True: A - B - D
条件为False: A - C - D
2.5 if-else 嵌套
A部分的代码
if 条件1:
B部分的代码
if 条件2:
C部分的代码
else:
D部分的代码
E部分的代码
else:
F部分的代码
G部分的代码
条件1为True条件2为True: A - B - C - E - G
条件1为True条件2为False: A - B - D - E - G
条件1为False: A - F - G
2.5 if-elif结构
A部分的代码
if 条件1:
B部分的代码
elif 条件2:
C部分的代码
elif 条件3:
D部分的代码
else:
E部分的代码
F部分的代码
条件1为True: A - B - F
条件1为False条件2为True: A - C - F
条件1为False条件2为False条件3为True: A - D - F
条件1为False条件2为False条件3为False: A - E - F
3.0 Demo练习
Total =eval(input("请输入总金额:"))
cent = Total*100
Doall = cent // 100
Surplus_cnet = cent % 100
Quarters=Surplus_cnet // 25
Surplus_Coin =Surplus_cnet%25
Dime= Surplus_Coin/10
Surplus_Coin1=Surplus_Coin%10
A_nickel = Surplus_Coin1 // 5
Surplus_Coin2=Surplus_Coin1%5
Penny=Surplus_Coin1%5
print("%d:美元,%d个两角五分硬币,%d个一角硬币,%d个五分硬币,%d个美分" %(Doall,Quarters,Dime,A_nickel,Penny))
import turtle
turtle.penup()
turtle.goto(eval(input("请输入中心坐标:")))
x,y=eval(input("请输入长和宽"))
turtle.forward(x/2)
turtle.right(90)
turtle.pendown()
turtle.forward(y/2)
turtle.right(90)
turtle.forward(x)
turtle.right(90)
turtle.forward(y)
turtle.right(90)
turtle.forward(x)
turtle.right(90)
turtle.forward(y/2)
turtle.done()
a,b,c=eval(input("Enter a,b,c"))
G=b**2-4*a*c
r1 = (-b+(G)**0.5)/2*a
r2 =(-b-(G)**0.5)/2*a
if G > 0:
print("The roots are", r1, r2)
elif G == 0:
print("The roots are", r1)
else:
print("The equation has no real roots")
a,b,c,d,e,f= eval(input())
O=a*d-b*c
if O==0:
print("The equation has no real roots")
else:
x = (e * d - b * f) / O
y = (a * f - e * c) / O
print("x is",x,"y is",y)
import random
a=random.randint(10,99)
b = eval(input("请输入一个两位数"))
print("中奖号码:",a)
B = a%10
A = a//10
y=b%10
x=b//10
if A ==x and B==y:
print("奖金:10000")
elif A==y and B==x:
print("奖金:3000")
elif A==x or B==x or A==y or B==y:
print("奖金1000")
else:
print("没中奖 抱歉!")
a,b=eval(input("请输入月和年"))
if b//4 and b%100 !=0:
if a in [1,3,5,7,8,10,12]:
print("%d年%d月份有31天" %(b,a))
elif a in [4,6,9,11]:
print("%d年%d月份有30天"%(b,a))
else:
print("%d年%d月份有29天"%(b,a))
else:
if a in [1,3,5,7,8,10,12]:
print("%d年%d月份有31天" %(b,a))
elif a in [4,6,9,11]:
print("%d年%d月份有30天"%(b,a))
else:
print("%d年%d月份有28天"%(b,a))
import random
user=eval(input("请输入0,1,2代表剪刀石头布"))
computer=random.randint(0,2)
list = ["scissor","rock","paper"]
if computer -user ==0:
print("The computer is %s. You are %s.Tt is a draw" %(list[computer],list[user]))
elif computer -user == -1 or computer --user ==2:
print("The computer is %s. You are %s. You won" % (list[computer], list[user]))
else:
print("The computer is %s. You are %s.You lose" % (list[computer], list[user]))
x,y=eval(input("请输入一个坐标"))
if (x**2+y**2)**0.5==10:
print("该坐标在圆上")
elif (x**2+y**2)**0.5<10:
print("该坐标在园内")
else:
print("在园外")