Python小白逆袭大神 第一天课程内容
1.基本操作
#声明一个变量
age = 20#给age变量赋值为20
print(age)
print(type(age))#打印age变量的类型
str = "hello world"
print(str)#打印字符串str
print(type(str))#打印str变量类型
c= 1+1 #加法运算
print(c)#打印c的值
print(type(c))#打印c的变量类型
运行结果:
运行结果看出,a,c变量是整型的,str是字符串类型的,可以看到在python中不用申明变量类型,python会根据内容自动给出变量的类型。
2.操作符
#如果3>1 就输出3>1
if(3>1):
print("3>1")
#个如果2=2 就输出2=2
if(2==2):
print("2=2")
#如果3>1 和 2=2 同时满足,就输出同时满足
if(3>1 and 2==2):
print("同时满足")
运行结果:
3.if语句
判断num是否大于1 ,输出相应的结果
num = 2
if(num>1):
print("num大于1")
else:
print("num小于等于1")
运行结果:
num>2
3.for循环
i 从0变到4 打印i
for i in range(5):
print(i)
运行结果:
0
1
2
3
4
4.while循环
求99+97+…+3+1
sum=0
n=99
while n>0:
sum = sum+n
n = n-2
print(sum)
结果:
2500
5.while…else语句
count =0
while count<3:
print(count,"小于3")
count = count +1
else:
print(count,"大于或者等于与3")
运行结果
0 小于3
1 小于3
2 小于3
3 大于或者等于与3
6.break语句
break语句可以跳出for和while的循环体
n = 1
while n<=100:
if n>5:
break
print(n)
n+=1
运行结果:
1
2
3
4
5
7.continue语句
continue是跳出当前循环,整个循环不会跳出,break是跳出整个大循环
n=1
while n<10:
n=n+1
if n%2==0:
continue
print(n)
运行结果:
3
5
7
9
8.pass语句
pass是空语句,不做任何事情,一般可以用在函数里。
for letter in 'Room':
if letter =='o':
pass
print('pass')
print(letter)
运行结果:
R
pass
o
pass
o
m
9.数据结构
9.1Number
其中isinstance函数判断变量是否是某个数类型的实例
a=3
b=3.14
c=3+4j
print(type(a),type(b),type(c))
isinstance(a,int)
运行结果:
<class 'int'> <class 'float'> <class 'complex'>
True
9.2String(字符串)
a="hello"
b="Pyhton"
print("a+b输出结果:",a+b)
print("a[1:4]输出结果:",a[1:4])
运行代码:
a+b输出结果: helloPyhton
a[1:4]输出结果: ell
9.3List(列表)
list=['abcd',786,2,23,'runoob',70.2]
print(list[1:3])
tinylist=[123,'runoob']
print(list+tinylist)
运行结果:
[786, 2]
['abcd', 786, 2, 23, 'runoob', 70.2, 123, 'runoob']
9.4Tuple(元组)
元组中的元素不能被改变,但是列表元素可以。元组中的列表元素也是可以被改变的。
t=('abcd',786,2.23,'runoob',70.2)
t1=(1,)
t2=('a','b',['A','B'])
t2[2][0]='X'
t2
('a', 'b', ['X', 'B'])
9.5dict(字典)
字典可以根据关键字访问。
d={'Mike':95,'Bob':75,'Tracy':85}
d['Mike']
运行结果:
95
9.6set(集合)
set与字典很像,但是不存储value值,并且重复的key值会被自动过滤。
s=set([1,2,3])
print(s)
s=set([1,1,2,2,3,3])
print(s)
运行结果:
{1, 2, 3}
{1, 2, 3}