我刚开始学习python并试图创建一个基本的while循环,但是当我运行它时,它不会运行elif语句,即如果userguess是==" tiger"它不打印"几乎" .. 作为我的新任何解释将不胜感激。感谢
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: ")
答案 0 :(得分:5)
这是因为您在到达raw_input
阻止之前正在调用if
两次。因此,在进行任何检查之前,用户必须输入两只动物。
guess an animal: tiger
guess an animal: tiger
almost, try again:
guess an animal:
如果您希望用户只需要猜一次,请将第二个raw_input
移动到循环的末尾。
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: ")
或者,将第二个raw_input
调用保留在原来的位置,并将第一个调用替换为虚拟值。
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: ")
您还可以完全删除初始分配,以及while循环的条件。因此,条件永远不会触发,因为当break
是"狮子"
animal
才到达块的末尾。
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: ")
第二种和第三种方式可能比第一种方式更可取,因为它们可以确保"你得到它"即使用户猜到了“狮子”,也会打印出来。在第一次尝试。