python可移植支持代码;用format.节省打印输出参数代码;math模块;

1、多平台移植代码:

#!/usr/bin/env python3

 这一行比较特殊,称为 shebang 行,在 Python 脚本中,你应该一直将它作为第一行。

请注意行中的第一个字符是井号(#)。以 # 开头的行为单行注释,所以安装了 Windows系统的计算机不读取也不执行这行代码。但是,安装了 Unix 系统的计算机使用这一行来找到执行文件中代码的 Python 版本。因为 Windows 系统忽略这一行,像 macOS 这样的基于 Unix 的系统使用这一行,所以加入这一行可以使脚本在不同操作系统的计算机之间具有可移植性。

2、.format节省打印变量输出:

复制代码
# 两个列表相加
a = [1, 2, 3, 4]
b = ["first", "second", "third", "fourth"]
c = a + b
print("打印abc: {0}, {1}, {2}".format(a, b, c))

# 两个数值相加
x = 4
y = 5
z = x + y
print("4+5={0:d}".format(z))
复制代码
  1. {0},{1},{2}表示:按顺序占位.format里的变量a,b,c
  2. {0:d}表示:.format里的变量z,d表示格式为整数
  3. 不使用 .format 的情况下得到同样的结果,那么就应该这样写: print("Output #3: ",a,", ",b,", ",c) ,但这是一段非常容易出现输入错误的代码。
#整数使用
x = 9
print("Output #4: {0}".format(x))
#3的4次方
print("Output #5: {0}".format(3**4))
print("Output #6: {0}".format(int(8.3)/int(2.7)))

-----------

Output #4: 9
Output #5: 81
Output #6: 4.0

-----------------------

3、浮点数

#浮点数
print("Output #7: {0:.3f}".format(8.3/2.7))
y = 2.5*4.8
print("Output #8: {0:.1f}".format(y))
r = 8/float(3)
print("Output #9: {0:.2f}".format(r))
print("Output #10: {0:.4f}".format(8.0/3))

----------------------------

Output #7: 3.074

Output #8: 12.0
Output #9: 2.67
Output #10: 2.6667

--------------------------

4、math模块库引入及使用:

math模块主要用于商业、科学、统计和其他应用

#!/usr/bin/env python3
from math import exp, log, sqrt

print("e的乘方#11: {0:.4f}".format(exp(3)))
print("自然对数#12: {0:.2f}".format(log(4)))
print("平方根#13: {0:.1f}".format(sqrt(81)))

-------------------------

e的乘方#11: 20.0855
自然对数#12: 1.39
平方根#13: 9.0

-------------------------

 注:更多math参考:Python 标准库(https://docs.python.org/3/library/index.html)

5、字符串

:s

#!/usr/bin/env python3

print("Output #14: {0:s}".format('I\'m enjoying learning Python.'))

-----------

Output #14: I'm enjoying learning Python.

---------------

 

.split()

#语句拆分split
string1 = "My deliverable is due in May"
string1_list1 = string1.split()
print(string1_list1)

----------

['My', 'deliverable', 'is', 'due', 'in', 'May']

------------------

posted @   晨光曦微  阅读(243)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示