2014-05-01 36 views
0

所以我一直在運行此代碼一段時間,但它只是繼續前進。我不知道如何讓它停止並打印出「總分鐘數」,「總步數」,以及「每分鐘平均步數」。無法讓我的代碼停止

minTot = 0 
stepTot = 0 
t = int(raw_input("Input the number of minutes (0 to exit): ")) 
if min == 0: 
    print "No minutes input." 
else: 
    while min != 0: 
     minTot = minTot + t 
     stepRate = int(raw_input("Input the step rate: ")) 
     stepTot = stepTot + stepRate * t 
     min = raw_input("Input the next number of minutes (0 to exit): ") 
    print "Total number of minutes:", t 
    print "Total number of steps:", stepTot 
    # Average is rounded down. 
    print " Average step rate per minute : ", minTot/stepTot 
+0

嘿,你的第一個輸入設置爲** t **不是min ...這是什麼語言? – user3003304

回答

3

一旦你接受了minraw_input,這是一個字符串,所以你需要將其轉換爲int。在Python中,0"0"是不同的東西,所以您需要確保它們都是相同的類型,或者撥打0上的str,或者撥打 min

理想情況下,您會比較min"0",而不是在首位靜態地調用str

2
while min != 0: 
    min = raw_input("Input the next number of minutes (0 to exit): ") 

raw_input返回一個字符串,它是從未等於整數0。敷在int()

min = int(raw_input("Input the next number of minutes (0 to exit): ")) 

此外,最好避免命名對象一樣內置的功能,如min。考慮將其更改爲minutes。否則,你會影響min()函數,如果你需要它。

0

raw_input()函數將輸入作爲python中的字符串。有多種方式來解決這個問題:

轉換爲整數:

>>> minutes = raw_input('Enter minutes: ') 
Enter minutes: 0 
>>> minutes 
"0" 
>>> if minutes.isdigit() == True: 
...  minutes = int(minutes) 
... 
>>> minutes 
0 
>>> 

這段代碼需要輸入一個字符串,並且如果號碼是一個數字(使用str.isdigit() ),然後我們使用int()轉換爲整數。

**輸入就拿int(raw_input())

>>> minutes = int(raw_input('Enter minutes: ')) 
Enter minutes: 87 
>>> minutes #Notice that the following is not surrounded by quotations 
87 
>>> 

int(raw_input())發生在僅整數作爲輸入。如果你在一個字符串類型它將提出一個ValueError:...

使用input()

>>> minutes = input('Enter minutes: ') 
Enter minutes: 
>>> minutes 
0 
>>> type(minutes) 
<type 'int'> 
>>> 

input()只需要在定義的變量,或者項目,你可以在你的shell調用,它不會引發錯誤:

>>> 'hello' #This works, so it should work in input() too 
'hello' 
>>> input('Enter a valid input: ') 
Enter a valid input: 'hello' 
'hello' 
>>> hello #This doesn't work, so it shouldn't work in input() either 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
NameError: name 'hello' is not defined 
>>> input('Enter a valid input: ') 
Enter a valid input: hello 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
NameError: name 'hello' is not defined 
>>>