1. 程式人生 > >Python-sys模塊,異常

Python-sys模塊,異常

sat for argument rip lin task module fin sys

習題1:題目:給一個不多於5位的正整數,要求:一、求它是幾位數,二、逆序打印出各位數字。

#encoding=utf-8

while True:

try:

num=int(raw_input("input a number not more than 5 digits:"))

except:

"Plese input again:"

else:

if len(str(num))<=5:

break

print len(str(num))

print str(num)[::-1]

習題2:題目:請輸入星期幾的第一個字母來判斷一下是星期幾,如果第一個字母一樣,則繼續判斷第二個字母。

#encoding=utf-8

week={‘m‘:‘monday‘,‘tu‘:‘tuesday‘,‘w‘:‘wednesday‘,‘th‘:‘thursday‘,‘f‘:‘friday‘,‘sa‘:‘saturday‘,‘s‘:‘sunday‘}

prefix=raw_input("input the first letter:")

if week.has_key(prefix.lower()):

print week[prefix.lower()]

else:

prefix2=raw_input("input the second letter:")

if week.has_key(prefix.lower()+prefix2.lower()):

print week[prefix.lower()+prefix2.lower()]

習題3:兩個 3 行 3 列的矩陣,實現其對應位置的數據相加,並返回一個新矩陣:

X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[5,8,1],
[6,7,3],
[4,5,9]]

#encoding=utf-8

x = [[12,7,3],

[4 ,5,6],

[7 ,8,9]]

y = [[5,8,1],

[6,7,3],

[4,5,9]]

z = [[0,0,0],

[0,0,0],

[0,0,0]]

#print x,y,z

for i in range(len(x)):

print "i:",i

for j in range(3):

print "j:",j

print "x[%s][%s]:%s"%(i,j,x[i][j])

print "y[%s][%s]:%s"%(i,j,y[i][j])

z[i][j]=x[i][j]+y[i][j]

print "z[%s][%s]:%s"%(i,j,z[i][j])

print z

c:\Python27\Scripts>python task_test.py

i: 0

j: 0

x[0][0]:12

y[0][0]:5

z[0][0]:17

j: 1

x[0][1]:7

y[0][1]:8

z[0][1]:15

j: 2

x[0][2]:3

y[0][2]:1

z[0][2]:4

i: 1

j: 0

x[1][0]:4

y[1][0]:6

z[1][0]:10

j: 1

x[1][1]:5

y[1][1]:7

z[1][1]:12

j: 2

x[1][2]:6

y[1][2]:3

z[1][2]:9

i: 2

j: 0

x[2][0]:7

y[2][0]:4

z[2][0]:11

j: 1

x[2][1]:8

y[2][1]:5

z[2][1]:13

j: 2

x[2][2]:9

y[2][2]:9

z[2][2]:18

[[17, 15, 4], [10, 12, 9], [11, 13, 18]]

一行搞定:

>>> [[x[i][j]+y[i][j] for i in range(3)] for j in range(3)]

[[17, 10, 11], [15, 12, 13], [4, 9, 18]]

Sys.argv練習把所有的輸入參數的字母個數統計出來

#encoding=utf-8

import sys

print "The command line arguments are:"

list=sys.argv

num=0

print list

for i in list[1:]:

if (i>=‘a‘ and i<=‘z‘) or (i>=‘A‘ and i<=‘Z‘):

num+=1

print num

c:\Python27\Scripts>python task_test.py A B c d

The command line arguments are:

[‘task_test.py‘, ‘A‘, ‘B‘, ‘c‘, ‘d‘]

4

第二道題:你輸入的參數全部是數字,計算所有數字參數的累計和

#encoding=utf-8

import sys

print "The command line arguments are:"

list=sys.argv

sum=0

print list

for i in list[1:]:

sum+=float(i)

print "sum:",sum

c:\Python27\Scripts>python task_test.py 1 1 1.1

The command line arguments are:

[‘task_test.py‘, ‘1‘, ‘1‘, ‘1.1‘]

sum: 3.1

按照吳老思路:

#encoding=utf-8

import sys

if len(sys.argv[1:])>=1:

sum=0

else:

sum = None

for i in sys.argv[1:]:

try:

sum+=float(i)

except:

continue#這裏的意思是出現非數字的地方不抱錯,

print sum

#encoding=utf-8

import sys

import os

def readfile(filename):

f=open(filename)

while True:

line=f.readline()

if len(line.strip())==0:

break

print line

f.close()

print "sys.argv[0]--------",sys.argv[0]

print "sys.argv[1]--------",sys.argv[1]

print "sys.argv[2]--------",sys.argv[2]

if len(sys.argv)<2:

print "No action specified."

sys.exit()

if sys.argv[1].startswith(‘--‘):

option = sys.argv[1][2:]

if option == ‘version‘:

print "version 1.2"

elif option ==‘help‘:

print """

This program.........

--version:prints the version number

--help : display this help"""

else:

print "unknow option"

sys.exit()

else:

for file in sys.argv[1:]:

#print file

readfile(file)

sys.stdin.readline() == raw_input()

>>> raw_input()

sd

‘sd‘

>>> sys.stdin.readline()

sadf

‘sadf\n‘

>>>

#coding=utf-8

import os

import sys

counter=1

while True:

line=sys.stdin.readline()

if not line.strip():

break

print "%s:%s"%(counter,line)

counter +=1

>>> import sys

>>> sys.version

‘2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AMD64)]‘

>>>

>>> sys.stdout.write("sdfsdffffffffff\n")

Sdfsdffffffffff

#coding=utf-8

import os

import sys

for i in range(3):

sys.stdout.write("gloryroad")

print ‘\n‘,‘_‘*60,‘\n‘

for i in range(3):

sys.stderr.write("error error")

將標準輸出到屏幕,改為輸出到文件裏

>>> import os

>>> import sys

>>> sys.stdout=open("d:\\a.txt","w")

>>> print "love you"

>>> "love you"

>>> fp

>>> print "hello"

>>> stdout.flush()

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name ‘stdout‘ is not defined

>>> print ""

>>> sys.stdout.flush()

>>> print

Python-sys模塊,異常