遍歷字典python
dic1 = {'a':100, 'b':100, 'c':100, 'd':100}git
例子1函數
for k in dic1:ui
print korm
例子2ip
for k in dic1:ci
print k dic1[k]字符串
例子3input
for k in dic1:string
#,爲去掉換行符
print "%s-->%s" % (k, dic1[k]),
例子4
#使用iteritems()和for循環遍歷字典中的值
for k, v in dic1.iteritems():
print k, v
例子5
#使用for循環寫乘法口訣
for i in xrange(1,10):
for k in xrange(1,i+1):
print "%s X %s = %s" % (i, k, i*k),
for循環的else退出,for循環結束後纔會執行else內容
例子6
#for循環的幾種語法用法
import sys
import time
for i in xrange(10):
if i == 1:
continue
elif i == 3:
pass
elif i == 5:
break
elif i == 7:
sys.exit()
else:
print i
time.sleep(1)
print "2"
例子7使用for循環遍歷文件內容
#!/usr/bin/python
fd = open('/work/python/2.txt')
for line in fd:
print line,
while循環使用在有條件的循環
例子1
#!/usr/bin/python
x = ''
while x != 'q':
print 'hello'
x = raw_input("please input :")
if not x:
break
if x == 'quit'
continue
print 'continue'
else:
print 'world'
使用while循環遍歷文件
例子2
fd = open('/work/python/1.txt')
while True:
line = fd.readline()
if not line:
break
print line,
fd.close()
例子2使用with語法打開文件,能夠不用close關閉文件
with open('/work/python/1.txt') as fd:
while True:
line = fd.readline()
if not line:
break
print line,
整型(int型,只保存整數)
經常使用函數及方法
可以使用abs()函數取絕對值
abs(...)
abs(number) -> number
Return the absolute value of the argument.
例子:
a=-10
print (abs(a))
輸出爲10
可以使用dir()函數查看該整型有哪些方法可使用
dir(...)
dir([object]) -> list of strings
If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attribut
es
of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
for a module object: the module's attributes.
for a class object: its attributes, and recursively the attributes
of its bases.
for any other object: its attributes, its class's attributes, and
recursively the attributes of its class's base classes.
print (dir(a))
浮點型(float型,能夠保存小數)
經常使用函數及方法
round函數
round(...)
round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number. Precision may be negative.
b=2.3333
print (round(b))
輸出爲2
布爾型
下面是python中布爾操做:
x or y:if x is false,then y, else x
x and y:if x is false, then x, else y
not x:if x is false, then True, else False
python的字符串和經常使用方法
字符串是有下標的,經常使用方法
a='1234567'
print (a[0],a[5])
輸出1 6
find()查找
a='1234567'
print (a.find('45'))
輸出3 返回子字符串下標
join()插入
print ('99'.join('aaa'))
輸出a99a99a
split()拆分
a='1234567'
print (a.split('45'))
輸出['123', '67']列表
replace()替換
a='1234567'
print (a.replace('123','abc'))
輸出abc4567
strip()去掉字符串先後空格
b=' a b c '
print (b.strip())
輸出 a b c
format()
print "{0} is {1} years old".format("FF", 99)
print "{} is {} years old".format("FF", 99)
print "Hi, {0}! {0} is {1} years old".format("FF", 99)
print "{name} is {age} years old".format(name = "FF", age = 99)