天天看点

python(内置函数)

一.python内置函数

1.id()返回对象的内存地址

a = 1
print (id(a))
print (id(1))      

2.int()用于将数据类型转换为整型

a = "1"
b = 2
print (int(a) + b)      

3.str()用于将数据类型转换为字符串

age = 18
name = "zhengying"
print (name + " age is " + str(age) + " years old")      

 4.len()返回对象(字符、列表、元组、字典、集合等)长度或项目个数

  •   int型不能使用len()函数
name = "xinfangshuo"

tu = ("zhao","qian","sun")

lt = ["zhao","qian","sun"]

dic = {"a":1,"b":2,"c":3,"d":4}

se = {"zhao","qian","sun","li","zhou"}

print (len(se))      

5.raw_input()/input()输入

#python2.x 中

raw_input("请输入账号:")
raw_input("请输入密码:")
print "登录成功"

name = raw_input("请告诉我你的名字:")
print "好的," + name      
#python3.x 中

#简单整数加法计算器
num1 = input("请输入第一个数字:")
num2 = input("请输入第二个数字:")
print (int(num1) + int(num2))      

6.type()用于查看字符类型

num = input("请输入第一个数字:")
print (type(num))      

7.abs()返回数字的绝对值

num1 = input("请输入第一个数字:")
num2 = input("请输入第二个数字:")
print (abs(int(num1) + int(num2)))      

8. 最大值、最小值、求和

  • max()返回最大值
  • min()返回最小值
  • sum()返回和
list1 = [1,3,4,5,34,79,12,4]
list2 = [1,3,4,5,79,12,4]

print (max(list1))
print (min(list1))
print (sum(list1)-sum(list2))      

9.open()打开文件

file4 = open('d:\\test1.txt','r')
for i in file4.readlines():
    print (i)
file4.close()      

10.range()用于创建一个整数列表,一般用在 for 循环中

print (range(5))
print (range(1,5))
print (range(0,5,2))      
list1 = []
for i in range(101):
    if i % 2 ==0:
        list1.append(i)
print (sum(list1))

sum1 = 0
for i in range(0,101,2):
    sum1 += i
print (sum1)      

11.enumerate()函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

  • enumerate(sequence, [start=0])
    • sequence  --  一个序列
    • start  --  下标起始位置。
Fruits = ["Apple","Banana","Orange"]

for i in enumerate(Fruits):
    print(i)

---> (0, 'Apple')
---> (1, 'Banana')
---> (2, 'Orange')      
Fruits = ["Apple","Banana","Orange"]

for i in enumerate(Fruits,1):
    print(i)

---> (1, 'Apple')
---> (2, 'Banana')
---> (3, 'Orange')      
Fruits = ["Apple","Banana","Orange"]

for x,y in enumerate(Fruits,1):
    print(x,":",y)

---> 1 : Apple
---> 2 : Banana
---> 3 : Orange      

作者:多测师高级讲师_郑sir

微信:ZhengYing8887

出处:https://www.cnblogs.com/ZhengYing0813/

备注:本文版权归作者所有,欢迎转载和添加作者微信探讨技术,但未经作者同意必须在文章页面给出原文链接,否则保留追究法律责任的权利。

继续阅读