python基础---->python的使用(一)

  这里面记录一些python的一些基础知识,数据类型和变量。幸而下雨,雨在街上泼,却泼不进屋内。人靠在一块玻璃窗旁,便会觉得幸福。这个家还是像个家的。

python的一些基础使用

一、python中的数据类型和变量知识

print("%s is number %d!" % ('python', 34))

# 把内容写到文件中
logfile = open('huhx.txt', 'a')
print('Fatal error: invalid input', file=logfile)
logfile.close()

content = input("please input:")
print(content)

python的注释有两种,一种是上述的使用#号,另外一种是文档字符串的注释。用在模块、类或者函数的起始处,起到在线文档的功能。与普通注释不同,文档字符串可以在运行时访问,也可以用来自动生成文档。

def foo():
    "this is a doc string"
    return True

python中的一些运算符,这里列举一些与java所不同的地方。

# **表示乘方, /表示传统除法,//表示整除时的商, %表示余数
print(3 ** 2, 5 / 3, 5 // 3, 5 % 3, sep=" ")  # 9 1.6666666666666667 1 2

python中的一些比较运算符号,其中<>和!=一样表示不等于,但是推荐使用!=。

<  <=  >  >=  ==  !=  <>

python中提供的逻辑运算符号:and  or  not分别对应于java中&& || !。注意的是python支持3 < 4 < 5的这种写法。

print(3 < 4 and 4 < 5, 3 < 4 < 5, sep=" ") # True True

python也支持增量赋值,但是不支持java中自增长++n什么。Python会将下述的 --n 解释为-(-n) 从而得到 n , 同样 ++n 的结果也是 n.

num = 45
num += 55
print(num, --num, ++num, sep=" ") # num++写法会报错,打印结果:100 100 100 

以下的对象的布尔值为False

None, False, 所有的值为零的数, 0 (整型), (浮点型), 0L (长整型), 0.0+0.0j (复数), "" (空字符串), [] (空列表), () (空元组), {} (空字典)

二、python中的数字与字符串

Python 支持五种基本数字类型:int (有符号整数),long (长整数),bool (布尔值),float (浮点值)和complex (复数)。

python中的加号( + )用于字符串连接运算,与java不同的是星号( * )可以用于字符串重复。

name = "huhx"
print(name * 2, name + "linux") # huhxhuhx huhxlinux

但是需要注意的是,如果字符串+一个数字的话,就会报错。

print("huhx" + 1) # TypeError: must be str, not int

对于单个字符的编码,Python提供了ord()函数获取字符的整数表示,chr()函数把编码转换为对应的字符:

print(ord(''), chr(25991)) # 20013 文

python中的decode与encode函数,下述的b'xe4xb8xadxe6x96x87'表示的是以字节为单位的bytes。

# b'xe4xb8xadxe6x96x87' 中文
print('中文'.encode('utf-8'), b'xe4xb8xadxe6x96x87'.decode('utf-8'))

len()函数计算的是str的字符数,如果换成bytes,len()函数就计算字节数:

print(len('中文'), len('中文'.encode('utf-8'))) # 2 6

三、列表list与元组tuple的使用

  • list是一种有序的集合,可以随时添加和删除其中的元素。

声明创建一个列表,可以看到可以有不同的类型。

fruit = ['apple', 'orange', 45]

得到列表的长度:

print(len(fruit)) # 3

用索引来访问list中每一个位置的元素:

print(fruit[0], fruit[1], fruit[2]) # apple orange 45

得到最后一个元素:

print(fruit[len(fruit) - 1], fruit[-1]) # 45 45

以下列举一下关于list的一些操作:

# 追加元素到末尾
print(fruit.append('huhx')) # None
# 元素插入到指定的位置
print(fruit.insert(1, 'linux')) # None
# 删除list末尾的元素
print(fruit.pop()) # huhx
# 删除指定位置的元素
print(fruit.pop(0)) # apple
# 某个元素替换成别的元素
fruit[0] = 'pear'
  • tuple和list非常类似,但是tuple一旦初始化就不能修改
classmate = ('huhx', 'linux', 'tomhu')
print(classmate[1], classmate.index('linux'))  # linux
friend = 'huhx'
if friend in classmate:
    print(classmate.index(friend))  # 0

 对于tuple中的index方法,如果元素不在tuple中。那么会报错。

print(classmate.index('hu'), 'huhx') # ValueError: tuple.index(x): x not in tuple

tuple一旦定义就不能变了,它也没有append(),insert()这样的方法。其他获取元素的方法和list是一样的,你可以正常地使用classmate[0],classmate[-1],但不能赋值成另外的元素。

当tuple只有一个元素的时候,定义需要注意一下。如下

t = (1) # 这里定义和t=1是一样的。()被认为是小括号
print(t + 45) # 46
t = (1,) # 这是定义一个元素的正确写法
print(t[0]) # 1

四、字典map与set的使用

 map的创建有以下的几种方式:

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

 访问map中的值:需要注意的是python对于map、turple等的一些取值操作。如果没有对应的key,就会报错。

dataMap = {'name': 'huhx', 'password': '123456', 8: 8} # map的创建
# print(dataMap['username']) # KeyError: 'username'
if 'name' in dataMap:
    print(dataMap['name']) # huhx
print(dataMap.get('username', 'linux')) # linux
# map的遍历,有以下两种方式
for key in dataMap: print('key = %s, and value = %s' % (key, dataMap.get(key))) for key, item in dataMap.items(): print(key, item)

 map的更新:涉及到添加元素或者修改元素

dataMap['name'] = 'liuling' # modify
dataMap['age'] = 34 # add

map删除字典元素或者删除字典

del dataMap['name'] # 删除key=name的元素
dataMap.clear() # 删除dataMap中所有的元素
del dataMap # 删除dataMap
dataMap.pop('name') # 删除并返回key=name的value值

五、int函数的使用

int函数能够将字符串转换成整数,也可以将浮点数转换成整数。

print(int(12.2)) # 12
print(int('12.2')) # ValueError: invalid literal for int() with base 10: '12.2'
print(int('34')) # 34

六、列表和字符串的遍历

if __name__ == '__main__':
    aList = [1, 2, 'huhx', '4']
    content = 'huhx'

    # 列表的遍历
    for item in aList:
        print(item)

    for index in range(len(aList)):
        print('%s (%d)' % (aList[index], index))

    for index, value in enumerate(aList):
        print(index, value)

    # 字符串的遍历
    for string in content:
        print(string)

    # range函数的使用
    for num in range(3):
        print(num)

七、python中一些内建函数的使用

complex(3, -45.4)      # (3-45.4j)
float('23.334')        # 23.334
divmod(10, 4)          # (2, 2)
round(3.49999)         # 3
round(3.49999, 1)      # 3.5

int(), round(), math.floor()函数的区别:

函数 int()直接截去小数部分。(返回值为整数)
函数 floor()得到最接近原数但小于原数的整数。(返回值为浮点数)
函数 round()得到最接近原数的整数。(返回值为浮点数)

pow函数的使用:如果有第三个参数,那么就是结果取余操作。

pow(3, 2)        # 9
pow(3, 2, 4)     # 1

进制转换函数:

hex(234)  # 0xea
oct(245)  # 0o365

ASCII 转换函数:

ord('a')  # 97
chr(97)   # a

编码与解码函数:

'中文'.encode('utf-8')                           # b'xe4xb8xadxe6x96x87'
b'xe4xb8xadxe6x96x87'.decode('utf-8')     # 中文

友情链接

原文地址:https://www.cnblogs.com/huhx/p/baseuselearnpython1.html