简体   繁体   中英

why wont the elif in my while loop work?

i just started learning python and tried making a basic while loop, but when i run it,it doesnt run the elif statement ie if the userguess is == "tiger" it doesnt print "almost".. as im new to this any explanation would be appreciated. thanks

animal = "lion"
userguess = raw_input("guess an animal: ")

while userguess != animal:
  userguess = raw_input("guess an animal: ")
  if userguess == animal:
    print("you got it")
    break
  elif userguess == "tiger":
    print("almost, try again: ")
  else:
    print("try again: ")

It's because you're calling raw_input twice before you reach the if block. So the user will have to enter two animals before any checking occurs.

guess an animal: tiger
guess an animal: tiger
almost, try again:
guess an animal:

If you want the user to only have to guess once, move the second raw_input to the end of the loop.

animal = "lion"
userguess = raw_input("guess an animal: ")

while userguess != animal:
  if userguess == animal:
    print("you got it")
    break
  elif userguess == "tiger":
    print("almost, try again: ")
  else:
    print("try again: ")
  userguess = raw_input("guess an animal: ")

Alternatively, leave the second raw_input call where it is, and replace the first call with a dummy value.

animal = "lion"
userguess = None

while userguess != animal:
  userguess = raw_input("guess an animal: ")
  if userguess == animal:
    print("you got it")
    break
  elif userguess == "tiger":
    print("almost, try again: ")
  else:
    print("try again: ")

You could also remove the initial assignment entirely, along with the while loop's conditional. As is, The condition is never triggering anyway because you always break before reaching the end of the block when animal is "lion".

animal = "lion"

while True:
  userguess = raw_input("guess an animal: ")
  if userguess == animal:
    print("you got it")
    break
  elif userguess == "tiger":
    print("almost, try again: ")
  else:
    print("try again: ")

The second and third ways may be preferable to the first, because they ensure that "you got it" will be printed even when the user guesses "lion" on their first try.

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