Python语法基础

1.基本数据类型

数值型

输入:
x=4
print (x),type(x)#使用tpye()来查看变量x的数据类型
输出:
4
(None, int)
-------------------------------------------------------------
输入:
print (x+1)#加
print (x-1)#减
print (x*2)#乘
print (x**2)#乘方
输出:
5
3
8
16
-------------------------------------------------------------
输入:
x+=1#自加
print (x)
x*=2#自乘
print (x)
#需要注意的一点就是Python中没有++、--运算符
输出:
5
10
--------------------------------------------------------------
输入:
y=2.5
print(type(y))
print (y+1,y-1,y*2,y**2)#连续输出
输出:
'<class 'float'>'
3.5 1.5 5.0 6.25
--------------------------------------------------------------

布尔型

用于指定真假的类型,布尔型,包含真(True)和假(False):

输入:
t,f=True,False
print (type(t))
输出:
'<class 'bool'>'
--------------------------------------------------------
输入:
print (t and f)
print (t or f)
print (not t)
print (t != f)
输出:
False
True
False
True
---------------------------------------------------------

字符串型

输入:
A='hello'
B='world'
print (A,len(A))
输出:
hello 5
------------------------------------------------------
输入:
AB=A+' '+B
print (AB)#用+号实现字符串拼接
输出:
hello world
------------------------------------------------------
输入:
AB12='%s %s %d'%(A,B,12)#类似sprintf的格式化输出
print (AB12)
输出:
hello world 12
------------------------------------------------------
输入:
print (A.capitalize())#首字母大写
print (A.upper())#全字母大写
print (A.lower())#全字母小写
print (A.rjust(7))#右对齐
print (A.center(7))#居中输出
print (A.replace('l','(elll)'))#字符串替代
print ('        world   '.strip())#去掉两侧空白
输出:
Hello
HELLO
hello
  hello
 hello 
he(elll)(elll)o
world

其他字符串的操作看这里

2.容器

内置的容器用得非常非常多,包括: lists, dictionaries, sets, and tuples.

Lists/列表

输入:
a=[1,2,3]#建立一个列表
print (a)#将这个列表打印出来
print (a[1])#打印这个列表的第1号元素,列表中的第一个元素是第0号元素,以此类推。
print (a[-1])#打印这个列表的最后一个元素(索引用-1表示)
输出:
[1, 2, 3]
2
3
-----------------------------------------------------
输入:
a[2]='xiaoxigua'#列表中元素的类型可以是不同的
print (a)
输出:
[1, 2, 'xiaoxigua']
-----------------------------------------------------
输入:
a.append('happy')#可以使用append在列表的尾部添加新的元素
print (a)
输出:
[1, 2, 'xiaoxigua', 'happy']
-----------------------------------------------------
输入:
aa=a.pop()#弹出列表中最后一个元素
print (aa,a)
输出:
happy [1, 2, 'xiaoxigua']

关于list更多的操作和内容可以看这里.

列表切片

输入:
nums=list(range(5))#建立一个元素为0-4的列表
print (nums[2:4])#取下标[2,4)左闭右开的元素,注意下标从0开始
print (nums[2:])#取下标2到最后一个元素,注意下标从0开始
print (nums[:2])#取下标[0,2)左闭右开的元素,注意下标从0开始
print (nums[:])#取整个列表的元素
print (nums[:-1])#取下标0到最后一个元素
nums[2:4]=[8,9]#修改下标[2,4)左闭右开的元素的值,注意下标从0开始
print (nums)
输出:
[2, 3]
[2, 3, 4]
[0, 1]
[0, 1, 2, 3, 4]
[0, 1, 2, 3]
[0, 1, 8, 9, 4]

循环

可以对list里面的元素做循环。

输入:
animals=['喵喵','汪汪','鸭鸭']
for animal in animals:
    print (animal)
输出:
喵喵
汪汪
鸭鸭
-----------------------------------------------------------
输入:
animals = ['喵星人', '汪星人', '火星人']
for idx, animal in enumerate(animals):
    print 'NO.%d: %s' % (idx + 1, animal)
输出:
NO.1: 喵喵
NO.2: 汪汪
NO.3: 鸭鸭

List comprehensions:

如果对list里面的元素都做一样的操作,然后生成一个list,用它最快了,这绝对会成为你最爱的python操作之一:

# 求一个list里面的元素的平方,然后输出,先试试看for循环的写法
输入:
a=[0,1,2,3,4]
square=[]
for i in a:
    square.append(i**2)
print (square)
输出:
[0, 1, 4, 9, 16]
----------------------------------------------------------------
#然后用list comprehension来写
输入:
b=[0,1,2,3,4,5]
square=[i**2 for i in b]
print (square)
输出:
[0, 1, 4, 9, 16, 25]
----------------------------------------------------------------
#还可以加元素,设置过滤条件来筛选想要的元素。
输入:
c=[0,1,2,3,4,5,6]# 把所有的偶数取出来,平方后返回
even_square=[i**2 for i in c if i%2==0]
print (even_square)
输出:
[0, 4, 16, 36]

字典

存储键值对(key => value)的数据结构, 类似Java中的Map,这真的是使用频度相当高的数据结构:

输入:
d={'cat':'cute','dog':'furry'}#建立字典
print (d['cat'])#根据key取value
print ('cat' in d)#查一个元素是否在字典中
输出:
cute
True
------------------------------------------------------------
输入:
d['fish']='wet'#设定键值对
print (d['fish'])#输出修改后的内容
输出:
wet
------------------------------------------------------------
输入:
print (d['monkey'])#不是d的键,输出会报错
输出:
keyerror
------------------------------------------------------------
输入:
print (d.get('monkey','无对应值'))#默认输出‘无对应值’(取不到key对应的value时)
print (d.get('fish','无对应值'))
输出:
无对应值
wet
------------------------------------------------------------
输入:
del d['fish']#删除字典中的键值对
print (d.get('fish','无对应值'))#此时fish的值就没有了
输出:
无对应值

同样的,你其他想了解的字典相关的操作和内容可以看 这里.

你可以这样循环python字典取出你想要的内容:

输入:
d={'human':2,'dog':4,'spider':8}
for animal in d:
    print ('A %s has %d legs'%(animal,d[animal]))
输出:
A human has 2 legs
A dog has 4 legs
A spider has 8 legs
#用items函数可以同时取出键值对:
输入:
d={'human':2,'dog':4,'spider':8}
for animal,legs in d.items():
    print ('A %s has %d legs'%(animal,legs))
输出:
A human has 2 legs
A dog has 4 legs
A spider has 8 legs

Dictionary comprehensions: 和list comprehension有点像,但是生成的是字典:

输入:
nums=[1,2,3,4,5,6]
even_num_to_square={x:x**2 for x in nums if x%2==0}
print (even_num_to_square)
输出:
{2: 4, 4: 16, 6: 36}

sets

可以理解成没有相同元素的列表(当然,显然和list是不同的):

输入:
animals={'cat','dog'}
print ('cat' in animals)#判定元素是否在sets中
print ('fish' in animals)
输出:
True
False
----------------------------------------------------
输入:
animals.add('fish')#往set中添加元素
print ('fish' in animals)
print (len(animals))
输出:
True
3
-----------------------------------------------------
输入:
animals.add('cat')#如果元素已经在set中了,add指令不会有什么改变
print (len(animals))
animals.remove('cat')#删除一个元素
print (len(animals))
输出:
3
2
----------------------------------------------------
#循环的方式和list很像
输入:
animals ={'cat','dog','fish'}
for index,animal in enumerate(animals):
    print('NO%d: %s'%(index+1,animal))
输出:
NO1: dog
NO2: cat
NO3: fish
-----------------------------------------------------
#Set comprehensions
输入:
from math import sqrt
print ({int(sqrt(x)) for x in range(50)})
输出:
{0, 1, 2, 3, 4, 5, 6, 7}

元组

和list很像,但是可以作为字典的key或者set的元素出现,但是一整个list不可以作为字典的key或者set的元素的:

输入:
d={(x,x+1):x for x in range(10)}
t=(5,6)
print (d[t])
print (d[(7,8)])
输出:
5
7

3.函数

#用 def 就可以定义一个函数,就像下面这样:
输入:
def sign(x):
    if x>0:
        return '+'
    elif x<0:
        return '-'
    else:
        return 0
for x in [-2,0,2]:
    print (sign(x))
输出:
-
0
+
----------------------------------------------------------
函数名字后面接的括号里,可以有多个参数
输入:
def hello(name,loud=False):
    if loud==False:
        return 'Hello,%s.'% name
    else:
        return 'HELLO! %s!'%name.upper()
print (hello('Bob'))
print (hello('Fred',loud=True))
输出:
Hello,Bob.
HELLO! FRED!

4.类

输入:
class Greeter:
    #构造函数
    def __init__(self,name):
        self.name=name#创一个实例变量
    #类成员函数
    def greet(self,loud=False):
        if not loud:
            print ('Hello,%s'%self.name)
        else:
            print ('HELLO! %s'%self.name.upper())
g=Greeter('Fred')#构造一个类
g.greet()#调用函数
g.greet(loud=True)#调用函数
输出:
Hello,Fred
HELLO! FRED

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值