2011-04-23 71 views
6

不幸的是,raw_input沒有按照我的需要去做。我想要做的是得到totPrimes =無論我在提示中輸入什麼。如果我將while count < totPrimes替換爲while count < 50此腳本有效。如果我在提示符中鍵入50,這個腳本不起作用,我害怕raw_input不是我想要使用的函數嗎?這裏是我的代碼片段:Python:raw_input讀取數字時出現問題

testNum = 3 
div = 2 
count = 1 
totPrimes = raw_input("Please enter the primes: ") 

while count < totPrimes : 
    while div <= testNum : 
+0

考慮將標題更改爲更充分的標題。 p.e.'problem with raw_input reading a number',或類似的問題。 – joaquin 2011-04-23 07:52:27

+0

僅供參考,這是Python 2.x中的一個問題,因爲您可以比較不同類型的對象。在Python 3.x中它會引發一個'TypeError:unorderable types'。 – katrielalex 2011-04-23 08:57:03

回答

11

totPrimes = int(totPrimes) 
while count < totPrimes: 
    # code 

raw_input給你,你必須轉換爲整數或浮點數作出任何數值比較之前的字符串。

+0

儘管在循環之前進行轉換並將其保存爲局部變量會更好。否則,您會在進行比較時每次在循環中不必要地調用「int」。 – ncoghlan 2011-04-23 12:24:35

+0

@ncoghlan你是對的。我用這種方式寫下來,以便將問題集中在一行中。我將它更新爲您引用的更高效的版本。 – joaquin 2011-04-23 20:31:25

0

你需要轉換totPrimes成一個int這樣的:

integer = int(totPrimes) 
0

你只需要你的原始輸入轉換成一個整數。對於您的代碼,只需將您的代碼更改爲:

testNum = 3 
div = 2 
count = 1 
totPrimes = raw_input("Please enter the primes: ") 
totPrimes=int(totPrimes) 
while count < totPrimes : 
    while div <= testNum : 
0

然後使用輸入。

原始輸入返回字符串。

輸入返回int。

0

的的raw_input函數總是返回raw_input docs一個「字符串」類型,所以我們必須在這種情況下totPrimes「串」類型轉換爲「廉政」或「浮動」型是這樣的:

totPrimes = raw_input("Please enter the primes: ") 
totPrimes = float(totPrimes) 

你可以這樣將它們組合起來:

totPrimes = float(raw_input("Please enter the primes: ")) 

爲了在python count < totPrimes比較的東西,比較需要有意義(數字到數字,字符串爲字符串)或程序將崩潰,while count < totPrimes :得到控制而e循環將不會運行。

您可以使用try/except來保護您的程序。 managing exceptions

對於參加「爲所有人編程」課程的人,您可以花幾小時時間並按此方式評分。您應該嘗試弄清楚if/else語句。

0

您必須將每個數字更改爲「hrs」或「rate」。

例如:40*10.50+(h-40)*10.50*1.5是錯的,40*r+(h-40)*r*1.5是正確的。

相關問題