I am trying to create a simple menu by utilizing a dictionary instead of a series of if, elif statements. My problem is the functions being called when I declare them as the definition within the dictionary. Also I'm running into an error when trying to call on the dictionary.
I know that I'm missing something with the declaration. It doesn't matter what I put in the definition, if it's executable code then it executes when declared instead of when I call on it.
As far as the problem with calling on the dictionary I'm totally lost, from everything I've read I believe I'm doing it correctly. I've included an overly simplified version of what I'm trying to do that replicates the problems I'm having.
def hello():
print("Hello")
def goodbye():
print("Goodbye")
options = { '1' : hello(),
'2' : goodbye()}
chosen = '1'
options[chosen]()
This is what I get when the above is executed.
Hello
Goodbye
Traceback (most recent call last):
File "main.py", line 12, in <module>
options[chosen]()
TypeError: 'NoneType' object is not callable
And I should just see this.
Hello
Simply remove the parentheses from the functions in the dictionary. Leaving them there causes the functions to be called when the dictionary is declared.
Furthermore you get an error because the values you put into the dictionary are the return values of the functions, i.e., None, and calling None() gets you nowhere ;-)
Just assign the function name as the values in the dictionary
def hello():
print("Hello")
def goodbye():
print("Goodbye")
options = {'1': hello,
'2': goodbye}
chosen = '1'
options[chosen]()
Related
so i'm trying to learn about classes in python but for some reason i can't get Wiek function working.
i get the error:
Traceback (most recent call last):
File "D:/pythonProject/MEDIUM.py", line 36, in <module>
fafik.Wiek()
TypeError: 'int' object is not callable
class Pies(Ssaki):
def __init__(self, LiczbaKonczynPsa, ImiePsa, WiekPsa):
self.LiczbaKonczyn = LiczbaKonczynPsa
self.Wiek = WiekPsa
self.Imie = ImiePsa
def Przedstaw(self):
print('Ten pies wabi się: ', self.Imie)
def Konczyny(self):
print('Ten pies posiada ', self.LiczbaKonczyn, 'kończyny')
def Wiek(self):
print('Wiek psa wynosi 6')
fafik = Pies(4, 'BOBO', WiekPsa=3)
fafik.Przedstaw()
fafik.Konczyny()
fafik.Wiek()
I'm sorry for asking maybe so stupid question but i truly can't fin solution to my problem.
You're getting the error because you have both a class attribute named Wiek, which in your example is the int 3, and a method called Wiek(), which you try to call on the last line of your example. Since self.Wiek has already been defined as 3, calling fafik.Wiek() is the equivalent of calling fafik.3(), which is invalid.
def Wiek(self):
print('Wiek psa wynosi 6')
self.Wiek = WiekPsa
You have a parameter called Wiek, but also a method called Wiek
When you call fafik.Wiek() python tries to call your parameter Wiek which is an int, and tries to call it as a function which is not possible since it's a int
In any case, don't give a parameter and a function the same name; except for very precise case (getters)
Just rename either the variable Wiek, or the function to a new name and it will work
The problem you have here is that your class has two items having the same name.
An attribute, of type 'int'.
A method.
When you call your function here fafik.Wiek()it understands that you're trying to call the integer attribute as a method.
Just change the name of your function.
I got NameError for calling test_gobject, but the funny thing is I never called this function name. I called test_gobjectpy()
Can you explain it to me why Python decide to call the wrong function name (see error output)
Maybe it has some problems because I have a string with the same name as function?!
file name test_dyn_fun.py
second_path = ['test_gobject.py', 'st1.py', 'test_show_desktop.py', 'download_img.py', 'test_dump.py']
print("second_path", second_path)
print()
for i in second_path:
#func = create_dyn_func(i)
tmp = i.replace(".", "") #rm dot for function name
print("tmp =", tmp)
exec(f"def {tmp}(): print({i})")
print()
print(dir(test_gobjectpy))
print()
print(locals())
test_gobjectpy()
Error output:
Traceback (most recent call last):
File "/home/manta/Coding/test_dyn_fun.py", line 13, in <module>
test_gobjectpy()
File "<string>", line 1, in test_gobjectpy
NameError: name 'test_gobject' is not defined
In your loop you create functions, the first one created is effectively created like this:
i = 'test_gobject.py'
tmp = 'test_gobjectpy'
exec(f"def {tmp}(): print({i})")
So, it's as if you ran:
exec("def test_gobjectpy(): print(test_gobject.py)")
For Python to print test_gobject.py, it tries to access an object called test_gobject and its attribute .py.
That's what is causing the error. The fact that test_gobject.py looks like a filename to you doesn't matter, it's just names of variables to Python, the way you wrote it.
What would you expect to happen if you called this function?
def test_gobjectpy():
print(test_gobject.py)
More in general, as a beginning programmer, it's generally best to stay away from stuff like exec() and eval(). It's very common for new Python programmers to think they need this, or that it somehow solves a problem they have, but it's generally the worst solution to the problem and rarely actually a good solution at all. (not never, just rarely)
Whenever I run the code, python comes up with the error message:
Traceback (most recent call last):
File ""/Users/jim/Desktop/Python/TextWindow.py", line 7, in module
Read(name)
NameError: name 'name' is not defined
def Writeline(string):
print(string)
def Read(name):
name = input()
Read(name)
Writeline(name)
I am assuming that you want Read to read in a string that you will then pass to Writeline. In that case, Read has to return a value. Python strings are immutable, so you have to return the string you read to access it outside the function:
def Writeline(string):
print(string)
def Read():
return input()
name = Read()
Writeline(name)
Edit
Keep in mind that input() does different things in Pythons 2 and 3. In Python 3, it does what you appear to want. In Python 2 raw_input() is the function that reads in input. input() will attempt to evaluate anything you type as a line of Python code.
First, go through the link that #Erica provided as a comment.
There's a few things going wrong here.
You haven't actually defined the variable "name" on a scope that is able to be used.
You are passing in name to function Read(), when you probably don't want to pass in any variable to begin with.
I think you want raw_input(), not input() (This only applies to python 2.x, as I did not see the 3.x tag)
What you need to do is assign the variable "name" to be the return of the Read() function.
Such as the following:
def WriteLine(s):
print(s)
def Read():
r = raw_input()
return r
name = Read()
WriteLine(name)
I'm currently taking a Python course, and got to the chapter in our book that talks about functions. (Please note, this is my first time learning any programming.)
One of the exercises I'm working on at the moment asks for me to turn a bunch of conditional statements into a function (i.e. generalization).
To make this brief, my problem is this:
After I define a function, let's say like so...
def count_letter(letter,string):
count = 0
for letter in string:
count += 1
print(count)
(That is the work, as far as I can recall, for what I typed up for the problem.)
I run the program, then call the function in the shell as usual...
(Example directly below)
>>> count_letter(a,bananana)
And I get the following output...
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
count_letter(a,bananana)
NameError: name 'a' is not defined
My teacher and everyone in our class can't figure out why we're getting such an error. We would understand if it was some other type of an error, but having the shell tell us an argument is 'undefined' (i.e. a variable, as we understand the error) is something we haven't been able to figure out.
We've been staring at the code for a week and still can't figure it out.
Any help would be very appreciated.
Afterthought: I'm trying to count the number of "a"s within "bananana" in the example. Thought I should clear the ambiguity there.
As written, a and bananana are the names of variables which should be defined in a similar way you defined the variable count. For example:
>>> character_to_search = 'l'
>>> text = 'Hello World'
>>> count_letter(character_to_search, text)
would be a correct syntax, because both character_to_search and text are undefined.
Another possibility is that instead of using actual variables, your intention was to pass strings directly to the function. In this case, your syntax is slightly incorrect. It should be (note the single quotes):
count_letter('a', 'bananana')
I am as green as it gets when it comes to programming but have been making progress. My mind however still needs to fully understand what is happening.
class classname:
def createname(self, name):
self.name = name;
def displayname(self):
return self.name;
def saying(self):
print("Hello %s" % self.name);
first = classname;
second = classname;
first.createname("Bobby");
Error:
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
first.createname("Bobby")
TypeError: createname() missing 1 required positional argument: 'name'
The error tells me that I need 1 more argument in the name, so I must be going wrong there, but I already tried something like this:
first.createname("bobby", "timmy");
I also rule out the fact that it would be the def createname(self, name), because self is or should be alone and not included? So I do not really understand what is going on.
You have not actually created an object yet.
For instance, you would want to write:
first = classname()
instead of just
first = classname
At the moment, how you wrote it, first is pointing to a class. E.g., if you ask what first is, you'd get:
<class '__main__.classname'>
However, after instantiating it (by simply adding the () at the end), you'd see that first is now:
<__main__.classname object at 0x101cfa3c8>
The important distinction here is that your call set first as a class, whereas mine set it as an object.
Think about it like this: A class is to an object as humankind is to you, or as canine is to Lassie.
You set it as "canine", whereas you wanted to set it as "Lassie".
Note: you also usually want to initialize your objects. For that, you place an __init__ method in your class.