Why this simple function is not working in python 2.7?
>>> def a(b,h):
... return b*h/2
... a(3,4)
File "<stdin>", line 3
a(3,4)
^
SyntaxError: invalid syntax
>>>
In the interactive interpreter, you'll need to add a blank line to close off the statement before the function is defined:
>>> def a(b,h):
... return b*h/2
...
>>>
Once you do, a new >>> prompt appears and you can enter the a(3,4) call.
From the Python reference documentation on Interactive input:
Note that a (top-level) compound statement must be followed by a blank line in interactive mode; this is needed to help the parser detect the end of the input.
Note that you may run into issues with integer division here; in Python 2 if both operands to the / division operator are integers, you'll get an integer result. See How can I force division to be floating point? Division keeps rounding down to 0 for work-arounds.
Related
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)
Ran into some interesting Python behavior today. I though I was writing
print("{}".format("some value"))
but instead I wrote
print("{}").format("some value")
and funnily enough it worked. So my question is, how does this work?
Digging deeper
This behavior seems to be python2 specific.
Python2.7
>>> print("{}").format("testing")
testing
Python3.4
>>> print("{}").format("testing)
File "<stdin>", line 1
print("{}").format("testing)
^
SyntaxError: EOL while scanning string literal
It also seems like the print function of python2 doesn't have a return value but Python3 does? so that confuses me even more.
Python2.7
>>> type(print("testing))
File "<stdin>", line 1
type(print("testing))
^
SyntaxError: invalid syntax
>>> a = print("testing")
File "<stdin>", line 1
a = print("testing")
^
SyntaxError: invalid syntax
Python3.4
>>> type(print("{}"))
{}
<class 'NoneType'>
>>> a = print("{}")
{}
>>> a
>>> type(a)
<class 'NoneType'>
In Python 2, print is a statement, not a function (unless you do from __future__ import print_function at the top of your module). This means that the parentheses around the thing you're printing are not part of a function call, but just treated as grouping parentheses. In the situation you describe ("{}") is the same as "{}" (the parens do nothing), so the format call works just like you'd expect if you wrote "{}".format(...).
In Python 3, print is a function, so the parentheses are not optional and can't be put in the wrong place. print returns None, so you're almost certainly going to get an error if you do print(something).something_else, since None doesn't have a something_else attribute.
In Python 2.7, print is a statement; this means that
print("{}").format("testing")
prints one expression, the result of the expression ("{}").format("testing"). That is, the format method is called on the (parenthesized) string before the print statement is evaluated. If you use
from __future__ import print_function
in the 2.7 examples, you'll get identical behavior to Python 3.
You're missing the closing quote after some strings (e.g. "testing).
As others are saying, Python 2 doesn't have a print() function, it has a print statement. Your strings (even if they were properly closed) are not what and where you think they are.
In Python 2, print is a statement keyword like raise, not a function. Parentheses aren't used for its arguments, and so print("{}").format("testing") is parsed as though you'd written print ("{}").format("testing"), which is the same as print(("{}").format("testing")). Because print is a statement, it cannot be used as an expression, and therefore it cannot have a return value.
If you want print in Python 2 to act like Python 3's print function, place this line at the top of your file:
from __future__ import print_function
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)
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
I have a Python function that takes a numeric argument that must be an integer in order for it behave correctly. What is the preferred way of verifying this in Python?
My first reaction is to do something like this:
def isInteger(n):
return int(n) == n
But I can't help thinking that this is 1) expensive 2) ugly and 3) subject to the tender mercies of machine epsilon.
Does Python provide any native means of type checking variables? Or is this considered to be a violation of the language's dynamically typed design?
EDIT: since a number of people have asked - the application in question works with IPv4 prefixes, sourcing data from flat text files. If any input is parsed into a float, that record should be viewed as malformed and ignored.
isinstance(n, int)
If you need to know whether it's definitely an actual int and not a subclass of int (generally you shouldn't need to do this):
type(n) is int
this:
return int(n) == n
isn't such a good idea, as cross-type comparisons can be true - notably int(3.0)==3.0
Yeah, as Evan said, don't type check. Just try to use the value:
def myintfunction(value):
""" Please pass an integer """
return 2 + value
That doesn't have a typecheck. It is much better! Let's see what happens when I try it:
>>> myintfunction(5)
7
That works, because it is an integer. Hm. Lets try some text.
>>> myintfunction('text')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in myintfunction
TypeError: unsupported operand type(s) for +: 'int' and 'str'
It shows an error, TypeError, which is what it should do anyway. If caller wants to catch that, it is possible.
What would you do if you did a typecheck? Show an error right? So you don't have to typecheck because the error is already showing up automatically.
Plus since you didn't typecheck, you have your function working with other types:
Floats:
>>> print myintfunction(2.2)
4.2
Complex numbers:
>>> print myintfunction(5j)
(2+5j)
Decimals:
>>> import decimal
>>> myintfunction(decimal.Decimal('15'))
Decimal("17")
Even completely arbitrary objects that can add numbers!
>>> class MyAdderClass(object):
... def __radd__(self, value):
... print 'got some value: ', value
... return 25
...
>>> m = MyAdderClass()
>>> print myintfunction(m)
got some value: 2
25
So you clearly get nothing by typechecking. And lose a lot.
UPDATE:
Since you've edited the question, it is now clear that your application calls some upstream routine that makes sense only with ints.
That being the case, I still think you should pass the parameter as received to the upstream function. The upstream function will deal with it correctly e.g. raising an error if it needs to. I highly doubt that your function that deals with IPs will behave strangely if you pass it a float. If you can give us the name of the library we can check that for you.
But... If the upstream function will behave incorrectly and kill some kids if you pass it a float (I still highly doubt it), then just just call int() on it:
def myintfunction(value):
""" Please pass an integer """
return upstreamfunction(int(value))
You're still not typechecking, so you get most benefits of not typechecking.
If even after all that, you really want to type check, despite it reducing your application's readability and performance for absolutely no benefit, use an assert to do it.
assert isinstance(...)
assert type() is xxxx
That way we can turn off asserts and remove this <sarcasm>feature</sarcasm> from the program by calling it as
python -OO program.py
Python now supports gradual typing via the typing module and mypy. The typing module is a part of the stdlib as of Python 3.5 and can be downloaded from PyPi if you need backports for Python 2 or previous version of Python 3. You can install mypy by running pip install mypy from the command line.
In short, if you want to verify that some function takes in an int, a float, and returns a string, you would annotate your function like so:
def foo(param1: int, param2: float) -> str:
return "testing {0} {1}".format(param1, param2)
If your file was named test.py, you could then typecheck once you've installed mypy by running mypy test.py from the command line.
If you're using an older version of Python without support for function annotations, you can use type comments to accomplish the same effect:
def foo(param1, param2):
# type: (int, float) -> str
return "testing {0} {1}".format(param1, param2)
You use the same command mypy test.py for Python 3 files, and mypy --py2 test.py for Python 2 files.
The type annotations are ignored entirely by the Python interpreter at runtime, so they impose minimal to no overhead -- the usual workflow is to work on your code and run mypy periodically to catch mistakes and errors. Some IDEs, such as PyCharm, will understand type hints and can alert you to problems and type mismatches in your code while you're directly editing.
If, for some reason, you need the types to be checked at runtime (perhaps you need to validate a lot of input?), you should follow the advice listed in the other answers -- e.g. use isinstance, issubclass, and the like. There are also some libraries such as enforce that attempt to perform typechecking (respecting your type annotations) at runtime, though I'm uncertain how production-ready they are as of time of writing.
For more information and details, see the mypy website, the mypy FAQ, and PEP 484.
if type(n) is int
This checks if n is a Python int, and only an int. It won't accept subclasses of int.
Type-checking, however, does not fit the "Python way". You better use n as an int, and if it throws an exception, catch it and act upon it.
Don't type check. The whole point of duck typing is that you shouldn't have to. For instance, what if someone did something like this:
class MyInt(int):
# ... extra stuff ...
Programming in Python and performing typechecking as you might in other languages does seem like choosing a screwdriver to bang a nail in with. It is more elegant to use Python's exception handling features.
From an interactive command line, you can run a statement like:
int('sometext')
That will generate an error - ipython tells me:
<type 'exceptions.ValueError'>: invalid literal for int() with base 10: 'sometext'
Now you can write some code like:
try:
int(myvar) + 50
except ValueError:
print "Not a number"
That can be customised to perform whatever operations are required AND to catch any errors that are expected. It looks a bit convoluted but fits the syntax and idioms of Python and results in very readable code (once you become used to speaking Python).
I would be tempted to to something like:
def check_and_convert(x):
x = int(x)
assert 0 <= x <= 255, "must be between 0 and 255 (inclusive)"
return x
class IPv4(object):
"""IPv4 CIDR prefixes is A.B.C.D/E where A-D are
integers in the range 0-255, and E is an int
in the range 0-32."""
def __init__(self, a, b, c, d, e=0):
self.a = check_and_convert(a)
self.b = check_and_convert(a)
self.c = check_and_convert(a)
self.d = check_and_convert(a)
assert 0 <= x <= 32, "must be between 0 and 32 (inclusive)"
self.e = int(e)
That way when you are using it anything can be passed in yet you only store a valid integer.
how about:
def ip(string):
subs = string.split('.')
if len(subs) != 4:
raise ValueError("incorrect input")
out = tuple(int(v) for v in subs if 0 <= int(v) <= 255)
if len(out) != 4:
raise ValueError("incorrect input")
return out
ofcourse there is the standard isinstance(3, int) function ...
For those who are looking to do this with assert() function. Here is how you can efficiently place the variable type check in your code without defining any additional functions. This will prevent your code from running if the assert() error is raised.
assert(type(X) == int(0))
If no error was raised, code continues to work. Other than that, unittest module is a very useful tool for this sorts of things.