2.16 python实践

Python学习

随机数的生成

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import random

print( random.randint(1,10) )        # 产生 1 到 10 的一个整数型随机数 (含1和10) 
print( random.random() )             # 产生 0 到 1 之间的随机浮点数
print( random.uniform(1.1,5.4) )     # 产生  1.1 到 5.4 之间的随机浮点数,区间可以不是整数
print( random.choice('tomorrow') )   # 从序列中随机选取一个元素
print( random.randrange(1,100,2) )   # 生成从1到100的间隔为2的随机整数

a=[1,3,5,6,7]                # 将序列a中的元素顺序打乱
random.shuffle(a)
print(a)

python 文件读写

with open("文件路径", “读写方式(rb)”) as f:
f.write("字符串")

python 列表生成

a = range(5)
a = [2*x for x in a]

在python中添加中文注释

在文件头申明utf-8:# -- coding: UTF-8 -- 或者 #coding=utf-8

math函数的使用

import math
a = math.sin(1)
b = math.pi 	# 3.14159628.....

write 和 writelines 的区别

a = ["a", "b", "c"]
b = [1, 2, 3]
c = "abc"
with open("./test.txt", 'r') as f:
	f.write(c)	//只能为字符串
	f.writelines(a) 
	f.writelines(c) 	//可为字符串或字符序列
	# f.writelines(b)会报错

time

import time
 
localtime = time.asctime( time.localtime(time.time()) )
print "本地时间为 :", localtime

Google 开源项目风格指南

https://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_style_rules/

python 实践解决的问题

编码问题UnicodeEncodeError: ‘ascii’ codec can’t encode character u’\xa0’ in position 20: ordinal not in range(128)

https://stackoverflow.com/questions/9942594/unicodeencodeerror-ascii-codec-cant-encode-character-u-xa0-in-position-20

a = u'\xa0'	// 不可直接写入文件否则报错
a.encode("utf-8")
f.open("./test.txt")
f.write(a)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值