473,394 Members | 1,701 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Checking var is a number?

Hi,
I am very new to all this and need to know how to check
a variable to see if it is a number or not. Also can anyone
recommend a reference book apart from dive into python
preferably a reference with good examples of how to impliment
code.

The project i have been given to work in is all CGI written
in Python.

Many Thanks
David Phillips

Jun 6 '06 #1
5 1779
da**********@ntlworld.com írta:
Hi,
I am very new to all this and need to know how to check
a variable to see if it is a number or not. Also can anyone
recommend a reference book apart from dive into python
preferably a reference with good examples of how to impliment
code.
There are different types of number in Python.

Integers and Long integers (type: 'int', 'long')
Decimal numbers (class 'decimal.Decimal')
Floating point numbers (type 'float')

You can check this way:

import decimal

def print_type(var):
if isinstance(var,int):
print "this is an integer"
elif isinstance(var,long):
print "this is a long integer"
elif isinstance(var,decimal.Decimal):
print "this is a decimal"
elif isinstance(var,float):
print "this is a float"
else:
print "this is something else..."

Test this:

....
print_type(12) this is an integer print_type(12L) this is a long integer print_type(3.5) this is a float print_type('hello world') this is something else... print_type('44') this is something else... d = Decimal('123')
print_type(d) this is a decimal The project i have been given to work in is all CGI written
in Python.

Probaby you wanted to convert a string into a number? For example:
int(s) 1234 s = 'Foo'
int(s) Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): Foo
Or you can catch the exception:
s = 'Foo2'
try: .... intval = int(s)
.... except ValueError:
.... print "This cannot be converted to an int."
....
This cannot be converted to an int.


Good luck!

Laszlo
Jun 6 '06 #2
da**********@ntlworld.com wrote:
I am very new to all this and need to know how to check
a variable to see if it is a number or not.
assuming that "variable" means "string object" and "number" means
"integer", you can use the isdigit predicate:

if var.isdigit():
print "all characters in", var, "are digits"

if you want to check for anything that can be converted to a float, the
best way is to do the conversion and trap any ValueError that may occur:

try:
value = float(var)
except ValueError:
print "not a valid float"

if you want an integer instead, replace "float" with "int".

if you had something else in mind, let us know.
Also can anyone recommend a reference book apart from dive into python
preferably a reference with good examples of how to impliment code.


you can find an extensive list of available books here:

http://wiki.python.org/moin/PythonBooks

some on-line code collections:

http://aspn.activestate.com/ASPN/Python/Cookbook/
http://effbot.org/zone/librarybook-index.htm

and don't forget the core references:

http://docs.python.org/lib/
http://docs.python.org/ref/

</F>

Jun 6 '06 #3
> Good luck!
Laszlo


I actually managed to get it sorted but i like that way of
doing it much better actually :)

Cheers
David P

Jun 6 '06 #4
I took a variable to mean a container for diffirent kinds of
information
either strings or integers etc, as i am mainly a asp, php, asp.net
developer.

Thanks for the list of references, that will come in very handy

Cheers Guys
David P

Jun 6 '06 #5
da**********@ntlworld.com wrote:
I took a variable to mean a container for diffirent kinds of
information either strings or integers etc, as i am mainly a
asp, php, asp.net developer.


in python, a variable is a name that refers to a specific object. it's
the object that has a type and a value, not the variable. this article
might be somewhat helpful:

http://effbot.org/zone/python-objects.htm

</F>

Jun 6 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: shank | last post by:
I use ASP to check users data they submit. In particular, I'm checking for credit cards and I also use a server component DynuCreditCard. It basically affirms that the number "could be" a real...
6
by: Ben Ingram | last post by:
Hi all, I am writing a template matrix class in which the template parameters are the number of rows and number of columns. There are a number of reasons why this is an appropriate tradeoff for...
5
by: BerkshireGuy | last post by:
Hello everyone, I have a bond form that a user uses to enter data. One of my fields, is PolicyNumber. I added some code on the Before Update event of txtPolicyNumber that checks to see if...
8
by: Brendan | last post by:
There must be an easy way to do this: For classes that contain very simple data tables, I like to do something like this: class Things(Object): def __init__(self, x, y, z): #assert that x,...
4
by: Patient Guy | last post by:
Does anyone have any coding rules they follow when doing argument checking? When arguments fail during check, do you return from the call with an ambiguous return value, or do you throw...
1
by: halcyon943 | last post by:
have 4 folders that I watch and need to move files from to another location. Three constraints: -Finish time. Make sure the program stops transferring files at a specific time -Number of...
125
by: jacob navia | last post by:
We hear very often in this discussion group that bounds checking, or safety tests are too expensive to be used in C. Several researchers of UCSD have published an interesting paper about this...
11
by: Bryan Crouse | last post by:
I am looking a way to do error checking on a string at compile time, and if the string isn't the correct length have then have the compiler throw an error. I am working an embedded software that...
1
by: imageguy | last post by:
We are trying to implement a system that checks the version of the application against a version number stored in the database. We don't want the app and the db don't become out of sync. We...
21
by: ningxin | last post by:
Hi, i am currently taking a module in c++ in the university, and was given an assignment. because i have no prior background on the subject, everything is kind of new to me. i have tried for quite...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.