Python - Num1 1未定义

时间:2017-07-03 22:04:46

标签: python

def to_numbers():
  num1 = str(raw_input('Enter a string number?\n'))

for value in num1:
  try:
    print '%s as an int is %d' % (str(value), int(value))
  except ValueError, ex:
    print '"%s" cannot be converted to an int: %s' % (value, ex)

想知道我是否可以正确编码。收到num1 not defined错误。

3 个答案:

答案 0 :(得分:2)

您需要在函数 namespace backend/controllers; 中返回num1(否则,您无法使用此值超出to_numbers)。然后,您需要致电to_numbers以定义to_numbers,如下所示:

num1

答案 1 :(得分:1)

Python在缩进时非常敏感,因此请确保正确缩进代码以获得预期的结果。您将num1作为未定义的错误,因为num1范围在方法to_numbers()中,而for循环不在to_numbers()范围内,因此错误。

删除num1赋值和for循环之间的行并缩进循环以使其同步(空格),就像num1一样,可以在to_numbers()中访问num1。

当我使用Python 3.x时,我必须更新一些语法,比如在打印语句中添加括号,并使用as关键字来命名异常实例,但逻辑仍然相同。

import platform

## Your method
def to_numbers():
  num1 = str(input('Enter a string number?\n'))
  for value in num1:
    try:
      print ('%s as an int is %d' % (str(value), int(value)))
    except ValueError as ex :
      print ('"%s" cannot be converted to an int: %s' % (value, ex))

## Print Python version for your reference
print("Python version : " + platform.python_version())
## Calling your method
to_numbers()

示例运行

Python version : 3.6.1
Enter a string number?
1234567890abcdefgh
1 as an int is 1
2 as an int is 2
3 as an int is 3
4 as an int is 4
5 as an int is 5
6 as an int is 6
7 as an int is 7
8 as an int is 8
9 as an int is 9
0 as an int is 0
"a" cannot be converted to an int: invalid literal for int() with base 10: 'a'
"b" cannot be converted to an int: invalid literal for int() with base 10: 'b'
"c" cannot be converted to an int: invalid literal for int() with base 10: 'c'
"d" cannot be converted to an int: invalid literal for int() with base 10: 'd'
"e" cannot be converted to an int: invalid literal for int() with base 10: 'e'
"f" cannot be converted to an int: invalid literal for int() with base 10: 'f'
"g" cannot be converted to an int: invalid literal for int() with base 10: 'g'
"h" cannot be converted to an int: invalid literal for int() with base 10: 'h'

答案 2 :(得分:0)

您必须插入标签,以便for在函数内部。否则,您只有一个函数可以读取值和def to_numbers(): num1 = str(raw_input('Enter a string number?\n')) return num1 num1=to_numbers() for value in num1: try: print '%s as an int is %d' % (str(value), int(value)) except ValueError, ex: print '"%s" cannot be converted to an int: %s' % (value, ex) 之外的值,但无法访问for