为什么该Python代码会引发错误?

时间:2019-01-22 18:50:39

标签: python windows-10

当我输入例如NICK和HASLO时,出现以下错误:

Traceback (most recent call last):
File "G:/Wszystko/WONSZ/test.py", line 21, in <module>
    nick = nick()
TypeError: 'str' object is not callable

当我输入nick和haslo时,它可以工作,但不能 那我该怎么做才能解决呢? 这是代码:

x = int
y = int

def nick():
    print ("Podaj swoj nick: ",end=' ')
    nick = input()
    return nick

def haslo():
    print ("Podaj swoje haslo: ",end=' ')
    haslo = input()
    return haslo

print ("Witaj!!!")

while True:
    x = 0
    y = 0
    nick = nick()
    haslo = haslo()

    if nick == "nick":
        x += 1

    if haslo == "haslo":
        y += 1

    if x==0:
        print("Nick bledny")
        if y == 0:
            print("Haslo bledne")
    if x==1 and y==1:
         break

print("Zalogowano")

该如何解决?

1 个答案:

答案 0 :(得分:3)

重复变量和函数名称可能很危险。就您而言,代码混乱不堪,Python无法正确判断您是指变量还是函数。

在这里,我更改了变量的名称。不仅有效,而且更易于阅读:

x = int
y = int

def nick():
    print ("Podaj swoj nick: ",end=' ')
    nickInput = input()
    return nickInput

def haslo():
    print ("Podaj swoje haslo: ",end=' ')
    hasloInput = input()
    return hasloInput

print ("Witaj!!!")

while True:
    x = 0
    y = 0
    nickVar = nick()
    hasloVar = haslo()

    if nickVar == "nick":
        x += 1

    if hasloVar == "haslo":
        y += 1

    if x==0:
        print("Nick bledny")
        if y == 0:
            print("Haslo bledne")
    if x==1 and y==1:
         break

print("Zalogowano")