Python Forum
Nested if stmts in for loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Nested if stmts in for loop
#1
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]
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Bug Need help on this nested loop task PP9044 4 4,639 Apr-16-2021, 01:31 PM
Last Post: perfringo
  Nested for loop issue always using index 0 searching1 2 2,577 Dec-30-2018, 09:17 AM
Last Post: searching1
  nested while loop flow help Ponamis 4 2,960 Nov-02-2018, 11:22 PM
Last Post: Ponamis
  Nested loop Tryhard20 3 5,711 Sep-05-2018, 04:57 AM
Last Post: volcano63
  Nested Loop multiplication table SushiRolz 3 10,209 Feb-28-2018, 04:34 AM
Last Post: Larz60+
  Nested Loop to Generate Triangle Babbare 12 11,696 May-29-2017, 05:00 AM
Last Post: buran

Forum Jump:

User Panel Messages

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