python 学习python语法的片段

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 学习python语法的片段相关的知识,希望对你有一定的参考价值。

# test for hex function
num = 16
print (hex(num)) # 0x10 convert a integer num to hex number;
num = '1'
print(int(num)) # convert a string or float num into int number
print(float(num))# convert a string or int num into float number

# test 2 for global num and id() function 
num = 20
def fun():
	num = 100
	print id(num) #the num object in this function is different from the num outside the function,so the address is different
	print num
fun()
print num # 20 
print id(num) #id function return the address of the object 

# test 3 for global num
def global_num():
	global num # declare using a global num
	num = 10
	print num
	print id(num)

num = 100
global_num()
print id(num) # two address is the same
print num
 
# test 4 use of len function
name = ['bruce','Li','Chen']
name1 = ('bruce',)
name2 = {'bruce':80,'Chen':100}
print len(name)# return the length of the name list
print len(name1)
print len(name)

# test 5 use of locals function
def locals_test():
	num = 1;
	num2 = 2
	print locals()
	print len(locals())
locals_test() # return {'num':1,'num2':2} <2></2>

# test 6 use of list function
# the same with tuple function

tmp = ['hello','world',1]
copy_tmp = list(tmp)
print copy_tmp #['hello', 'world', 1]
copy_tmp = list()
print copy_tmp  #[]

# test 7 use of raw_input function
s = raw_input('--> ') #--> write to the standard output
print s; #if you input 'Hello world',then output 'hello world'

# use of open function and try...except
try:
	f = open('a.txt','r')  # return a file openjec
except IOError:
	print 'can\'t find the file'
else:
	print 'Other errors happen'

# test 8 use of dir function  return the list of names in the current local scope. 
class Teacher:

	def __init__(self,name,age):
		self.name = name
		self.age = age

instance = Teacher('bruce',12)
print dir(instance)  #['__doc__', '__init__', '__module__', 'age', 'name']
 
# use of max function 
fruit = ['apple','banala','juice']
num = [1,2,3]
print max(num)
print max(fruit)
 
# use of type function 
fruit = "apple"
num = 1
print type(fruit) #<type 'str'> 
print type(num) #<type 'int

以上是关于python 学习python语法的片段的主要内容,如果未能解决你的问题,请参考以下文章

《Python学习之路 -- Python基础之切片》

python小白学习记录 多线程爬取ts片段

python 机器学习有用的代码片段

python ipython:机器学习片段

使用 Python 代码片段编写 LaTeX 文档

学习笔记:python3,代码片段(2017)