IF语句不起作用

2024-03-29 12:24:37 发布

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

我是Python新手,非常习惯C风格的编程,Python中的if语句出现了错误。我试图在while循环中增加一个变量;在打印之前首先使用“if”语句检查它,但由于某种原因它不起作用。下面的代码,我看到类似的错误,但无法应用我从那里得到的

import socket
import time
import threading

tLock = threading.Lock()
shutdown = False
kt = 0

def receving(name, sock):
    while not shutdown:
        try:
            tLock.acquire()
            while True:
                data, addr = sock.recvfrom(1024)
                if kt > 0:
                    print str(kt)
                kt = kt+1

    except:
        pass
    finally:
        tLock.release()

host = '127.0.0.1'
port = 0

server = ('127.0.0.1',5000)

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
s.setblocking(0)

rT = threading.Thread(target=receving, args=("RecvThread",s))
rT.start()

alias = raw_input("Please Enter Your Name: ")
message = raw_input(alias + " Please Enter Your Password:")
while message != 'q':
    if message != '':
        s.sendto(alias + ":" + message, server)
    tLock.acquire()
    message = raw_input(alias + "-> ")
    tLock.release()
    time.sleep(0.2)

shudown = True
rT.join()
s.close()

这是服务器 导入套接字 导入时间 导入线程

host = '127.0.0.1'
port = 5000

clients = []

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host,port))
s.setblocking(0)

checkpass = False
quitting = False
print "Server Started."

while not quitting:
    try:
        data, addr = s.recvfrom(1024)
        if checkpass == False:       
            userNa,passWo = data.split(":")
        daata =[line.strip() for line in open("passFile.txt",'r')]
        for index,item in enumerate(daata):              
            if userNa == daata[index] and passWo ==daata[index+1]:
                checkpass = True
                print "Welcome " + userNa +" You have successfully logged in!"                       
                   break;   
            else:
                print "Your username and/or password was incorrect try again"


    else:
        print "well we tried"

        if "Quit" in str(data):
            quitting = True
        if addr not in clients:
            clients.append(addr)

        print time.ctime(time.time()) + str(addr) + ": :" + str(data)
        for client in clients:
            s.sendto(data, client)
    except:
        pass
s.close()

Tags: infalsetruehostmessagedataiftime
1条回答
网友
1楼 · 发布于 2024-03-29 12:24:37

你的代码不应该运行。在函数receving中,您应该得到一个UnboundLocalError异常:

In [5]: kt = 0

In [6]: def test(s):
    print('{} test'.format(s))
    print('value of kt:', kt)
    kt = kt + 1
   ...:     

In [7]: test('first')
first test
                                     -
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-7-0e641494ca48> in <module>()
  > 1 test('first')

<ipython-input-6-c37035372993> in test(s)
      1 def test(s):
      2     print('{} test'.format(s))
  > 3     print('value of kt:', kt)
      4     kt = kt + 1
      5 

UnboundLocalError: local variable 'kt' referenced before assignment

应该在函数中使用global语句。你知道吗

In [8]: def test2(s):
   ...:     global kt
   ...:     print('{} test'.format(s))
   ...:     print('value of kt:', kt)
   ...:     kt = kt + 1
   ...:     

In [9]: test2('first')
first test
value of kt: 0

In [10]: test2('second')
second test
value of kt: 1

相关问题 更多 >