Kuhuqo - 1 year ago 77
Python Question

How can I improve this if else statement?

I am developing a tool to simulate some electronics experiments. In one case, I am generating values for an LED of specified wavelength.

What I want to happen:

I want the initial 'introductory' text to play only one time, if it has been seen once - it won't be played again.

What is currently happening:

The 'introductory' text is skipped, and an input question which I want to be asked after the initial text plays immediately. I also want this input to display if the introductory text has already been shown.

Here's a code excerpt:

``````def LED():
while True:
breaker = False
seen = 1
while True:
if seen < 1:
print("LEDS - Light Emitting Diodes")
print("")
time.sleep(1)
play = 0
print("Photons are created when an electron drops down a quantum level. To excite it, we need a diode voltage.")
time.sleep(1)
print("The required diode voltage for a RED LED (620nm) is 1.5V")
time.sleep(1)
print("The required diode voltage for a GREEN LED (500nm) is 2.5V")
time.sleep(1)
print("The required diode voltage for a BLUE LED (450nm) is 3.2V")
time.sleep(0.5)
print("LEDs are fabricated to work at a particular current, in this case 20mA. So we'll need a resistor")
seen += 1
break
else:
g = raw_input("Would you like to continue LEDs? [Y/N]: ")
if g == "n" or g == "N":
breaker = True
break
else:
while True:
while True:
print("Enter N to quit")
choice = raw_input("Please select a hue, RED, GREEN, or BLUE: ")
choice = (choice.lower())
if choice == "n":
breaker = True
print("Exiting")
break
``````

FIXED:

``````def LED():
breaker = False
seen = 1
while True:
while True:
if seen <= 1:
print("LEDS - Light Emitting Diodes")
print("")
time.sleep(1)
``````

You started `seen` at 1:

``````seen = 1
``````

So the test

``````if seen < 1:
``````

is never true.

You could just as well make it a Boolean:

``````seen = False

if not seen:
seen = True
``````

as you only need to toggle once.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download