Python Forum
Nested if stmts in for loop - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Nested if stmts in for loop (/thread-16973.html)



Nested if stmts in for loop - johneven - Mar-22-2019

I'm completely flummoxed by this one.
Homework question follows:

Create an empty list called resps. Using the list percent_rain, for each percent, if it is above 90, add the string ‘Bring an umbrella.’ to resps, otherwise if it is above 80, add the string ‘Good for the flowers?’ to resps, otherwise if it is above 50, add the string ‘Watch out for clouds!’ to resps, otherwise, add the string ‘Nice day!’ to resps. Note: if you’re sure you’ve got the problem right but it doesn’t pass, then check that you’ve matched up the strings exactly.

Here's my attempt:
percent_rain = [94.3, 45, 100, 78, 16, 5.3, 79, 86]
resps = []

for x in percent_rain:
    if x>90:
        if x = True:
            resps.append("Bring an umbrella.")
    elif x>80:
        if x = True:
            resps.append("Good for the flowers?")
    elif x>50:
        if x = True:
            resps.append("Watch out for clouds!")
    else:
        resps.append("Nice day!")                 
    print(resps)
Here's error message:
[error]
SyntaxError: bad input on line 5
[error]


RE: Nested if stmts in for loop - ichabod801 - Mar-22-2019

That's an odd error message. Your syntax error is that you are using an assignment (=) in a conditional on lines 6, 8, and 12. You test equality with double equals (==), and you shouldn't test equality with True (instead of if x == True: use if x:). However you don't need any of those conditionals. You just need the x > conditionals and the final else. So get rid of lines 6, 8, and 12, and dedent the lines after them one level.


RE: Nested if stmts in for loop - xeedon - Oct-19-2019

Here is the correct code
percent_rain = [94.3, 45, 100, 78, 16, 5.3, 79, 86]
resps=[]
for x in percent_rain:
    if x>90:
        if x:
            resps.append('Bring an umbrella.')
    elif x>80:
        if x:
            resps.append('Good for the flowers?')
    elif x>50:
        if x:
            resps.append("Watch out for clouds!")
    else:
        resps.append('Nice day!')
        print(resps)