美文网首页Python
9、内置函数

9、内置函数

作者: 代码充电宝 | 来源:发表于2019-04-26 09:30 被阅读1次
(1)内置函数
  • abs绝对值
>>> abs(-100)
100
>>> abs(100,2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: abs() takes exactly one argument (2 given)
>>> abs('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'str'
  • cmp比较
>>> cmp(1, 2)
-1
>>> cmp(2, 1)
1
>>> cmp(3, 3)
0
  • range(start, stop[, step]):创建整数列表
    • start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
    • stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
    • step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
>>>range(10) # 从 0 开始到 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11) # 从 1 开始到 11
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5) # 步长为 5
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3) # 步长为 3
[0, 3, 6, 9]
>>> range(0, -10, -1) # 负数
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
  • int str类型转换
>>> int('123')
123
>>> int(12.34)
12
>>> str(123)
'123'
>>> str(1.23)
'1.23'
  • sum求和
>>> L = [1,2,3,4,5]
>>> sum(L)
15
  • print函数
    • objects -- 复数,表示可以一次输出多个对象。输出多个对象时,需要用 , 分隔
    • sep -- 用来间隔多个对象,默认值是一个空格
    • end -- 用来设定以什么结尾。默认值是换行符 \n,我们可以换成其他字符串
    • file -- 要写入的文件对象
print(1) # 1
print('Hello World') # Hello World
print('aaa''bbb')    # aaabbb
print(1,'hello word')# 1 hello word
print("www","runoob","com",sep=".",end="@end")  # www.runoob.com@end
name = '张三'
score = 99
print('%s =  %d' %(name,score)) # 张三 =  99
    * 不支持数字和str混合输出
# TypeError: unsupported operand type(s) for +: 'int' and 'str'
print(11+"aa")

相关文章

网友评论

    本文标题:9、内置函数

    本文链接:https://www.haomeiwen.com/subject/tmwxnqtx.html