Python Process Control conditions
Summarize
Cycle
For loop
Script Simple to use
For typical 1+...+100python scripts
Small details of the sequence
Iterative traversal
Simple operation
Inline for Loop Classic-99 multiplication table
For loop
Common keywords
Guess random number
While
While compared to for
While loop
Ways to open a file
Ways to read files
Summary
Method for traversing a file
Summary:
Summarize
While loop
With+while Cycle
Summarize Python Process Control conditions
If expression: # expression: statement (s) # code block ELIF expression: statement (s) Else exdpression: Statement (s)
- Score Judgment
For example
[[email protected] day02]# cat 2.py #!/usr/bin/pythonscore = Int (raw_input ("Please input num:")) if score >=: p Rint ' A ' print ' very good ' elif score >=: print ' B ' print ' good ' elif score >=: print ' C '
print ' Pass ' else: print ' Game over ' print ' END '
[[email protected] day02]# python 2.py * input num:2game overend[[email protected] day02]# python 2.py please input Num:70cpassend[[email protected] day02]# python 2.py Please input num:89bgoodend[[email protected] day02]# python 2.py P Lease input Num:90avery Goodend
- Uppercase and Lowercase methods
For example
[email protected] day02]# cat 4.py #!/usr/bin/pythonyn = raw_input ("Please input [yes/no]:") yn = yn.lower () #用到一个字符串 Method: Uppercase replaces lowercase. The opposite is. Upperif yn = = ' y ' or yn = = ' yes ': print ' programe is runing ... ' elif yn = ' n ' or yn = = ' no ': print ' Progr Ame is exit ... "Else: print" Please input [yes/no]: "
[email protected] day02]# python 4.py please input [yes/no]: Yprograme is runing ... [email protected] day02]# python 4.py please input [yes/no]: Yesprograme is runing ... [email protected] day02]# python 4.py please input [yes/no]: Nprograme is exit ... [email protected] day02]# python 4.py please input [yes/no]: Noprograme is exit ... [email protected] day02]# python 4.py please input [yes/no]: aplease input [yes/no]:
Summarize
除了shell之外,1返回的是正确,0返回的是错误。逻辑值(bool)包含了两个值:True:表示非空的量(比如:string,tuple,list,set,dictonary),所有非零数。Fasle:表示0,None,空的量等。多条件判断可以用and,or 等
Cycle
- A loop is a structure that causes the program to repeat a certain number of times.
- The same is true for conditional loops, where the condition becomes false and the loop ends.
For loop
- For loop: In sequence, use for loop traversal.
- Grammar:
For Iterating_var in sequence: statement (s)
For example
In [4]: List1 = [1,2,3,4,5]in [5]: For i in List1: ...: print I ... : 12345In [6]: range (5) out[6]: [0, 1, 2 , 3, 4]in [7]: Range (0,10,2) out[7]: [0, 2, 4, 6, 8]in [8]: Range (0,10,3) out[8]: [0, 3, 6, 9]in [9]: For I in range:
...: print I ... : 0123456789
Script Simple to use
[[email protected] day02]# cat 5.py #!/usr/bin/pythonfor i in Range (1,11): If I% 2 = = 0: print i[[email protected ] day02]# vim 5.py[[email protected] day02]# python 5.py [2, 4, 6, 8, 10][[email protected] day02]# cat 5.py #!/usr/bin/py Thonprint [I for I in range (1,11) if I% 2 = = 0][[email protected] day02]# vim 5.py[[email protected] day02]# python 5.py [1, 9, 25, 49, 81] [[email protected] day02]# cat 5.py #!/usr/bin/pythonprint [i**2 for me in range (1,11) if I% 2! = 0]
For typical 1+...+100python scripts
#!/usr/bin/pythonsum = 0for i in range (1,101): sum = sum + i # sum + = IPrint sum
Small details of the sequence
range 占用内存xrange 遍历的时候才会占用内存推荐使用xrange
Iterative traversal
- Traversal sequence: Takes each element of the sequence out.
-Directly from the sequence to take the value
-use index to fetch values
Simple operation
- iterating through the dictionary
for example
in [one]: Dict.fromkeys (' ABCDE ', +) #利用dict. Fromkeys method Create dictionary out[11]: {' A ': 100 , ' B ': +, ' C ': +, ' d ': +, ' e ': 100}in []: Dic1 = Dict.fromkeys (' abcde ', ') in []: dic1out[13]: {' A ': +, ' B ': 1 XX, ' C ': [+], ' d ': +, ' e ': 100}in []: for K in Dic1: #默认的情况下是取key ...: Print K ...-acbedin [+]: for K in Dic1: #通过索引取出value ...: Print K, dic1[k] ...: A 100c 100b 100e 100d 100In []: for K in Dic1: #也可以通过占位符, print out the desired effect ...: print "%s-to-%s"% (k, dic1[k]) ...: A--100c--100b-- 100e-100d-100In [+]: for K in Dic1: ...: print "%s-to-%s"% (k, dic1[k]), #用, number can suppress line breaks :---------------------and--------100In []: for K, V in Dic1.items ():p rint K, V #也可以通过itmes的方法取出key, Valuea 100c 100b 100e 100d 100In [+]: for K, V in Dic1.iteritems ():p rint K, VA 100c 100b 100e 10 0d
Inline for Loop Classic-99 multiplication table
[[email protected] day02]# cat 7.py #!/usr/bin/pythonfor i in Xrange (1,10): #乘法表不需要0, so value from 1 for J in Xrange (1,i +1): # (1,3) will be evaluated from 1, 2, excluding 3 print "%sx%s=%s"% (j, I, J*i), #逗号抑制内部循环换行 print #内部循环结束进行换行输出 [[ Email protected] day02]# python 7.py1x1=11x2=2 2x2=41x3=3 2x3=6 3x3=91x4=4 2x4=8 3x4=12 4x4=161x5=5 2x5=10 3x5=15 4x5=20 5 x5=251x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=361x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=491x8=8 2x8=16 3x8=24 4x8=32 5x8 =40 6x8=48 7x8=56 8x8=641x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81
For loop
- For
- Else
- The For loop executes the Else statement if it ends normally.
Common keywords
Breakcontinueexitpass
Operation
For example
[email protected] day02]# cat 8.py #!/usr/bin/pythonimport timeimport sysfor i in Xrange (): if i = = 5: continue elif i = = 6: Pass elif i < 9: time.sleep (1) print i elif i = = 9: sys.exit (Ten) Else: print "EMD" print "hahaha"
Guess random number
[[email protected] day02]# cat 10.py #!/usr/bin/env pythonimport randomright = Random.randint (1,20) Count = 0while count &L T 6: num = input (' Please input a number: ') if num = = Right:print ' is Right ' break else:if num > right: Print "Binger than right" else:print "Samller than right" count + = 1
Whilewhile compared to for
while expression: statement(s)
# # operation
Example 1
[[email protected] day02]# cat 11.py #!/usr/bin/pythonn = 0while True: if n = = Ten: Break print n, ' hello ' n + = 1
Output
[[email protected] day02]# python 11.py 0 hello1 hello2 hello3 hello4 hello5 hello6 hello7 hello8 hello9 Hello
Example 2
[[email protected] day02]# cat 12.py #!/usr/bin/pythonwhile True: string = raw_input (' Please input string: ') I F string = = "Q": Break
Output
[email protected] day02]# python 12.py please input string:eplease input string:wplease input string:q
Example 3
[[email protected] day02]# cat 13.py #!/usr/bin/pythonx = ' while x! = ' Q ': x = raw_input (' Please input: ')
Output
[email protected] day02]# python 13.py please input:eplease input:wplease input:q
Ways to open a file
R: Open in read mode
W: Open in write mode
A: Open in Append mode
r+: Open in read-write mode
w+: Open in read-write mode
A +: Open in read/write mode
RB: Open in binary read mode
WB: Open in binary write mode
AB: Open in binary append mode
rb+: Open in binary read/write mode
wb+: Open in binary read/write mode
ab+: Open in binary read/write mode
- Attention
Opening a file with W overwrites the original file
Ways to read files
in [+]: FD. Fd.close fd.errors fd.isatty fd.newlines fd.readinto fd.seek fd.truncate fd.xreadlines fd.closed Fd.fileno fd.mode fd.next fd.readline fd.softspace fd.write Fd.encoding fd.flush fd.name fd.read fd.readlines Fd.tell fd.writelines in [ []: FD = open ('/tmp/tmp.txt ') in [to]: Fd.read () out[31]: ' 1\n2\n3\n ' in [+]: FD = open ('/tmp/tmp.txt ') in []: Fd.readline () out[33]: ' 1\n ' in [the]: Fd.readline () out[34]: ' 2\n ' in [+]: Fd.readline () out[35]: ' 3\n ' in [approx]: Fd.readline () out[36]: ' ' In [PNS]: FD = open ('/tmp/tmp.txt ') in []: Fd.readlines () out[38]: [' 1\n ', ' 2\n ', ' 3\n ']in [all]: Fd.readlines () out[39]: [] In [max]: FD = open ('/tmp/tmp.txt ') in [Max]: Fd.next () out[41]: ' 1\n ' in [[]: Fd.next () out[42]: ' 2\n ' in []: Fd.next () out[43 ]: ' 3\n ' in []: Fd.next ()--------------------------------------------------------------------------- Stopiteration Traceback (most recent) <ipython-input-44-3df4eef70a28> in <module> ()----> 1 F D.next ()
Summary
fd.read():返回的是字符串fd.readline():返回的是每一行字符串fd.readlines():返回的是一行列表
Method for traversing a file
[[email protected] day02]# Cat/tmp/tmp.txt123[[email protected] day02]# cat 14.py #!/usr/bin/pythonfd = open ('/tmp/tmp.t XT ') for line in Fd.readlines (): print line,[[email protected] day02]# python 14.py 123[[email protected] day02]# Cat 1 4.py > 15.py[[email protected] day02]# vi 15.py [[email protected] day02]# cat 15.py #!/usr/bin/pythonfd = open ('/tmp/t Mp.txt ') for line in FD: print line,[[email protected] day02]# python 15.py 123
Summary:
print line后面加个逗号,可以抑制print默认的换行。for line in fd.readlines(): 这种方法会全部加在到内存中,不建议使用for line in fd: 这种方法类似于fd.next(),没循环一次加在一行,推荐使用。
Summarize
打开文件的时候要使用w方法会覆盖原来的文件,谨慎使用read(),readline()readlins()的区别是字符串和列表使用方法的时候选择最小消耗资源的方式
While loop
[[email protected] day02]# cat 16.py #!/usr/bin/pythonfd = open ('/tmp/tmp.txt ') while True: line = Fd.readline () If not line: break print Line,fd.close[[email protected] day02]# python 16.py 123
With+while Cycle
[[email protected] day02]# cat 17.py #!/usr/bin/pythonwith Open ('/tmp/tmp.txt ') as FD: While True: line = Fd.read Line () if is line: break print Line,[[email protected] day02]# python 17.py123
Summarize
for循环有一定的次数while循环需要给出条件,条件语句后面要加:for和while遍历完文件之后需要加fd.close关闭文件,养成好习惯,如果不加python执行完系统也会进行回收with+while进行循环就不用加close的方法
Python Process Control