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()输入

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

name = raw_input("请告诉我你的名字:")
print "好的," + name
#简单整数加法计算器
num1 = raw_input("请输入第一个数字:")
num2 = raw_input("请输入第二个数字:")
print int(num1) + int(num2)

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

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

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

num1 = raw_input("请输入第一个数字:")
num2 = raw_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

 

你可能感兴趣的:(python(内置函数))