使用if比较答案和调用函数

2024-06-26 17:02:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着比较两个答案,如果问题的答案是“e”,我需要它调用一个函数CheckID,这个函数连接到某个服务器上的数据库并提取一些信息。我可以连接到数据库,但问题是它不是在回答问题后调用函数,它显示我'e'没有定义!!我试图通过添加e=CheckID()来定义它,但它仍然没有调用函数。请帮助我实现这个目标,或者让我知道我做错了什么

这是我的密码:

import psycopg2
import psycopg2.extras

question = input("Type 'e' to Check Existing Id, or 'a' to add Account Id ?   ")

if question == 'e':
    CheckID()

else:
    AddID()


def CheckID():

    acc = input("Type ID ")  

    conn = psycopg2.connect(database="", user = "", password = "", host = "", port = "")
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute('select "AccountID","Zip" from "Account" where "AccountID" =  %s', (acc,))

    ans =cur.fetchall()
    ans1 = {}

    for AccountID in ans:

        if len(Zip) != 3:       
            Zip = '111'
            print(AccountID, Zip)


        else:
            print(AccountID, Zip)

def AddID():
    print "Thank you for using our script"

ask()

这是我得到的错误

enter code here Type 'e' to Check Existing Id, or 'a' to add Account Id ?   e
Traceback (most recent call last):
  File "final7.py", line 4, in <module>
    question = input("Type 'e' to Check Existing Id, or 'a' to add Account Id ?   ")
  File "<string>", line 1, in <module>
NameError: name 'e' is not defined

Tags: ortoaddidinputchecktypeaccount
2条回答

正如在注释中提到的,您正在用python2而不是python3运行脚本。在python2中,input()eval(raw_input(...))相同。你知道吗

像这样运行程序:python3 final7.py

您的问题在于您使用的是哪个Python版本。我在python3.6中运行,代码运行正常。在Python2.x中

input 

定义为

raw_input 

所以只需运行3.6中的代码或将“input”更新为“raw\u input”。你知道吗

相关问题 更多 >