无法让我的代码停止

时间:2014-05-01 17:35:21

标签: python

所以我一直在运行这段代码,但它一直在继续。我不知道怎么让它停下来打印出“总分钟数”,“总步数”,“每分钟平均步数”。

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

3 个答案:

答案 0 :(得分:3)

min接受raw_input后,它是一个字符串,因此您需要将其转换为int。在Python中,0"0"是不同的东西,因此您需要通过调用str上的0来确保它们属于同一类型,或者在int上调用min

理想情况下,您需要将min"0"进行比较,而不是首先在静态数字上笨拙地调用str

答案 1 :(得分: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()函数。

答案 2 :(得分: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
>>>