Nadia Nadia -4 years ago 108
Python Question

Why isn't my if statement working? (graphics.py related)

I'm creating a mini program & I'm trying to check whether the user inputs what I want them to -- They're only supposed to type one of the following: happy, sad, angry,nervous,excited but for some reason its ignoring that entire if statement and even the table (rectangle) I drew doesn't appear as well?

from graphics import *
win = GraphWin("Moods", 800, 500)

#Creating the input Box + A Go Button.
inputBox=Entry(Point(400,250),12)
inputBox.draw(win)
colour=inputBox.getText().lower()

message=Text(Point(400,50),"Click to go next!")
message.setFace('courier')
message.setSize(20)
message.draw(Win)
submsg1=Text(Point(400,100),"")
submsg1.setText("(Allowed moods are: Happy, Sad, Angry, Nervous,
Excited)")
submsg1.setFace('courier')
submsg1.setSize(15)
submsg1.setStyle('italic')
submsg1.draw(win)

clickPoint = win.getMouse()

#Checking user inputs the right way.
if not colour.isalpha():
error=Text(Point(400,300),"Please type either: happy, sad, angry")
error.draw(win)
elif (colour !="happy" or colour !="sad" or colour !="angry"):
error=Text(Point(400,300),"Please type either: happy, sad, angry")
error.draw(win)
else:
#Clearing Second Frame, for next screen.
inputBox.undraw()
goButton.undraw()
error.undraw()
message.undraw()
submsg1.undraw()

#Moving to next frame.
table=Rectangle(Point(50,400),Point(750,400))
table.setFill("blue")
table.draw(win)

Answer Source

Basically what is happening with your code is that this line here;

elif (colour !="happy" or colour !="sad" or colour !="angry"):

this will execute if one of the conditions is true because of how the or works. because one of them will always be true (because the user cannot enter happy and sad at the same time).

so for your example you will want the and function as then all of the conditions will have to be true for it to run.

elif (colour !="happy" and colour !="sad" and colour !="angry"):
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download