I have no experience with python, so I thought I'd start looking into it for my new hobby. I'm having an issue when it comes to a switch case, which python doesn't have, after googling I found most use a dictionary style method which you can see below. It's a small .py file I'm building to replicate an ATM style system, just to get me familiar with all of python's options.
while True:
print ("Who are you?")
name = input().lower()
if re.match("^[A-Za-z]*$", name):
break
else:
print('Please enter a valid name')
print('Hello ' + name)
print("Please enter your PIN " + name)
pin = input()
accounts = {"stephen" : stephen,
"Dean" : Dean,
"Jennifer" : Jennifer,
"Liam" : Liam,
"Billie" : Billie,
"Decky" : Decky,
"Joel" : Joel,
}
accounts[name]()
def stephen():
if pin == 1234:
print("Pin Accepted")
else:
print("Wrong PIN")
def Dean():
if pin == 1344:
print("Pin Accepted")
else:
print("Wrong PIN")
Now the problem is that when I get to the enter pin section, it comes back with an error saying the following:
options = {"stephen" : stephen, NameError: name 'stephen' is not defined
Any ideas what it could be? looking at the example it seems I have everything right, but I couldn't find an answer from googling the specific error.
At the point where you get the error because you try to use stephen, it's not defined yet. Create that dictionary after the function has been defined.
Python is an interpreted language, which means that the code is executed by the interpreter line by line without previously compiling. So the function stephen is not defined when you try to enter it into the dictionary because it's only defined later in the script. Define the function stephen prior to entering it into the dictionary and your script will work.
accounts = {"stephen" : stephen,
"Dean" : Dean,
"Jennifer" : Jennifer,
"Liam" : Liam,
"Billie" : Billie,
"Decky" : Decky,
"Joel" : Joel,
}
1) the values in your accounts dictionary cause the error. no matter variables or functions, you have to define them before use.
2) remove the last comma in your account dictionary
An easy sample is here:
>>> mydict ={"a":A} # A is not defined, will raise Error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'A' is not defined
>>> mydict ={"a":"A"} # A is string here, it is okay
>>> A = "A" # declares A and assigns value to it
>>> mydict ={"a":A} # good now.
Related
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?
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)
This is my code block
import json
import difflib
from difflib import get_close_matches
definitions = json.load(open("data.json"))
def thesaurus(words):
if words in definitions:
return definitions[words]
elif len(get_close_matches(words, definitions.keys())) > 0:
yn = input("Did you mean %s instead? Enter 'Y' if yes or 'N' if no: " % get_close_matches(words,definitions.keys()) [0])
if yn == "Y":
return thesaurus[get_close_matches(words, definitions.keys())]
elif yn == "N":
return "None found"
else:
return "Please check word again"
words = input("Look Up: ").lower()
print(thesaurus(words))
I expected to receive the meaning of the word "Grief". However, I kept receiving the error : function object is not subscriptable.
Here is the terminal log, just in case it might help:
My-MacBook-Pro:Python Adwok$ python3 dictionary.py
Look Up: GRERFAG
Did you mean grief instead? Enter 'Y' if yes or 'N' if no: Y
Traceback (most recent call last):
File "dictionary.py", line 22, in <module>
print(thesaurus(words))
File "dictionary.py", line 13, in thesaurus
return thesaurus[get_close_matches(words, definitions.keys())]
TypeError: 'function' object is not subscriptable
Please point out even the smallest details, I would appreciate that very much.
As stated by the error stack, in line 13 you are accessing thesaurus as if it was a list/dictionary (or any subscriptable object). Since thesaurus is a function (which is not subscriptable), you get an error. Thus, you need to invoke the function (instead of accessing it):
thesaurus(get_close_matches(words, definitions.keys()))
Also, you should notice:
At the end of your code you are correctly invoking the thesaurus function by calling print(thesaurus(words))
Consider reusing the result of get_close_matches to avoid multiple calls to the same function (which can lead to performance degradation if the call is resource consuming).
I suggest you the following solution:
import json
import difflib
from difflib import get_close_matches
definitions = json.load(open("data.json"))
def thesaurus(words):
if words in definitions:
return definitions[words]
else:
close_matches = get_close_matches(words, definitions.keys())
if len(close_matches) > 0:
yn = input("Did you mean %s instead? Enter 'Y' if yes or 'N' if no: " % get_close_matches(words,definitions.keys()) [0])
if yn == "Y":
return thesaurus(close_matches)
elif yn == "N":
return "None found"
else:
return "Please check word again"
words = input("Look Up: ").lower()
print(thesaurus(words))
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!