Python Forum
having an issue with nested if statements
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
having an issue with nested if statements
#7
You might want to simplify your design to reduce the number of nested if statements. Perhaps something like the following example code. I arbitrarily defined SINGLE, DOUBLE etc. to be numbers. You can define them to anything you like.
# State Machine Definitions
# Bit 0 = First Base
# Bit 1 = Second Base
# Bit 2 = Third Base
# Bit 3 = Run Scored
# Bit 4 = Run Scored
# Bit 5 = Run Scored
# Bit 6 = Run Scored

# Single = Multiply by 2 and add 1
# Double = Multiply by 4 and add 2
# Triple = Multiply by 8 and add 4
# Home Run = Multiply by 16 and add 8


FIRST = 1
SECOND = 2
FIRST_AND_SECOND = 3
THIRD = 4
FIRST_AND_THIRD = 5
SECOND_AND_THIRD = 6
BASES_LOADED = 7

SINGLE = 100
DOUBLE = 200
TRIPLE = 300
HOMER = 400

def get_new_state(old_state, runs, action):
    if action == SINGLE:
        new_state = old_state * 2 + 1
    elif action == DOUBLE:
        new_state = old_state * 4 + 2
    elif action == TRIPLE:
        new_state = old_state * 8 + 4
    elif action == HOMER:
        new_state = old_state * 16 + 8
    #    
    # Perform bitwise and on bits 3 thru 6
    runs_added = 0
    mask = 4
    for bit_number in range(3,7):
       mask *= 2
       if mask & new_state:
           runs_added += 1       
    #
    new_state = new_state & 7           
    runs += runs_added
    #
    return new_state, runs_added
    
team1runs=0
team2runs=0
new_state = 0

state = FIRST_AND_THIRD
action = TRIPLE   
print(" Old team1 state =  {}    runs = {}".format(state, team1runs)) 
state, team1runs = get_new_state(state, team1runs, action)
print(" New team1 state =  {}    runs = {}".format(state, team1runs)) 
Output:
Old team1 state = 5 runs = 0 New team1 state = 4 runs = 2
For more information about bitwise math see https://www.tutorialspoint.com/python/bi...xample.htm

Lewis
To paraphrase: 'Throw out your dead' code. https://www.youtube.com/watch?v=grbSQ6O6kbs Forward to 1:00
Reply


Messages In This Thread
RE: having an issue with nested if statements - by ljmetzger - May-08-2018, 12:25 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Nested for loop issue always using index 0 searching1 2 3,328 Dec-30-2018, 09:17 AM
Last Post: searching1
  Nested IF statements severnon1188 1 3,145 Oct-08-2017, 10:31 PM
Last Post: ichabod801
  Nested loops, lists and if statements Liquid_Ocelot 10 10,701 Apr-23-2017, 02:02 PM
Last Post: Mekire

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020