473,580 Members | 2,870 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how best to check a value? (if/else or try/except?)

My code is below. The main focus would be on the OnStart method. I want
to make sure that a positive integer is entered in the input box. At
first I tried an if/else clause, then switched to try/except. Neither is
perfect yet, but I was wondering which I should try for in the first
place. I figure I need to check for an emptry string, non-numeric
strings (maybe these are the same check), 0 and negative numbers (which
might also fall into the category of 'anything but a number' because of
the negative sign).

Thanks.

-------------------------------

import wx
class MyTimer(wx.Fram e):

def __init__(self):
wx.Frame.__init __(self, None, wx.ID_ANY, 'Timer',
style=wx.DEFAUL T_FRAME_STYLE ^
wx.RESIZE_BORDE R ^ wx.MAXIMIZE_BOX )
panel = wx.Panel(self)

mainSizer = wx.BoxSizer(wx. VERTICAL)
inputSizer = wx.BoxSizer(wx. HORIZONTAL)

self.progress = wx.Gauge(panel, wx.ID_ANY, 100, size=(300, 20))
self.status = wx.StaticText(p anel, wx.ID_ANY, 'Enter a time.')
prompt = wx.StaticText(p anel, wx.ID_ANY, 'Time to wait:')
self.input = wx.TextCtrl(pan el, wx.ID_ANY, size=(20, 20))
self.start = wx.Button(panel , wx.ID_ANY, 'Start')
self.reset = wx.Button(panel , wx.ID_ANY, 'Reset')
self.reset.Disa ble()
self.timer = wx.Timer(self)

mainSizer.Add(s elf.progress, flag=wx.ALIGN_C ENTER | wx.ALL ^
wx.BOTTOM,
border=10)
mainSizer.Add(s elf.status, flag=wx.ALIGN_C ENTER | wx.ALL,
border=10)
mainSizer.Add(i nputSizer, flag=wx.ALIGN_C ENTER | wx.BOTTOM,
border=10)
inputSizer.Add( prompt, flag=wx.ALIGN_C ENTER)
inputSizer.Add( self.input, flag=wx.ALIGN_C ENTER | wx.LEFT |
wx.RIGHT,
border=5)
inputSizer.Add( self.start, flag=wx.ALIGN_C ENTER)
inputSizer.Add( self.reset, flag=wx.ALIGN_C ENTER)

self.Bind(wx.EV T_TEXT_ENTER, self.OnStart, self.input)
self.Bind(wx.EV T_BUTTON, self.OnStart, self.start)
self.Bind(wx.EV T_TIMER, self.OnTimer, self.timer)
self.Bind(wx.EV T_BUTTON, self.OnReset, self.reset)

panel.SetSizer( mainSizer)
mainSizer.Fit(s elf)

def OnStart(self, event):
try:
self.time = int(self.input. GetValue())
self.minutes_pa ssed = 1
self.minutes_re maining = self.time - 1
self.start.Disa ble()
self.input.Disa ble()
self.reset.Enab le()
self.status.Set Label('%s minute(s) remaining.' % self.time)
self.timer.Star t(1000)
except ValueError:
wx.MessageBox(' Enter a valid time.', 'Invalid time entered',
wx.OK | wx.ICON_ERROR)
self.input.Clea r()

def OnReset(self, event):
if self.timer.IsRu nning():
self.timer.Stop ()
self.input.Clea r()
self.input.Enab le()
self.start.Enab le()
self.reset.Disa ble()
self.status.Set Label('Enter a new time.')
self.progress.S etValue(0)
self.minutes_pa ssed = 1

def OnTimer(self, event):
if self.minutes_re maining != 0:
self.progress.S etValue(self.mi nutes_passed * (100.0 /
self.time))
self.status.Set Label('%s minute(s) remaining.' %
self.minutes_re maining)
self.minutes_pa ssed += 1
self.minutes_re maining -= 1
else:
self.timer.Stop ()
self.progress.S etValue(self.mi nutes_passed * (100.0 /
self.time))
self.status.Set Label('%s minute(s) have elapsed.' % self.time)
wx.Sound.Play(w x.Sound(r'C:\Wi ndows\Media\not ify.wav'))
class MyApp(wx.App):

def OnInit(self):
frame = MyTimer()
self.SetTopWind ow(frame)
frame.Show()
return True
if __name__ == '__main__':
app = MyApp(False)
app.MainLoop()
Jul 27 '06 #1
4 3676
John,

The way I do it is, is I ask myself 'is there a more common (basic)
base between the code paths or do they both have about a 50/50 chance
on average?' or 'will one code path be taken during an error and the
other one during the normal processing?'. If there is a clear single
common/usual/basic case or I try to detect an error I use 'try/except',
if it could go either way on average I use 'if'.

In general in Python we follow the 'it is better to ask forgiveness
than to ask permission'. In other words if you don't know if a piece
of data you have is a function and is callable you just call it and if
it raises an exception then you'll know it's not. This is the opposite
of C where you have to spend a good deal of time validating your input
arguments before you can safely continue.

That said, Python is also a practical language and quite often if you
do just one check then an 'if' may take 2 lines (if no need for else)
while a try/except will take 4 lines. So just apply common sense. For
example, I want to find out if I can call f then do some stuff if that
is the case:
try:
f(arg)
#...do stuff because f is callable...
except TypeError:
pass
# ... if f is not callable, then I don't care...

But of course it is much shorter to do:
if callable(f):
#...do stuff because f is callable...

Hope this helps,
Nick Vatamaniuc

John Salerno wrote:
My code is below. The main focus would be on the OnStart method. I want
to make sure that a positive integer is entered in the input box. At
first I tried an if/else clause, then switched to try/except. Neither is
perfect yet, but I was wondering which I should try for in the first
place. I figure I need to check for an emptry string, non-numeric
strings (maybe these are the same check), 0 and negative numbers (which
might also fall into the category of 'anything but a number' because of
the negative sign).

Thanks.

-------------------------------

import wx
class MyTimer(wx.Fram e):

def __init__(self):
wx.Frame.__init __(self, None, wx.ID_ANY, 'Timer',
style=wx.DEFAUL T_FRAME_STYLE ^
wx.RESIZE_BORDE R ^ wx.MAXIMIZE_BOX )
panel = wx.Panel(self)

mainSizer = wx.BoxSizer(wx. VERTICAL)
inputSizer = wx.BoxSizer(wx. HORIZONTAL)

self.progress = wx.Gauge(panel, wx.ID_ANY, 100, size=(300, 20))
self.status = wx.StaticText(p anel, wx.ID_ANY, 'Enter a time.')
prompt = wx.StaticText(p anel, wx.ID_ANY, 'Time to wait:')
self.input = wx.TextCtrl(pan el, wx.ID_ANY, size=(20, 20))
self.start = wx.Button(panel , wx.ID_ANY, 'Start')
self.reset = wx.Button(panel , wx.ID_ANY, 'Reset')
self.reset.Disa ble()
self.timer = wx.Timer(self)

mainSizer.Add(s elf.progress, flag=wx.ALIGN_C ENTER | wx.ALL ^
wx.BOTTOM,
border=10)
mainSizer.Add(s elf.status, flag=wx.ALIGN_C ENTER | wx.ALL,
border=10)
mainSizer.Add(i nputSizer, flag=wx.ALIGN_C ENTER | wx.BOTTOM,
border=10)
inputSizer.Add( prompt, flag=wx.ALIGN_C ENTER)
inputSizer.Add( self.input, flag=wx.ALIGN_C ENTER | wx.LEFT |
wx.RIGHT,
border=5)
inputSizer.Add( self.start, flag=wx.ALIGN_C ENTER)
inputSizer.Add( self.reset, flag=wx.ALIGN_C ENTER)

self.Bind(wx.EV T_TEXT_ENTER, self.OnStart, self.input)
self.Bind(wx.EV T_BUTTON, self.OnStart, self.start)
self.Bind(wx.EV T_TIMER, self.OnTimer, self.timer)
self.Bind(wx.EV T_BUTTON, self.OnReset, self.reset)

panel.SetSizer( mainSizer)
mainSizer.Fit(s elf)

def OnStart(self, event):
try:
self.time = int(self.input. GetValue())
self.minutes_pa ssed = 1
self.minutes_re maining = self.time - 1
self.start.Disa ble()
self.input.Disa ble()
self.reset.Enab le()
self.status.Set Label('%s minute(s) remaining.' % self.time)
self.timer.Star t(1000)
except ValueError:
wx.MessageBox(' Enter a valid time.', 'Invalid time entered',
wx.OK | wx.ICON_ERROR)
self.input.Clea r()

def OnReset(self, event):
if self.timer.IsRu nning():
self.timer.Stop ()
self.input.Clea r()
self.input.Enab le()
self.start.Enab le()
self.reset.Disa ble()
self.status.Set Label('Enter a new time.')
self.progress.S etValue(0)
self.minutes_pa ssed = 1

def OnTimer(self, event):
if self.minutes_re maining != 0:
self.progress.S etValue(self.mi nutes_passed * (100.0 /
self.time))
self.status.Set Label('%s minute(s) remaining.' %
self.minutes_re maining)
self.minutes_pa ssed += 1
self.minutes_re maining -= 1
else:
self.timer.Stop ()
self.progress.S etValue(self.mi nutes_passed * (100.0 /
self.time))
self.status.Set Label('%s minute(s) have elapsed.' % self.time)
wx.Sound.Play(w x.Sound(r'C:\Wi ndows\Media\not ify.wav'))
class MyApp(wx.App):

def OnInit(self):
frame = MyTimer()
self.SetTopWind ow(frame)
frame.Show()
return True
if __name__ == '__main__':
app = MyApp(False)
app.MainLoop()
Jul 27 '06 #2
On Thu, 2006-07-27 at 20:44 +0000, John Salerno wrote:
My code is below. The main focus would be on the OnStart method. I want
to make sure that a positive integer is entered in the input box. At
first I tried an if/else clause, then switched to try/except. Neither is
perfect yet, but I was wondering which I should try for in the first
place. I figure I need to check for an emptry string, non-numeric
strings (maybe these are the same check), 0 and negative numbers (which
might also fall into the category of 'anything but a number' because of
the negative sign).
Have a look at using a wx.Validator in your wx.TextCtrl.
Syntax for wx.TextCtrl:

wx.TextCtrl(par ent, id, value="", pos=wx.DefaultP osition,
size=wx.Default Size, style=0, validator=wx.De faultValidator,
name=wx.TextCtr lNameStr)

This will enable you to automagically check the TextCtrl if it's empty,
has wrong data type, does not meet a prescribed condition (eg: no
negative numbers) and do something if it does not pass validation (eg:
colour the background of the TextCtrl red, initiate a system beep, etc).

Regards,

John

--
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

Jul 27 '06 #3
John McMonagle wrote:
Have a look at using a wx.Validator in your wx.TextCtrl.
Ah, good thinking! I wasn't even considering another option like that,
which probably makes more sense anyway!
Jul 28 '06 #4
Nick Vatamaniuc wrote:
John,

The way I do it is, is I ask myself 'is there a more common (basic)
base between the code paths or do they both have about a 50/50 chance
on average?' or 'will one code path be taken during an error and the
other one during the normal processing?'. If there is a clear single
common/usual/basic case or I try to detect an error I use 'try/except',
if it could go either way on average I use 'if'.
Thanks, that's something good to think about. This issue came up once
before and I remember someone saying something like "you're using a
try/except statement, but i wouldn't really consider that situation
'exceptional'", so thinking of it in your terms might help a lot.
Jul 28 '06 #5

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

Similar topics

4
2530
by: Nicolas Fleury | last post by:
Hi everyone, I'm wondering what is the easiest/cleanest way to look for existence of available methods/members. For example, in parsing a xml file, created objects can define a setXmlFilename function or a xmlFilename member to get the filename they are from. Right now I have the following code:
2
2924
by: Mike Button | last post by:
Hello all, I am really really desperate on what I should do, and I am asking for help from anyone in this newsgroup, here's the situation: I am creating a form that is being run on a server where there is no scripts allowed running (the software is from Opentext called Livelink)- therefore I need javascript to do the tasks listed below:...
7
6976
by: h7qvnk7q001 | last post by:
I'm trying to implement a simple server-side form validation (No Javascript). If the user submits a form with errors, I want to redisplay the same form with the errors highlighted. Once the form is correct I need to submit to another page that uses the form data. I first tried making the form submit action= field point to the same file....
0
1375
by: Tom | last post by:
I'm trying to adapt a function I'd written to insert arrays in MySQL to the ADOdb_lite class. The best way to do this would probably be to extend the ADOdb_lite class, but there doesn't seem to be a nice way to do that. So what I've done is created two wrapper functions: 1. wrapper_ado_cx($db_name='_default', $db_user='_default',...
17
3020
by: 2005 | last post by:
Hi In C++, are the following considered best practices or not? - passing aguments to functions (ie functions do not take any arguments ) - returning values using return statement Anything else? The reason for this question is that I had an assignment in which I was
13
1502
by: vizcayno | last post by:
Hello: Need your help in the "correct" definition of the next function. If necessary, I would like to know about a web site or documentation that tells me about best practices in defining functions, especially for those that consider the error exceptions management. I have the next alternatives but I think there are better: Alternative 1:...
17
1447
by: =?Utf-8?B?VGVycmFuY2U=?= | last post by:
Hello, I was wondering if someone can give me a few pointers in catching an exception correctly or at least making the code a little more elegant than what I have. I have a rss reader that I built in VB. When I read the contents from the xml file I create several labels controls that I place on the form at runtime. My problem is that some rss...
16
14717
by: skanemupp | last post by:
which is the best way to check if a string is an number or a char? could the 2nd example be very expensive timewise if i have to check a lot of strings? this value = raw_input() try: value = int(value)
4
10245
by: bukzor | last post by:
Does anyone have a pythonic way to check if a process is dead, given the pid? This is the function I'm using is quite OS dependent. A good candidate might be "try: kill(pid)", since it throws an exception if the pid is dead, but that sends a signal which might interfere with the process. Thanks. --Buck
0
7854
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7783
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7878
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8157
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5665
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5349
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3790
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2295
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1118
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.