如何克服这个问题:python中没有定义函数。

时间:2016-05-16 10:28:31

标签: python

美好的一天,我有以下片段:

#! /usr/bin/python
#! /usr/bin/python3

from sys import version_info
import logging

py3 = version_info[0] > 2 

if py3:
    name = input('What is your name?: ')
    verify_user(name)
else:
    name = raw_input('What is your name?: ')
    verify_user(name)


def verify_user(name):
    if name is not 'My Admin':
        logging.warning('What the hell are you doing in here ???')
    else:
        logging.info('Welcome Dear Admin')

当我在shell中执行:./ log.py时,我收到以下错误:

verify_user is not define. 

不确定发生了什么。我已经定义了verify_user()。 任何帮助都将非常感激。

2 个答案:

答案 0 :(得分:4)

您在定义之前调用verify_user。将verify_user功能移到文件顶部。

#! /usr/bin/python 
#! /usr/bin/python3

from sys import version_info
import logging

def verify_user(name):
    if name is not 'My Admin':
        logging.warning('What the hell are you doing in here ???')
    else:
        logging.info('Welcome Dear Admin')

py3 = version_info[0] > 2 

if py3:
    name = input('What is your name?: ')
    verify_user(name)
else:
    name = raw_input('What is your name?: ')
    verify_user(name)

答案 1 :(得分:1)

Python是dynamic language,因此您需要先定义函数然后再使用它。

解决方案:在使用之前输入整个函数定义。

#! /usr/bin/python
#! /usr/bin/python3

from sys import version_info
import logging

def verify_user(name):
    if name is not 'My Admin':
        logging.warning('What the hell are you doing in here ???')
    else:
        logging.info('Welcome Dear Admin')

py3 = version_info[0] > 2 

if py3:
    name = input('What is your name?: ')
    verify_user(name)
else:
    name = raw_input('What is your name?: ')
    verify_user(name)