I am learning coding in Python. I am facing an issue today. My code is showing output correctly but it is showing a warning. I don't know where is the fault. Please help me to solve it.
Code:
class Info:
Name = ""
Roll = ""
Section = ""
Department = ""
Session = ""
University = ""
def display(a, b, c, d, e, f):
print(f"Name: {a}")
print(f"ID: {b}")
print(f"Section: {c}")
print(f"Department: {d}")
print(f"Session: {e}")
print(f"University: {f}")
Code = input("Enter Code: ")
Code = Info() # Error in this line
Code.Name = input("Enter Name: ")
Code.Roll = input("Enter ID: ")
Code.Section = input("Enter Section Name: ")
Code.Department = input("Enter Department Name: ")
Code.Session = input("Enter Session: ")
Code.University = input("Enter University Name: ")
display(Code.Name, Code.Roll, Code.Section, Code.Department, Code.Session, Code.University)
Error is showing in this line Code = Info()
Error message:
How can I solve this problem?
The warning message from your IDE's linter tells you:
Redeclared "Code" defined above without usage.
Code is defined by your input() function call. But then you define Code again immediately by calling Info(), without ever using the result of calling input().
Because you are reassigning the same variable (Code) on 2 consecutive lines.
You Can remove first line
Code = input....
The warning message is showing up because you define a variable called Code in which you store the input on this line:
Code = input("Enter Code: ")
but then you never actually use it, since you redefine it in the next line:
Code = Info()
As you noticed this may not cause any errors, but many modern code editors warn you about unused variables. In your case you should ask yourself what is the purpose of the user input and why aren't you using it anywhere?
Related
Im making an AI/Chat Bot from scratch and I want to make code where the bot uses dictionaries of its known stuff and uses them to talk to the user. However, when I try to make the answer appear on the screen using a variable, an error appears
Ive tried making the code so that when the user writes down something in the greetings dictionary, the bot will say "Hello!". But when i run the code, this error comes up: 'set' object is not callable' on line 7 of the code.
MY_NAME = input("What is my name? \n")
Greeting = {"Hi", "Hello", "Hey"}
while True:
input = input("Talk to " + MY_NAME + "\n")
if input == Greeting():
print ("Hello!")
I want the fixed code to this. Thankyou!
Problems:
Greeting is a set. You use it like calling a function which results in your error.
Change variable input because it conflicts with the original input function. In the next iteration, it will throw error as "str object is not callable".
You need a membership check:
while True:
inp = input("Talk to " + MY_NAME + "\n")
if inp in Greeting:
print ("Hello!")
Try using in, and rename input to inp since input will override the default input keyword:
MY_NAME = input("What is my name? \n")
Greeting = {"Hi", "Hello", "Hey"}
while True:
inp = input("Talk to " + MY_NAME + "\n")
if inp in Greeting:
print ("Hello!")
This question already has answers here:
Why does code like `str = str(...)` cause a TypeError, but only the second time?
(20 answers)
Closed 21 days ago.
I have the following code, which is supposed to ask the user 2 file names. I get an error with the input() in the second function but not in the first, I don't understand...
Here is the error :
output = getOutputFile()
File "splitRAW.py", line 22, in getOutputFile
fileName = input("\t=> ")
TypeError: 'str' object is not callable
# Loops until an existing file has been found
def getInputFile():
print("Which file do you want to split ?")
fileName = input("\t=> ")
while 1:
try:
file = open(fileName, "r")
print("Existing file, let's continue !")
return(fileName)
except IOError:
print("No such existing file...")
print("Which file do you want to split ?")
fileName = input("\t=> ")
# Gets an output file from user
def getOutputFile():
print("What name for the output file ?")
fileName = input("\t=> ")
And here is my main() :
if __name__ == "__main__":
input = getInputFile()
output = getOutputFile()
The problem is when you say input = getInputFile().
More specifically:
The program enters the getInputFile() function, and input hasn't been assigned yet. That means the Python interpreter will use the built-in input, as you intended.
You return filename and get out of getInputFile(). The interpreter now overwrites the name input to be that string.
getOutputFile() now tries to use input, but it's been replaced with your file name string. You can't call a string, so the interpreter tells you that and throws an error.
Try replacing input = getInputFile() with some other variable, like fileIn = getInputFile().
Also, your getOutputFile() is not returning anything, so your output variable will just have None in it.
Next time just "RESTART YOUR KERNEL" TypeError: 'str' object is not callable - restart kernel and its gone. You're good to go.
You may be overriding the input name with something else.
If you need to reinitialize the input function in a notebook:
from builtin import input
Depending on what version of python you're using:
Python 2:
var = raw_input("Please enter something: ")
print "you entered", var
Or for Python 3:
var = input("Please enter something: ")
print("You entered: " + var)
I am new to programming. I am currently taking python in school right now and I ran into a error and I figure it out. I keep getting a syntax error and I am not sure if it is typo on the instructor or myself.
def main():
num_emps=int(input("How many employee records? "))
empfile=open("employee.txt","w")
for count in range(1,num_emps+1):
print("Enter data for employee#",count,sep='')
name=input("Name: ")
id_num=input("ID Number: ")
dept=input("Department: ")
empfile=write.(name+"\n")
empfile=write.(id_num+"\n")
empfile=write.(dept+"\n")
print()
empfile.close
print("Employee records written to disk")
main()
I keep getting the error at
empfile=write.(name+"\n")
or is it supposed to be
empfile.write(name+"\n")
Thanks for the help
Use empfile.write() instead of empfile=write.()
Corrected and optimized version:
def main():
# indentation was missing in your question:
num_emps = int(input("How many employee records? "))
empfile = open("employee.txt","w")
for count in range(num_emps): # range from 0 to num_emps-1
print("Enter data for employee #{}:".format(count)) # use str.format(...)
name = input("Name: ")
id_num = input("ID Number: ")
dept = input("Department: ")
empfile.write(name + "\n")
empfile.write(id_num + "\n")
empfile.write(dept + "\n")
# alternative using Python 3's print function:
# print(name, file=empfile) # line-break already included
print()
empfile.close() # to call the function, you need brackets () !
print("Employee records written to disk")
main()
Also, there's not really a need to write a main() function in your example. You could have put the code directly into the file.
And if you want a proper main() function, use this construct to call it:
if __name__ == "__main__":
main()
else:
print("You tried to import this module, but it should have been run directly!")
It is used to determine whether a script was invoked directly or imported by another script.
I have two lists in separate text files, "messages" and "codes". My program will open them and read them. My program is a code redeemer that will take a code and redeem it for a message.
lstCodes = open("codes.txt").readlines()
lstMessages = open("messages.txt").readlines()
I take in a user input as the code with the following class.
class DateCheck:
def __init__(self, date1):
self.date1 = date1
if date1 == datetime.date(xxxx,x,xx):
print('Correct! \n')
checkx = input('Are you ready to type in your final secret code? YES = 1, NO = 0: \n')
dcodex = input("Enter Code: \n")
#progressB=progress(50,.04)
LoopCheck(checkx, dcodex)
else:
print('Wrong code')
Once it asks for the user to input the code it passes it to another class that will look for that code in the text file and if found return the message from messages.txt.
class LoopCheck:
def __init__(self, check, code):
self.check = check
self.code = code
if code in lstCodes:
print(lstMessages[lstCodes.index(code)])
else:
print("Wrong Code")
And heres the issue, it will only work with the first code in code.txt and the first message in message.txt. When I input the correct code2 it returns "Wrong". I've tried looking at how I'm reading the lists but I can't figure out what I'm doing wrong. I'm sure it's a small mistake but I haven't been able to figure it out.
#messages.txt
message1
message2
#codes.txt
xxxx
xxxx
Best would be to use a dictionary:
codes = {}
with open("codes.txt") as cod_fobj, open("messages.txt") as mess_fobj:
for code, mess in zip(cod_fobj, mess_fobj):
codes[code.strip()] = mess.strip()
Now:
>>>> codes['code1']
'message1'
The check could look like this:
if code in codes:
print(codes[code])
else:
print("Wrong Code")
Or:
try:
print(codes[code])
except KeyError:
print("Wrong Code")
I think I figured out what was wrong. I changed the formatting on codes.txt to:
#codes.txt
xxxx, xxxx, xxxx
I also changed lstCodes = open("codes.txt").readlines() to lstCodes = open("codes.txt").read().split(',')so now when I look for the code in code.txt it returns its index and then I look up the index number on messages.txt and return the message associated with it.
I have problem with users input control in one function in Python 3.4.
def input_name (*args):
name_output = ""
name_input = input ("Give first name: ")
if name_input.isalpha() and name_input[0].isupper() == True:
name_output += name_input
return (name_output)
else:
print ("Wrong, do it again")
input_name ()
name = input_name()
print(name.lower())
I am trying to catch users wrong input - so the name must be alphabetical and first letter must be uppercase. In future code I will create users login name with lowercase letters, so I am trying to print users name with small leters for login name. And there is problem.
When I type name firs time well, it's ok
When I type first time name with 1 lowercase letter (name) and then I write it correctly (Name), it tells me Error, I don't understand why. Can you tell me, what is my mistake?
Thank you very much for showing the path.
Mirek
The error is caused by the last line. Since your input is wrong the first time, the function returns None, so name.lower() raises an exception. I wouldn't use recursion in this case.
def input_name():
while True:
name_input = input ("Give first name: ")
if name_input.isalpha() and name_input[0].isupper():
return name_input
else:
print ("Wrong, do it again")
name = input_name()
print(name.lower())
Hope it helps!