Python Forum
Teacher (thrown in at the deep end - help) - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Teacher (thrown in at the deep end - help) (/thread-10471.html)



Teacher (thrown in at the deep end - help) - Mr90 - May-22-2018

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")


RE: Teacher (thrown in at the deep end - help) - j.crater - May-22-2018

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.


RE: Teacher (thrown in at the deep end - help) - buran - May-22-2018

if height >=1.57 and height <= 1.92:
        total = total +1
or

if 1.57 <= height <= 1.92:
        total = total +1



RE: Teacher (thrown in at the deep end - help) - Mr90 - May-22-2018

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-)


RE: Teacher (thrown in at the deep end - help) - buran - May-22-2018

(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


RE: Teacher (thrown in at the deep end - help) - DeaD_EyE - May-22-2018

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.