输入字符串而不是int时的NameError

时间:2018-06-05 01:39:55

标签: python python-2.7 input nameerror

我正在尝试构建一个简单的程序,在用户输入的数字上运行Collatz Sequence。我也正在使用它来尝试使用'尝试除了' Python中的语句,只要用户输入字符串而不是整数,就抛出一个print语句。

当输入整数时,程序按预期工作,例如在这里输入数字12,我得到以下输出:

$ python collatzSequence.py 
Enter in a number: 
12
6
3
10
5
16
8
4
2
1

但是,当您输入字符串时,我收到此错误:

python collatzSequence.py 
Enter in a number: 
ddd
Traceback (most recent call last):
  File "collatzSequence.py", line 34, in <module>
    main()
  File "collatzSequence.py", line 25, in main
    numb = input()
  File "<string>", line 1, in <module>
NameError: name 'ddd' is not defined

当我想要做的是当用户输入不是整数的东西并且打印时,我想要抓住&#39;请输入一个整数。&#39;

以下是我编写的代码,我已经放置了&#39;尝试除了&#39;在collat​​z()函数中的语句,我也尝试将它放在main()函数中,但我得到了相同的结果。 :

# Exploring the 'Collatz Sequence'.

# If number is even, print number // 2 and returns this value.
# If number is odd, print and return 3 * number + 1.
def collatz( number ) :
  # Error handling to make sure number entered is an int.
  try:
    number = int(number)
  except NameError :
    print( 'Please enter an integer.')
    return

  # number is even.
  if number % 2 == 0 :
    print( str(number // 2) )
    return number // 2
  # number is odd.
  else :
    print( str(3 * number + 1) )
    return 3 * number + 1

# Lets user type in an integer and keeps calling collatz() on that number until the funciton returns the value 1.
def main() :
  print( "Enter in a number: " )
  numb = input()

  numb = collatz(numb)
  while numb != 1 :
    numb = collatz(numb)



  if __name__ == "__main__":
    main()

感谢任何帮助,任何人都可以帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

感谢DyZ解决这个问题。 问题是,除了&#39;在错误的地方发表声明。我需要有&#39; numb = input()&#39; main()函数中try语句中的行,因为它是引发NameError的行。 我还添加了一个while语句,因此如果用户继续输入字符串,它将继续请求整数。输入int后,此循环中断。 以下是固定代码:

# Exploring the 'Collatz Sequence'.

# If number is even, print number // 2 and returns this value.
# If number is odd, print and return 3 * number + 1.
def collatz( number ) :
  number = int(number)

  # number is even.
  if number % 2 == 0 :
    print( str(number // 2) )
    return number // 2
  # number is odd.
  else :
    print( str(3 * number + 1) )
    return 3 * number + 1

# Lets user type in an integer and keeps calling collatz() on that number until the funciton returns the value 1.
def main() :
  print( "Enter in a number: " )

  # Error handling to make sure number entered is an int.
  while True :
    try:
      numb = input()
      break
    except NameError :
      print( 'Please enter an integer.' )

  numb = collatz(numb)
  while numb != 1 :
    numb = collatz(numb)

if __name__ == "__main__":
  main()

给出结果:

$ python collatzSequence.py 
Enter in a number: 
ddd
Please enter an integer.
22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1

再次感谢DyZ!