简体   繁体   中英

My if-else statement isn't working with the list I used

So I entered 3 as my eye color (green) and it displays "You are a optimistic person" instead of "you are a curious person". Why is this? Isn't it supposed to display the else?

eyeList = ["blue", "brown","green","hazel","grey","none"]

print(eyeList)

eyecolor = int(input("Pick your eye color: "))

if eyecolor == 1 or 2:

  print("you are a  optimistic person")

else:
  print("you are a curious person")

Python syntax:

if condition:
    Indented expressions
elif condition2:
    Other expressions
else:
    Further expressions

You are simply missing the colons ( : ) after each condition.

Furthermore, to check if something is equal to something else, you have to use == . A single = performs an assignment.

if variable == 42:
    variable = 7

Finally, you cannot compare integers to strings ( input() function returns a string). In order to do it convert the string into an integer:

IntegerValue = int(stringFormat)

Final tip : your console gives you useful hints about what's wrong in the code. Listen to them.

  1. personality might be a string , use int(input(...)) to get an int
  2. you cannot compare int to string
  3. the equality operator is == , not =
  4. you need the colon : after every if or elif line

something like this might work:

myList = ["shy","sociable","loud"]
print(myList)
try :
    personality = int(input("Pick a trait from the list: "))
except ValueError :
    sys.exit("Invalid input: " + str(personality))

if personality == 0 :
  print("You are a person who doesn't doesn't like talking to other people")
elif personality == 1 :
  print("you talk to people, but aren't really loud")
elif personality == 2 :
  print("You love talking to people and you are very loud")

There are 3 issues:

a) Input is taken as string, you need to convert it in int

b) You put wrong syntax for checking, it should be two equal signs ==

c) Skip the : at the end of the if

Fixed code:

myList = ["shy","sociable","loud"]
print(myList)
personality = int(input("Pick a trait from the list: "))

if personality == 0:
  print("You are a person who doesn't doesn't like talking to other people")
elif personality == 1:
  print("you talk to people, but aren't really loud")
elif personality == 2:
  print("You love talking to people and you are very loud")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM