473,800 Members | 2,523 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

lots of nested if statements.

3 New Member
I'm writing a program which contains an awful lot of nested if statements. I don't know how efficient this is but it definetely makes the code less readable. Does anyone have any advice on how I can improve the following kind of code?

Apparently other languages have a switch statement which is useful here...Python seems to lack this functionality.

My Python is self-taught so I'd appreciate any outside input.

Lots of the code involves blocks of code like this:
Expand|Select|Wrap|Line Numbers
  1. for d1, d2, d3, d4, number in list:
  2.   if abs(d1-a1) < D1_tol:
  3.     if abs(d2-a2) < D2_tol:
  4.       if abs(d3-a3) < D3_tol:
  5.         if abs(d4) > abs(a4):
  6.           do_something
  7. for d1, d2, d3, d4, number in list2:
  8.   if abs(d1-a1) < D1_tol:
  9.     if abs(d2-a2) < D2_tol:
  10.       if abs(d3-a3) < D3_tol:
  11.         if abs(d4) > abs(a4):
  12.           do_something_else
  13.  
Feb 27 '07 #1
9 9330
dshimer
136 Recognized Expert New Member
If all those things have to be true at the same time how about "and", as a very simple example.

Expand|Select|Wrap|Line Numbers
  1. >>> a=1
  2. >>> b=2
  3. >>> c=3
  4. >>> if a>0 and b>0 and c>0:
  5. ...     print 'y'
  6. ... else: print 'n'
  7. ... 
  8. y
  9. >>> a=-1
  10. >>> if a>0 and b>0 and c>0:
  11. ...     print 'y'
  12. ... else: print 'n'
  13. ... 
  14. n
  15. >>> 
Feb 27 '07 #2
paulyche
3 New Member
Thanks for the reply.

I can use 'and' sometimes. However sometimes there are so many if's that they'd go off the end of the line if I used 'and' statements. That seems even less readable.
Feb 27 '07 #3
bartonc
6,596 Recognized Expert Expert
Thanks for the reply.

I can use 'and' sometimes. However sometimes there are so many if's that they'd go off the end of the line if I used 'and' statements. That seems even less readable.
You can break lines in Python
Expand|Select|Wrap|Line Numbers
  1. if varylongname1 and varylongname2 and varylongname2 and \
  2.     varylongname4 and varylongname5 and varylongname6:
Feb 27 '07 #4
bvdet
2,851 Recognized Expert Moderator Specialist
I'm writing a program which contains an awful lot of nested if statements. I don't know how efficient this is but it definetely makes the code less readable. Does anyone have any advice on how I can improve the following kind of code?

Apparently other languages have a switch statement which is useful here...Python seems to lack this functionality.

My Python is self-taught so I'd appreciate any outside input.

Lots of the code involves blocks of code like this:
Expand|Select|Wrap|Line Numbers
  1. for d1, d2, d3, d4, number in list:
  2.   if abs(d1-a1) < D1_tol:
  3.     if abs(d2-a2) < D2_tol:
  4.       if abs(d3-a3) < D3_tol:
  5.         if abs(d4) > abs(a4):
  6.           do_something
  7. for d1, d2, d3, d4, number in list2:
  8.   if abs(d1-a1) < D1_tol:
  9.     if abs(d2-a2) < D2_tol:
  10.       if abs(d3-a3) < D3_tol:
  11.         if abs(d4) > abs(a4):
  12.           do_something_else
  13.  
This may not be better, but is a little easier to read:
Expand|Select|Wrap|Line Numbers
  1. def compare_terms(*args):
  2.     evalList = []
  3.     for item in args:
  4.         evalList.append(eval(item))
  5.     return evalList
  6.  
  7. for d1, d2, d3, d4, number in lst:
  8.     if False not in compare_terms('abs(d1-a1) < D1_tol',\
  9.                                   'abs(d2-a2) < D2_tol',\
  10.                                   'abs(d3-a3) < D3_tol',\
  11.                                   'abs(d4) > abs(a4)'):
  12.         do_whatever
I suggest not using 'list' for a variable name since it masks Python's built in function 'list()'.
Feb 27 '07 #5
bartonc
6,596 Recognized Expert Expert
This may not be better, but is a little easier to read:
Expand|Select|Wrap|Line Numbers
  1. def compare_terms(*args):
  2.     evalList = []
  3.     for item in args:
  4.         evalList.append(eval(item))
  5.     return evalList
  6.  
  7. for d1, d2, d3, d4, number in lst:
  8.     if False not in compare_terms('abs(d1-a1) < D1_tol',\
  9.                                   'abs(d2-a2) < D2_tol',\
  10.                                   'abs(d3-a3) < D3_tol',\
  11.                                   'abs(d4) > abs(a4)'):
  12.         do_whatever
I suggest not using 'list' for a variable name since it masks Python's built in function 'list()'.
Nice catch on a keyword being used as a variable name. Very elegant coding! Thanks BV.
Feb 27 '07 #6
bvdet
2,851 Recognized Expert Moderator Specialist
Nice catch on a keyword being used as a variable name. Very elegant coding! Thanks BV.
My pleasure, just glad to be here. Pushing 2,000 posts Barton? Congrats and attaboys for all your hard work!
Feb 27 '07 #7
bvdet
2,851 Recognized Expert Moderator Specialist
This may not be better, but is a little easier to read:
Expand|Select|Wrap|Line Numbers
  1. def compare_terms(*args):
  2.     evalList = []
  3.     for item in args:
  4.         evalList.append(eval(item))
  5.     return evalList
  6.  
  7. for d1, d2, d3, d4, number in lst:
  8.     if False not in compare_terms('abs(d1-a1) < D1_tol',\
  9.                                   'abs(d2-a2) < D2_tol',\
  10.                                   'abs(d3-a3) < D3_tol',\
  11.                                   'abs(d4) > abs(a4)'):
  12.         do_whatever
I suggest not using 'list' for a variable name since it masks Python's built in function 'list()'.
After thinking about this again, the function is redundant:
Expand|Select|Wrap|Line Numbers
  1. for d1, d2, d3, d4, number in lst:
  2.     if False not in [abs(d1-a1) < D1_tol,\
  3.                      abs(d2-a2) < D2_tol,\
  4.                      abs(d3-a3) < D3_tol,\
  5.                      abs(d4) > abs(a4)
  6.                      ]:
  7.         do_whatever      
Feb 28 '07 #8
paulyche
3 New Member
Thanks for everyone's replies. I'll take a closer look at your suggestion bvdet and try it out.

I was only using 'list' as an example. Gedit does a good job of highlighting reserved words to keep me making too many newbie errors like that.

Once again, thanks for all your time.
Feb 28 '07 #9
bvdet
2,851 Recognized Expert Moderator Specialist
Thanks for everyone's replies. I'll take a closer look at your suggestion bvdet and try it out.

I was only using 'list' as an example. Gedit does a good job of highlighting reserved words to keep me making too many newbie errors like that.

Once again, thanks for all your time.
You are welcome. 'list' is not a reserved word like 'import', 'for', 'in', etc., but is a built-in function. 'list' can be used as a variable name. When the object reference to 'list' has decreased to zero, you would get the built-in function back.
Mar 1 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

3
6473
by: Tcs | last post by:
My backend is DB2 on our AS/400. While I do HAVE DB2 PE for my PC, I haven't loaded it yet. I'm still using MS Access. And no, I don't believe this is an Access question. (But who knows? I COULD be wrong... :) I've tried the access group...twice...and all I get is "Access doesn't like ".", which I know, or that my query names are too long, as there's a limit to the length of the SQL statement(s). But this works when I don't try to...
2
4319
by: Jim Irvine | last post by:
Does anybody know the limit of nested iif statements you can use in Access?
10
3247
by: nimmi_srivastav | last post by:
Below you will see an example of a nested conditional expression that this colleague of mine loves. He claims that it is more efficient that a multi-level if-else-if structure. Moreover, our complexity analyzer tool supposedly does not pick it up. Is it really more efficient? Personally I find this coding style extremely cryptic, misleading and error-prone. I believe that I have removed all traces of proprietary-ness from this coding...
1
2455
by: redpayne | last post by:
Ok-I am doing homework out of a book and the instructions are to display an interface with 5 option buttons in a frame. When clicked, each button changes the background color of the frame. It proceeds to tell me to construct CheckboxGroup, use FlowLayaout and add the Checkboxes to the frame along with ItemListener. It says addWindowListener()method, write code for itemStateChanged() which uses the getState() method and nested if statements....
1
3222
by: sql_er | last post by:
Hi all, I am trying to convert an SQL statement into an XPath (or a sequence of XPath) statements. More specifically, I have the following: SELECT a FROM b WHERE c IN (SELECT d FROM e) I recently learned about XPath and know how to perform simple filtering
2
7240
by: pradeep.thekkottil | last post by:
I'm setting up an auction website using PHP and MySQL. There in the section where logged in members can put up new auction in a form, I want to run a form validation where I used if else statements to check the fileds filled. In the form page there are two radio buttons - fixed and auction - (only one can be chosen) and depend upon which one is chosen some text should be inserted in the text fields. For that I'm using a validation where...
0
1295
by: Neil Cerutti | last post by:
The docs say: A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header's colon, or it can be one or more indented statements on subsequent lines. Only the latter form of suite can contain nested compound statements; the following is illegal, mostly because it wouldn't be clear to which if clause a following else clause would belong: if test1: if test2: print x
4
2670
by: Patrick A | last post by:
All, I rely on nested IF statements with multiple conditions heavily, and someone suggested recently writing the statements (and especially reading them months later) would be much easier if I used Case statements instead. I've read several different examples of Case statements, but can't quite figure out the syntax, or if they can be used when you need to test for a pair of conditions, as I am doing below.
2
3573
by: Ralf | last post by:
I have a custome request to print a gridview with lots of columns, 31 to be exact. I know how to print out a gridview, done it already for a GV with 6 columns. But, this GV is very wide and will not fit on a page. I looked into using a repeater, but couldn't figure it out. Tried datalists, no luck. Does anybody have an idea of how I can output the data where it will print. It doesn't have to output into a gridview, I just need it...
0
9690
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9550
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10501
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10273
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10250
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
10032
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9085
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7574
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5469
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...

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.