0

对于 python 分配,我需要要求用户输入数字,直到他们输入负数。到目前为止,我有:

    print("Enter a negative number to end.")
    number = input("Enter a number: ")
    number = int(number)
    import math
    while number >= 0:
        numberagain = input("Enter a number: ")
        numberagain = int(numberagain)
        while numberagain < 0:
            break

如何将用户输入值的次数加起来

4

2 回答 2

3
i = 0
while True:
    i += 1
    n = input('Enter a number: ')
    if n[1:].isdigit() and  n[0] == '-':
        break
print(i)

str.isdigit()函数对于检查输入是否为数字非常有用。这可以防止在尝试转换时发生错误,比如'foo'转换为int.

于 2013-01-08T00:30:30.210 回答
2
import itertools

print('Enter a negative number to end.')
for i in itertools.count():
  text = input('Enter a number: ')
  try:
    n = int(text)
  except ValueError:
    continue
  if n < 0:
    print('Negative number {} entered after {} previous attempts'.format(n, i))
    break

上面的解决方案应该对奇怪的输入(例如尾随空格和非数字内容)具有鲁棒性。

这是一个快速演示:

wim@wim-desktop:~$ python /tmp/spam.py
Enter a negative number to end.
Enter a number: 1
Enter a number: 2
Enter a number: foo123
Enter a number: i am a potato
Enter a number: -7
Negative number -7 entered after 4 previous attempts
wim@wim-desktop:~$ 
于 2013-01-08T02:04:53.057 回答