简体   繁体   中英

how can I give a variable another value inside a function in python?

I'm creating a simple python script that checks for new comments on a WordPress blog using the xmlrpc API.

I'm stuck with a loop that should tell me if there are new comments or not. Here's the code:

def checkComm():
    old_commCount = 0;
    server = xmlrpclib.ServerProxy(server_uri); # connect to WP server
    comments = server.wp.getComments(blog_id, server_admin, admin_pass, filters);
    new_commCount = len(comments);
    if new_commCount > old_commCount:
        print "there are new comments"
        old_commCount = new_commCount
    else:
        print "no new comments"

while True:
    checkComm()
    time.sleep(60)

I've skipped the variables like blog_id, server_admin etc.. since they add nothing to this question.

Can you tell what is wrong with my code?

Thanks a lot in advance.

You want to pass it as a parameter, because you are resetting it every time you call the function:

def checkComm(old_commCount): # passed as a parameter
    server = xmlrpclib.ServerProxy(server_uri) # connect to WP server
    comments = server.wp.getComments(blog_id, server_admin, admin_pass, filters)
    new_commCount = len(comments)
    if new_commCount > old_commCount:
        print "there are new comments"
        old_commCount = new_commCount
        return old_commCount # return it so you can update it
    else:
        print "no new comments"
        return old_commCount

comm_count = 0 # initialize it here
while True:
    comm_count = checkComm(comm_count) # update it every time
    time.sleep(60)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM