2012-02-29 92 views
0

我得到這個錯誤:uTypeError:不支持的操作數類型(S) - : '海峽' 和 '海峽'

uTypeError: unsupported operand type(s) for -: 'str' and 'str'

從這個代碼:

print "what is your name?" 
x=raw_input() 
print "Are you woman or man?" 
y=raw_input() 
print "how old are you?" 
z=raw_input() 
print "at what age did you or will you first travel in an plane?" 
f=raw_input() 

print "This is a story about a ",y," named ",x 
print z-f ,"years ago",x, " first took an airplane." 
print " the end" 

爲什麼?

+1

回滾使問題與答案匹配; @ user1240834,如果你有一個新問題,而不是編輯這個問題,請打開一個新問題。 – DSM 2012-02-29 19:10:45

回答

3

您的變量zf是字符串。 Python不支持從另一個字符串中減去一個字符串。

如果你想顯示一個數字,你將不得不將它們轉換爲任何浮動或整數:

print int(z) - int(f),"years ago",x, " first took an airplane." 

原因這些都是擺在首位的字符串是因爲raw_inputalways returns a string

2

raw_input()返回一個字符串,所以基本上你結束了這一點:

print '20'-'11' 

因爲你不能減去另一個字符串,您需要首先轉換爲數字。

試試這個:

z = float(raw_input()) 
... 
f = float(raw_input()) 

其次,使用描述性的變量名,而不是X,Y,Z和F,所以像:

age = float(raw_input()) 
... 
firstPlaneTravelAge = float(raw_input()) 

print age-firstPlaneTravelAge, ... 

另外請注意,此代碼有沒有驗證,如果用戶輸入的不是數字,它會崩潰。

+0

thanK你這麼多,幫助很多:) – user1240834 2012-02-29 17:39:09

相關問題