Can someone tell me what are the mistakes in this code? - python

x = 4
y = 5
a = 3(x+y)
I want to know the mistakes in this code. I know I am a newbie but can someone help me out?

a = 3(x+y)
3 is not a function, and here you are trying to call it like one.
I assume you intend multiplication. Try:
a = 3 * (x + y)

The issue is the syntax. You are communication with the Python interpreter in the language it doesn't know (like communicating to aliens in English ;)).
When you do 3(), python thinks you are making the call to function due to the presence of (). Hence you will get error as:
>>> 3()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
In case you want to multiply (x+y) with 3 and store it in a, your syntax should be:
a = 3 * (x+y)
Read a tutorial on Python's Arithmetic Operators for more details.

NO operator is assumed to be present . It must be written explicitly. In the following example, the multiplication operator after b must be explicitly written. It make the code workable.
a = c.d.b(xy) // usual arithmetic statement.
a = c*d*b*(x*y) // python correct arithmetic statement.
I think this is also happened with you. try to avoid such mistakes.becuase you can not assume any operator to be present in any operation of any programming language.
Keep in mind when you are trying to do any operation.
your given code:
a = 3(x+y)
your correct code is :
a = 3 * (x + y)

Related

8/2(2+2) doesn't work in python but 8/2+(2+2) and 8/2*(2+2) do. Why? [duplicate]

This question already has an answer here:
Why do I get "TypeError: 'int' object is not callable" from code like "5(side_length**2)"?
(1 answer)
Closed 5 months ago.
Trying to understand operands in python.
8/2(2+2) gave the following error:
TypeError Traceback (most recent call last)
<ipython-input-12-8949a58e2cfa> in <module>
----> 1 8/2(2 + 2)
TypeError: 'int' object is not callable.
Trying to do this like this then using sum() then as python dictionary then in numpy.
Python doesn't support implicit multiplication. When Python tries to run 2(2+2), it tries to call the numeric literal 2 as a function, passing 2+2 as an argument to it. You need to use * between things you want to multiply.
There is no operator between the 2 and the ( - human math assumes a multiplication here but a computer does not.
The parser sees 2(...) - which is interpreted as a function with the name 2 and a parameter.
Since there is no default function with that name and there is no def 2(x) you get that error message.
Additionally 2 is not a vaild function name in python.
Python doesn't work like normal maths. 2(2+2) will not be executed as 2×4. Instead, 2 will be treated as a function, which is not callable (your error message) . To do that, you've to put operator between 2 and (2+2). Try putting a * between 2 and (2+2). Your expression would be 8/2*(2+2)

Python String and Instance Object confusion

Inside a class, in the __repr__ constructor, python is confused about what is a string and what isn't. This is for a school project, don't worry, I won't actually be handling social security numbers here.
The code below does not work:
def __repr__(self):
return (
'\nName:\t'+self.getName()+':\t\t\tNurse\n'+
'\tPhone:\t\t\t\t\t\t('+str(self.getPhoneNumber())[0:3]+') '+
str(self.getPhoneNumber())[3:6]+'-'+str(self.getPhoneNumber())[6:10]+'\n'+
'\tOverseeing Doctor:\t\t\t'+self.getDoctor()+'\n'
'\tDescription:\t\t\t\t'+self.getDesc()+'\n'+
'\tBirthday:\t\t\t\t\t'+self.getBDay()+'\n'+
'\tSocial Security Number:\t\t***-**-'+str(round(self.getSocial()))[5:9]+'\n'+#error is in this line
str(self._cases[i] for i in range(len(self._cases)))
)
However, in a different class, I have nearly identical code that does work:
def __repr__(self):
return (
'\nName:\t'+self.getName()+':\t\t\tDoctor\n'+
'\tPhone:\t\t\t\t\t\t('+str(self.getPhoneNumber())[0:3]+') '+
str(self.getPhoneNumber())[3:6]+'-'+str(self.getPhoneNumber())[6:10]+'\n'+
'\tDepartment:\t\t\t\t\t'+self.getDepartment()+'\n'
'\tDescription:\t\t\t\t'+self.getDesc()+'\n'+
'\tBirthday:\t\t\t\t\t'+self.getBDay()+'\n'+
'\tSocial Security Number:\t\t***-**-'+str(self.getSocial())[5:9]+'\n'+
str(self._cases)+'\n'
)
Please tell me what is different between the two, and how to fix the initial code.
You claim there is an error in this part:
str(round(self.getSocial()))[5:9]
but did not tell us anything about your actual error; errors come with tracebacks and exception messages, but without those details we cannot tell you anything about what might go wrong there. Perhaps self.getSocial() returns a string, and round() only takes floating point numbers:
>>> round('123')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a float is required
You'll need to give us that error message as well as your inputs (the return value of self.getSocial()) and the expected output so we can help you solve that part; perhaps you misunderstood what round() does.
Next, you are trying to convert a generator expression to a string:
str(self._cases[i] for i in range(len(self._cases))
Everything between the parentheses is a lazy evaluating loop, but str() won't evaluate it for you.
If you wanted to produce a string of all cases, joined together with, say, tabs, use str.join() instead:
'\t'.join([str(self._cases[i]) for i in range(len(self._cases)])
You really should look into using str.format() templating; it'll make for much improved and readable code. Your 'working' example would translate to:
def __repr__(self):
phone = str(self.getPhoneNumber())
social = str(self.getSocial())
return (
'\n'
'Name:\t{name}:\t\t\tDoctor\n'
'\tPhone:\t\t\t\t\t\t({phone1}) {phone2}-{phone3}\n'
'\tDepartment:\t\t\t\t\t{dept}\n'
'\tDescription:\t\t\t\t{desc}\n'
'\tBirthday:\t\t\t\t\t{bday}\n'
'\tSocial Security Number:\t\t***-**-{social}\n'
'{cases}\n').format(
name=self.getName(),
phone1=phone[:3], phone2=phone[3:6], phone3=phone[6:10],
dept=self.getDepartment(), desc=self.getDesc(),
bday=self.getBDay(), social=social[5:9],
cases=self._cases)

Python - Function - Argument said to be "undefined"

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')

What is the difference between syntax error and runtime error?

For example:
def tofloat(i):
return flt(i)
def addnums(numlist):
total = 0
for i in numlist:
total += tofloat(i)
return total
nums = [1 ,2 ,3]
addnums(nums)
The flt is supposed to be float, but I'm confused whether it is a syntax error or a runtime error.
Actually, it is a runtime error, because Python will try to resolve the flt name during runtime (because it's a dynamic language), and it won't find it. When this happens, Python yields and exception saying that it couldn't find the symbol you were using flt and all this happens at runtime.
Syntax errors happen when the interpreter find something not compelling with Python's syntax. For example: The Python's grammar doesn't recognize the input syntax as a valid Python program. This may happen when:
You forgot to add : at the end of an if, def, class, etc expression
You forgot to close some parenthesis or brackets, etc.
A lot of places else when you don't adhere to python's grammar :)
In your example, there is nothing wrong with the grammar. For the interpreter, flt(i) is a very valid call to a flt method which had to be check at runtime within the scopes if it really exists. So the interpreter won't complaint and the syntax of your problem is good.
Actually, this can be seen as a disadvantage over compiled languages like C#, C++, etc. This kind of errors can be detected sooner at compile time, and the compiler screams loud when it find it so you can notice it.
With dynamic languages, you won't notice this until the actual method is called. Your program is simple, so you may find it quick. But, what about the missing o in float was inside some legacy framework within a subclass of a subclass of a class, as a property, inside some other module, etc. That would be harsh :)
UPDATE: The execution model in Python's docs are a great read if you're into how does Python internals works. This will clarify your doubt further and will give you a lot of knowledge :)
Hope this helps!
SyntaxError is raised by parser when it founds that your syntax is not correct, like missing colons, parenthesis, invalid statements etc. It'll not allow you to execute your code until you don't fix that the issue.
Your code will throw only error at runtime, i.e when the function tofloat(i) is called for the first time, so it is a runtime error. Specifically NameError.
Also a runtime error won't stop your program's execution until that buggy part is not executed. So, your code can actually run fine if you don't call tofloat ever.
The code below executes properly up to third line but then stops as NameError is raised.(a runtime error)
print 1
print 2
print 3
print foo
output:
1
2
3
Traceback (most recent call last):
File "so.py", line 4, in <module>
print foo
NameError: name 'foo' is not defined
This code won't execute as we made a SyntaxError, even though the first 3 lines are perfectly okay:
print 1
print 2
print 2
print (foo
Output:
$ python so.py
File "so.py", line 5
^
SyntaxError: invalid syntax
Note that there's also a RunTimeError in python, which is raised when an error is detected that doesn't fall in any of the other categories
You have a NameError, Your code should read:
def tofloat(i):
return float(i)
There is no flt method in Python, that is why it is not working for you.
Incidentally, you really don't need to wrap that float casting into a function, and your whole code can be written as:
def addnums(numlist):
return sum(map(float, numlist))
Using it:
>>> addnums(range(4))
6.0

TypeError: 'float' object is not callable

I am trying to use values from an array in the following equation:
for x in range(len(prof)):
PB = 2.25 * (1 - math.pow(math.e, (-3.7(prof[x])/2.25))) * (math.e, (0/2.25)))
When I run I receive the following error:
Traceback (most recent call last):
File "C:/Users/cwpapine/Desktop/1mPro_Chlavg", line 240, in <module>
PB = float(2.25 * (1 - math.pow(math.e, (-3.7(prof[x])/2.25))) * (math.e, (0/2.25)))
TypeError: 'float' object is not callable
What is the cause, and how can the problem be resolved?
There is an operator missing, likely a *:
-3.7 need_something_here (prof[x])
The "is not callable" occurs because the parenthesis -- and lack of operator which would have switched the parenthesis into precedence operators -- make Python try to call the result of -3.7 (a float) as a function, which is not allowed.
The parenthesis are also not needed in this case, the following may be sufficient/correct:
-3.7 * prof[x]
As Legolas points out, there are other things which may need to be addressed:
2.25 * (1 - math.pow(math.e, (-3.7(prof[x])/2.25))) * (math.e, (0/2.25)))
^-- op missing
extra parenthesis --^
valid but questionable float*tuple --^
expression yields 0.0 always --^
The problem is with -3.7(prof[x]), which looks like a function call (note the parens). Just use a * like this -3.7*prof[x].
You have forgotten a * between -3.7 and (prof[x]).
Thus:
for x in range(len(prof)):
PB = 2.25 * (1 - math.pow(math.e, (-3.7 * (prof[x])/2.25))) * (math.e, (0/2.25)))
Also, there seems to be missing an ( as I count 6 times ( and 7 times ), and I think (math.e, (0/2.25)) is missing a function call (probably math.pow, but thats just a wild guess).
While this may not be an answer to this question in particular, another reason you could get this error is if you have defined "range" as a variable.
range = 0
for x in range(len(array)):
#will give an error, because it's trying to multiply "range" with "(len(array))"
The solution would be to rename your variable to a synonym (period) or append something to it (range1, range_a)
The question has been answered but for others, the reason for the same error might be highly possible due to the following reason:
Sometimes, when you use a variable name same as one of the inbuilt functions and when you try to call that inbuilt function later on, its gonna give you a type error.
For example, somewhere in your code you define a variable as:
sum = 0
Maybe to use it as an accumulator variable in global dataframe.
Now, later when you're defining a function in which you want to call the inbuilt function sum() , its gonna give an type error as you have over-written an in-built function name.
That's why, you should avoid the use in-built function names like str, range, sum, etc.. as one of the variable names in your code.

Categories

Resources