Python Forum

Full Version: Teacher (thrown in at the deep end - help)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I'm self learning Python and I need some help (desperately) - I understand that I am double accounting in my simple program (I am adding the total for above 1.57 and also adding for below 1.92). I've spent time attempting to write a nested if statement (if index >=1.57 and <= 1.92) but it isn't working.

Can someone on here help me please?? Oh I'm using version 3 I understand the syntax is different in earlier versions.

total = 0
all_heights = [1.87, 1.48, 1.57, 1.91, 2.01]
for index in all_heights:
    if index >=1.57:
        total = total +1
    if index <= 1.92:
        total = total +1
print ("The total number of qualifying astronauts is ",total)

time.sleep (2)
print ("It's not is it - the program is double counting the total")
Welcome to Python and the forums!
First, please put your code in Python code tags and full error traceback message in error tags. You can find help here.
if height >=1.57 and height <= 1.92:
        total = total +1
or

if 1.57 <= height <= 1.92:
        total = total +1
Sorry just noticed this now

will do from now on

Thanks for that - so I needed to refer to the index reference on both sides of the and statement - sorry for asking stupid questions and I appreciate your help (it won't be the last time I will need it) 8-)
(May-22-2018, 12:35 PM)Mr90 Wrote: [ -> ]so I needed to refer to the index reference on both sides of the and
yes, that is right. or do it as my second example
Just use the second example. This is more pythonic and better to read.

if min_val <= current_val <= max_val:
    pass
This allows also current_val == min_val or current_val == max_val.
If the min/max value should be outside of the range, use the < operator instead.